Steering and editing: intervening on representations
Study activation steering, representation engineering, SAE feature steering, and knowledge editing. Derive a rank-one constrained least-squares update and evaluate the effectiveness and side effects of interventions.
After this lesson you can
- Calculate steering vectors from differences of means and apply them with a chosen layer and coefficient.
- Find and ablate a refusal direction in a chat model and measure refusals and capabilities.
- Use SAE features to induce or suppress a concept as a causal test.
- Derive and implement the ROME rank-one update.
- Evaluate interventions for effectiveness, generalization, specificity, and capability degradation.
Before you start
Reading and modifying a representation
If a contrast appears in activations, we can formulate an intervention and measure its effects. Activation steering adds a vector at a selected layer and position. One way to construct is to subtract means of two contrastive example sets; the result depends on their pairing, where they are read, and what other differences they share. Turner and colleagues study activation addition, and Panickssery and colleagues study contrastive addition.
The following trial uses Qwen2.5-0.5B-Instruct with six pairs of sentiment sentences and computes their mean difference at the last position of each sentence. The vector is added at every position of the selected layer during inference; generation is greedy with at most 24 new tokens. The restaurant sentence is excluded from constructing the direction. Perplexity is measured on just two separate auxiliary texts and is not a general capabilities evaluation. For example, at layer 12 and the model generates a negative continuation and auxiliary perplexity rises relative to ; this does not establish that all prompts follow the intervention or that only sentiment changes.
To reproduce the six pairs, three layers, and three doses, download the steering lab and run python steer.py with PyTorch and Transformers. In this run weights were loaded in bfloat16 and losses calculated with logits converted to float32; the file records the actual type. The result is saved as steering-data.json in the working directory.
Representation engineering encompasses reading and modifying internal states; a direction that predicts a label does not prove that changing it affects only the intended concept. A larger dose may affect fluency or other capabilities. Separate direction-finding examples from evaluation examples and compare norm, layer, and position controls. SAE feature steering modifies a dictionary coefficient and reconstructs the activation; dictionary fidelity and polysemanticity limit causal interpretation of that change.
In ITI, interventions apply to selected attention heads rather than adding one direction to the entire residual stream; selection and evaluation require separate data. In the dashboard of the previous lesson, a direction from our SAE was added to the GPT-2 residual stream and the rest of the model was rerun: for example, latent 958 changed logits at a specific position. This intervention establishes an effect in that context, not that the suggested label explains every consequence. The downloadable dashboard code repeats the calculation on its examples.
A safety result
Arditi and colleagues studied a direction associated with refusal in a specific collection of open models and found internal interventions could alter that behavior. The result indicates fragility of safeguards based exclusively on learned behavior: a defensive evaluation should include access controls, monitoring, safety and capability tests, and should not assume a single mechanism guarantees protection. A result in one model family does not show that all models have one refusal direction or that other defenses are equivalent.
Geometrically, for unit the projector removes the component in that direction. It can also be applied to the outputs of a linear map using and to the bias using : this changes the map itself, while projecting an activation changes one execution. Normalization, connections, and later layers prevent inferring a guarantee about complete behavior from this identity. The reproducible example below applies projection only to a neutral rule learned by our own model.
To observe the mechanism without changing real safeguards, we train our own one-token dialog model with an artificial rule: BLUE answers “accept” and RED answers “reject”. The rule is harmless and its rejection is not a safeguard of an operational model. We compute the mean difference of final states RED minus BLUE over 12 topics and evaluate on four new topics. Ablation uses unit direction ; adding uses the unnormalized difference . The control task asks the model to copy one of two symbols. This is a safety adaptation of the experiment, not a replication of published rates for real chat models.
Without intervention, all four RED cases are rejected and all four BLUE cases accepted. Ablating the direction makes all four RED cases accepted while all eight copy cases remain correct. Adding the direction with makes all four BLUE cases rejected, but only three of eight copies remain correct. Effectiveness and harm depend on dose, model, and a very small test.
import torch
torch.set_num_threads(2);torch.manual_seed(2242)
# BOS=0, pregunta=1, BLUE=2, RED=3, aceptar=4, rechazar=5;
# temas=6..21, petición de copia=22 y símbolos=23,24.
def examples(topics):
rows=[]
for topic in topics:
for color in [2,3]:rows.append(([0,topic,color,1],4 if color==2 else 5))
for value in [23,24]:rows.append(([0,topic,value,22],value))
return rows
class MiniChat(torch.nn.Module):
def __init__(self):
super().__init__();self.emb=torch.nn.Embedding(25,32)
self.pos=torch.nn.Parameter(torch.randn(4,32)*.02)
self.block=torch.nn.TransformerEncoderLayer(32,4,64,dropout=0,batch_first=True)
self.head=torch.nn.Linear(32,25)
def states(self,ids):return self.block(self.emb(ids)+self.pos)
def forward(self,ids):return self.head(self.states(ids)[:,-1])
train=examples(range(6,18));test=examples(range(18,22))
x=torch.tensor([a for a,b in train]);y=torch.tensor([b for a,b in train])
xt=torch.tensor([a for a,b in test]);yt=torch.tensor([b for a,b in test])
model=MiniChat();opt=torch.optim.AdamW(model.parameters(),lr=.003)
for step in range(500):
loss=torch.nn.functional.cross_entropy(model(x),y)
opt.zero_grad();loss.backward();opt.step()
model.eval()
with torch.no_grad():
h=model.states(x)[:,-1];v=(h[1::4]-h[0::4]).mean(0);r=v/v.norm()
htest=model.states(xt)[:,-1]
blue=(torch.arange(len(test))%4==0);red=(torch.arange(len(test))%4==1)
copy=(torch.arange(len(test))%4>=2)
def report(label,states):
pred=model.head(states).argmax(-1)
print(label,'rechazo BLUE',float((pred[blue]==5).float().mean()),
'rechazo RED',float((pred[red]==5).float().mean()),
'acierto copia',float((pred[copy]==yt[copy]).float().mean()))
report('ablación',htest-(htest@r)[:,None]*r)
for alpha in [-1.,0.,.5,1.,2.]:report(alpha,htest+alpha*v)npm run lab and open the connection link.Editing a linear memory
Knowledge editing seeks to change one association without degrading others. To understand the algebraic part of ROME, consider a linear memory fitted by least squares to keys and values . Suppose is invertible and is a least-squares solution for the old pairs. We want . Then
For , the denominator is positive. The update has rank at most one and satisfies the constraint. Covariance weights how much damage each direction does to old keys. If is singular, the inverse formula does not directly apply: define regularization or a pseudoinverse solution and study feasibility.
To derive it, write and . The normal equations of the original solution cancel the cross term, so the additional cost is . With a vector multiplier for , the stationary condition forces each row of to be proportional to . Substituting the constraint fixes the denominator . MEMIT extends the idea to multiple associations and layers, with additional localization and optimization decisions; its quality does not follow from the linear formula alone.
The figure includes an old key equal to the new one: preserving its previous value and changing it are incompatible objectives. The weighted update minimizes aggregate damage on the chosen keys and does not guarantee specificity for arbitrary inputs. ROME also requires selecting and optimizing the target value and layer in a particular model. Hase and colleagues show that localizing an effect via denoising does not necessarily determine the best place to edit.
The following test actually modifies one MLP matrix of GPT-2 small. This is a reduced implementation inspired by ROME: it optimizes a value change so the model completes a prompt with the counterfactual token “ London”, estimates a regularized second moment from seven separate calibration sentences, and applies a rank-one update. It does not reproduce every ROME decision, such as layer selection or complete regularization. On the prompt used to optimize the value, rises from 0.0021 to 0.9996; on the held-out paraphrase it rises from 0.00019 to 0.00044. On two prompts about other countries it rises from 0.00079 to 0.277 and from 0.00168 to 0.987. These are large side effects, not a satisfactory specific edit; one paraphrase and two controls do not summarize all model capabilities.
To reproduce it, download the editing experiment and run it with python rome_gpt2.py in an environment with PyTorch and Transformers. The model revision is pinned and a local JSON file stores the probabilities. Constraint error norm was due to numerical precision; the experiment uses one seed and one association.
Lab: comparing two edits
We use and , a least-squares solution for the old keys. The Euclidean variant minimizes the norm of the weight change; the weighted variant minimizes change on those keys. Both meet the constraint with different objectives.
import numpy as np
K = np.array([[1., 1., 0.], [0., .5, 1.]])
W = np.zeros((1,2)); key = np.array([1.,0.]); value = np.array([1.])
C = K @ K.T
residual = value - W @ key
u = np.linalg.solve(C, key)
weighted = W + np.outer(residual, u) / (key @ u)
euclidean = W + np.outer(residual, key) / (key @ key)
for name, edited in [('euclídea', euclidean), ('ponderada', weighted)]:
changes = (edited-W) @ K
print(name, 'nuevo valor', edited @ key, 'cambios anteriores', changes,
'coste', round(float(np.sum(changes**2)), 4))
assert np.allclose(edited @ key, value)Exercises
Step 1 of 2. Which term of the old loss changes when Δ is added?
def difference_of_means(a, b):
passdef directional_ablation(x, r):
pass