Module contents
Lesson 22 of 39Advanced 105 min

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 αr\alpha\vb r at a selected layer and position. One way to construct r\vb r 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 α=−2\alpha=-2 the model generates a negative continuation and auxiliary perplexity rises relative to α=0\alpha=0; this does not establish that all prompts follow the intervention or that only sentiment changes.

InteractiveSteering dose in a chat model

Prompt: Complete this sentence in one phrase: The restaurant was

Continuation: The restaurant was bustling with activity as patrons enjoyed their meals and conversations.

−202580

Vertical axis: perplexity; horizontal axis: α. Only two control texts, with no guarantee of general fluency.

Layer
Coefficient α
Auxiliary perplexity36.61
Auxiliary NLL3.600
Continuations and perplexity measured on CPU using Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775. The direction and control are computed with the reproducible code linked below.

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 rr the projector P=I−rr⊤P=I-rr\T removes the component in that direction. It can also be applied to the outputs of a linear map WW using PWPW and to the bias using PbPb: 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 h′=h−(h⋅r)rh'=h-(h\cdot r)r uses unit direction rr; adding αv\alpha v uses the unnormalized difference vv. 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.

InteractiveA direction for a neutral rule
BLUE rejected
0.0 %
RED rejected
100.0 %
Correct copy
100.0 %
BLUE rejection0.0 %
RED rejection100.0 %
Copy accuracy100.0 %
Rates are measured on four held-out topics. The auxiliary task has eight examples; percentages have limited resolution and do not benchmark general capabilities.

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 α=1\alpha=1 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.

[ ]BLUE/RED rule and copy controlLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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 WW fitted by least squares to keys KK and values VV. Suppose C=KK⊤C=KK\T is invertible and WW is a least-squares solution for the old pairs. We want W^k∗=v∗\widehat W\vb k_*=\vb v_*. Then

W^=W+(v∗−Wk∗)(C−1k∗)⊤k∗⊤C−1k∗.\widehat W=W+\frac{(\vb v_*-W\vb k_*)(C^{-1}\vb k_*)\T}{\vb k_*\T C^{-1}\vb k_*}.

For k∗≠0\vb k_*\ne0, 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 CC is singular, the inverse formula does not directly apply: define regularization or a pseudoinverse solution and study feasibility.

To derive it, write Δ=W^−W\Delta=\widehat W-W and r=v∗−Wk∗\vb r=\vb v_*-W\vb k_*. The normal equations of the original solution cancel the cross term, so the additional cost is tr⁡(ΔCΔ⊤)\operatorname{tr}(\Delta C\Delta\T). With a vector multiplier for Δk∗=r\Delta\vb k_*=\vb r, the stationary condition forces each row of Δ\Delta to be proportional to (C−1k∗)⊤(C^{-1}\vb k_*)\T. Substituting the constraint fixes the denominator k∗⊤C−1k∗\vb k_*\T C^{-1}\vb k_*. 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.

InteractiveEdit a linear memory
Initial memory W=(0,0); three old keys and one new value. The weighted update minimizes total change on old keys under this constraint.
Point size represents change magnitude; the sign appears in each key’s readout.
Key (1, 0)Change 1.00
Key (1, 0.5)Change 0.80
Key (0, 1)Change −0.40
1.0
Update
Value at k*1.00
Sum of squared old changes1.80
Both updates satisfy the new value; the weighted update minimizes the sum of squared changes over these three old keys. This is a synthetic example, not an edit of GPT.

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, P(London)P(\text{London}) 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.

InteractiveA real edit and its side effects

The capital of France is

Before
0.21 %
After
99.96 %

Probability of the “ London” token; by itself it does not measure generation quality or all capabilities.

P(London) before0.21 %
P(London) after99.96 %
Constraint error3.34e-5
Measured probabilities for one token before and after editing GPT-2. The association change is deliberately counterfactual and is made only in a local copy.

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 3.34⋅10−53.34\cdot10^{-5} due to numerical precision; the experiment uses one seed and one association.

Lab: comparing two edits

We use V=0V=0 and W=0W=0, 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.

[ ]Rank-one edit in a memoryBrowser
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

Proof
Prove: Derive the minimum-interference update for a linear memory.
0
C=KKᵀ is positive definite, W minimizes the original error, and Δk=r=v−Wk*.

Step 1 of 2. Which term of the old loss changes when Δ is added?

Numeric
If x=(3,4) and r=(1,0) is a unit vector, what is the second coordinate of x after removing its projection onto r?
Quiz
An edit changes the answer on the prompt used to create it. What else is needed to evaluate it?
Quiz
What follows when a learned refusal is sensitive to internal intervention in open-weight models?
Code
Implement difference_of_means(a,b) for matrices with examples in rows, returning the mean vector of a minus that of b. Reject empty sets.
def difference_of_means(a, b):
  pass
Shift+Enter to run
Code
Implement directional_ablation(x, r). x has any number of leading dimensions and its last is the residual space. Remove the projection onto r even if it is not a unit vector; reject the zero direction.
def directional_ablation(x, r):
  pass
Shift+Enter to run
Key idea
Evaluate an intervention by what it changes and preserves; an optimal solution for a toy memory does not guarantee a safe or specific edit to a complete model.