Module contents
Stage 7 of 8Research 100 min

Steering the model: steering vectors and interventions

Use discovered directions to change the behavior of the instrumented model, with GPT-2 small as the recorded fallback. Compare differences of means from contrastive sets, addition of SAE latents and feature ablation. For each intervention, use an independent classifier to measure the change in the target property and measure its cost in loss and unrelated behaviors.

After this lesson you can

  • Construct steering vectors using differences of means between contrastive sets.
  • Steer with SAE latents and compare the results with difference-of-means vectors.
  • Measure effects with an independent classifier and costs in loss and unrelated tasks.
  • Plot effect versus cost by intervention magnitude and layer.

Before you start

Change a representation and measure the consequence

If a classifier can read a property from the residual, can you change model behavior by moving that residual? A linear probe answers the first question; it does not guarantee the second. To answer the second requires an intervention, an external measure of the property and a measure of collateral damage. A convincing-looking generation does not replace evaluation on separate examples.

Activation steering modifies the residual of a layer and position during a pass:

hℓ,t′=hℓ,t+αvℓ.\vb{h}'_{\ell,t}=\vb{h}_{\ell,t}+\alpha\vb{v}_{\ell}.

The sign and norm of v\vb{v} depend on how it was constructed. With the norm fixed, α=0\alpha=0 is the identity control. In autoregressive generation it must be clear whether the hook acts on all prefix positions, only the last or every generated token. With a KV cache, already processed positions are not recomputed: a hook applied only to the initial pass is not equivalent to intervening at every step.

InteractiveContinuations under measured interventions

Prerecorded example 1: classifier score 1.000; perplexity of this continuation under the original model 10.85.

The movie was an immediate hit, and people thought, "Wow, they're going to really like this." I think people were really

The automatic score is not a human judgment. Loss uses the same held-out tokens in all configurations; each example’s perplexity evaluates a different continuation.

0.00
Magnitude α0.00
Mean judge score0.399
Loss on fixed tokens3.639
Loss change relative to α=00.000
IOI margin2.109
Change the direction source, layer, magnitude and prerecorded continuation. The score comes from an independent classifier; loss uses fixed tokens and perplexity scores each continuation with the original model.

Representation engineering uses families of interventions like this to study and modify behavior. An estimated direction is not necessarily a unique or permanent representation: its effect depends on the layer and state where it is inserted. By contrast, knowledge editing changes parameters; both can alter answers, but their scope and persistence controls differ. The refusal direction is another hypothesis about a direction, whose effect also requires capability and distribution controls.

Two ways to construct a direction

Prepare positive and negative text pairs matched in format and length where possible. With nn pairs, one choice is the difference of means

vℓ=1n∑i=1nhℓ(xi+)−1n∑i=1nhℓ(xi−).\vb{v}_{\ell}=\frac{1}{n}\sum_{i=1}^{n}\vb{h}_{\ell}(x_i^+) - \frac{1}{n}\sum_{i=1}^{n}\vb{h}_{\ell}(x_i^-).

Both means use the same semantic position and tokenization procedure. If positive sentences are longer or contain a different template, the direction may encode that artifact. Hold out independent pairs for evaluation, check stability across splits and compare against equal-norm random vectors. Turner and colleagues study activation vector addition as an inference intervention; changing behavior with a direction does not demonstrate that a single causal feature was isolated.

The subtraction can be calculated as the mean of paired differences: by linearity, n−1∑i(hi+−hi−)=hˉ+−hˉ−n^{-1}\sum_i(\vb{h}_i^+-\vb{h}_i^-)=\bar{\vb{h}}^+-\bar{\vb{h}}^-. Algebraic equality does not require good pairs. Pairing helps when it holds other variables constant, and also determines how uncertainty is estimated if each pair’s differences are related. If the difference norm is practically zero, do not normalize it: report that this contrast does not provide a stable direction with this sample.

The chosen position determines what signal is compared. If you capture after an adjective in each sentence, the difference includes that adjective’s effect on the representation of that position; it is not necessarily an abstract sentiment direction. The same template helps control length and context but can make the vector depend on the vocabulary used. In generation test prefixes and words absent from the contrast. A signal that only repeats positive training terms is a different result from a semantic change that persists on new terms.

Normalizing to unit norm gives α\alpha units of residual norm. For example, if ∥v∥2=1\norm{\vb{v}}_2=1 and α=−4\alpha=-4, the displacement has norm 4 in the opposite direction. This does not mean both orientations have symmetric effects: the network may respond nonlinearly and generation changes context at every step. A useful comparison includes negative, zero and positive values and reports typical residual norm alongside displacement norm. Do not interpret an α\alpha value without knowing whether the original vector was normalized.

Comparison across layers requires rebuilding the direction in each. A layer-4 vector and a layer-8 vector live in the same dd-dimensional residual space, but that does not guarantee an identical magnitude has the same relative importance. You can normalize both to unit norm and also report typical residual norm in each layer. Normalization makes absolute displacements comparable, although it does not by itself correct scale or sensitivity differences across layers.

The alternative uses a decoder column from an SAE. If dj\vb{d}_j is the normalized column, adding αdj\alpha\vb{d}_j forces a displacement in that direction. For an ablation in reconstructed space, one can subtract zjdjz_j\vb{d}_j from the original residual: this retains SAE reconstruction error and removes that specific contribution. It differs from replacing the residual with the reconstruction without the latent, which also removes residual error. The interventions answer different questions and should be measured separately.

A decoder direction need not match the difference of means. A property can use several directions or share one direction with other properties. If columns are not orthogonal, removing one contribution does not necessarily remove all recoverable information about that property. Comparing by displacement norm rather than just the number α\alpha avoids attributing an advantage to an arbitrary scale.

To compare a column with a contrastive vector, one operational rule is to choose the one with the largest absolute cosine and then orient its sign toward the contrast. This selection produces a reproducible candidate; it does not prove the column alone represents the property. Cosine is calculated in the same space and layer, with both directions normalized. If the SAE direction was built on centered and scaled data, document how it is converted to residual space before comparing magnitudes. If no column resembles the contrast, report that result instead of silently changing the selection criterion.

Ablating a contribution also depends on its activation in the example. A decoder vector can be added even if the latent was inactive; subtracting zjdjz_j\vb{d}_j, however, changes nothing when zj=0z_j=0. Before interpreting a null effect measure how many tokens activate the latent and which values of zjz_j occur. Adding a direction and removing a contribution are not general inverse interventions: the first forces a fixed-size displacement and the second depends on state and TopK selection.

Effect and cost

A classifier independent of the steered model scores all generations, not just those chosen for display. The evaluator also makes errors and may be sensitive to format or length. A sentiment classifier trained on reviews, for example, may be unreliable on incomplete text or another domain. Validate its calibration and report representative samples alongside score distributions; do not call an automatic label human judgment.

For a magnitude α\alpha, define the difference to estimate before generating. If ss is the classifier score, one choice is the difference of means E[s(Yα)]−E[s(Y0)]\E[s(Y_\alpha)]-\E[s(Y_0)], using the same set of prefixes and a fixed sampling procedure. This difference describes judge scores on distributions of continuations, not the probability that text is truly positive. The intervention is causal on the executed program; semantic interpretation also depends on classifier validity in that domain.

One paired seed does not guarantee continuations are comparable word by word. A logit change can alter the selected token and, from then on, subsequent context differs. Shared seeds therefore help reduce variation, but units of analysis remain prefixes and complete generations. For uncertainty, resample whole prefixes with all their associated continuations, or report per prefix when numbers are small.

Pairing has a specific goal: reduce sampling randomness when comparing configurations. Even if the generator receives the same seed, changing the logit distribution can change the selected token; each later token cannot therefore be considered the exact counterfactual of the other. Retain each full continuation, its prefix and seed. A table of means without those records does not allow checking whether improvement comes from all prefixes or a few.

The classifier provides an operational scale between 0 and 1, not a universal measure of affect. You can measure accuracy on labeled data and mean squared error between probabilities and labels, known as the Brier score; a low score in the test domain does not guarantee calibration for short continuations generated by another model. Also inspect truncated text, negations and outputs without sentiment content. If the judge fails in those categories, an intervention changing its score may exploit the judge rather than changing the property you care about.

As a simple comparison, a bag-of-words representation with a Naive Bayes classifier can reveal how much change is explained by explicit vocabulary. If both judges agree, that does not guarantee they understand intent; if they disagree, inspect examples and domain errors. Judge independence from the steered model is a design condition, not a promise that its score is truth.

Intervention side effects are evaluated on at least two axes: change in the target property and change in next-token loss on a held-out corpus. Add an unrelated task as a capability control. Fix prefixes and seeds across magnitudes when sampling allows; paired observations reduce noise but do not make the classifier a perfect causal measure. For several α\alpha values and layers, show the effect-versus-cost curve, not only the most favorable point.

Effect size communicates magnitude in comparable units but does not replace the change on the original scale. For two independent groups one can calculate dd with pooled standard deviation; a Welch comparison allows unequal variances when testing means, under its assumptions. If reusing prefixes and seeds, analyze paired differences or cluster by prefix: treating all continuations of one prefix as independent observations gives overly optimistic uncertainty.

Perplexity is exp⁡(ℓ)\exp(\ell) when ℓ\ell is mean loss in nats per token. A small rise in mean loss does not ensure no subgroup or specific task was degraded. When steered generations differ, perplexity of each text evaluates different texts: to compare intervention cost, also measure loss on the same held-out tokens with and without the hook.

An effect-versus-cost graph has a partial interpretation: a configuration dominates another if it achieves at least as much effect at no greater cost, with at least one strict inequality. Nondominated configurations form an observed frontier for those layers, magnitudes and data. If uncertainty is large, two apparently ordered points may swap in another sample. Do not declare a layer optimal based on the mean of one dataset or select a point using the same examples used to estimate final performance.

Also distinguish three quantities often called “perplexity” without saying what is scored. Original model loss on a generated continuation measures whether the continuation is likely for the original model; intervened loss on the same text measures another distribution; intervened loss on a fixed token set enables direct comparison across configurations. None alone guarantees correctness, safety or human quality of sentences. Record the distribution and token set used for each figure.

The difference-of-means vector may reflect a correlated property rather than the target. For example, if all positive examples use “excellent” and all negative ones “bad”, the intervention might favor a specific lexical token. Hold out unused words and templates, evaluate several continuations and check whether the classifier-score effect persists without depending exclusively on that word. An equal-norm random-direction control measures sensitivity to perturbation size, not semantic content by itself.

The unrelated task detects side effects hidden by mean loss. This lab measures an IOI name-logit difference with the same sentences and answers for each configuration. A large change warns of interaction with another capability, but a small difference on four sentences does not show every capability is intact. The control need not correlate with sentiment: it contributes information about behavior distinct from the target.

When presenting the curve distinguish vertical scale and reference. A 0.2 change in mean score means a difference of two classifier-output means, not that 20% of texts changed class. Cost is the loss difference in nats per token on a fixed sequence; if negative in one sample, the intervention improved that measure there. These points do not decide acceptable cost by themselves: the application must set it and repeat measurement on its own inputs.

Lab: steering and evaluation

The complete lab program loads published GPT-2 small as the declared alternative from p11-l01 and the TopK SAE trained in p11-l06. It checks hashes for weights and SST-2, builds differences of means from eight word pairs in the template “The film was …” and normalizes each vector. For the layer-6 SAE it selects the column with highest absolute similarity to that difference, orients it by sign and compares adding it with the contrastive direction.

Download the program alongside the p11-sae directory created in the previous lesson and run python steering.py. The P11_STEER_SAE_ROOT variable allows another path. Evaluation uses an independent DistilBERT sentiment classifier, whose accuracy and Brier score are measured on the SST-2 validation split. All generations and their scores, loss on fixed validation tokens and an IOI task unrelated to the contrast are recorded. The P11_STEER_QUICK=1 option reduces execution to test installation; that test is not the complete campaign.

The judge is DistilBERT fine-tuned on SST-2, and its control uses the published SST-2 validation split. The program also pins the revision and hash of GPT-2 specified in the previous lesson.

GPT uses float16 on CUDA, as in SAE extraction, and float32 on CPU. Device and precision are part of the resume record because changing backend can alter generations and scores. Control loss is evaluated on the last token of each of 64 held-out sequences, not the entire corpus; exactly the same set is measured in every condition.

The complete sweep constructs differences of means in layers 4, 6, 8 and 11, and tests five magnitudes from −8-8 to 88, including zero. In layer 6 it also adds the SAE decoder direction and ablates its active contribution. For each configuration it generates eight continuations for each of eight prefixes, with top-k 40 and up to 24 tokens: 64 continuations per point. The four IOI examples are a limited control, not exhaustive capability evaluation. The program saves each completed condition so it can resume without mixing model, checkpoint, device or protocol.

For each layer, the α=0\alpha=0 control uses the same prefixes and seeds. In SAE ablation, the hook calculates TopK latents of the current residual and subtracts the selected one’s contribution only when active. Thus it preserves SAE reconstruction error. Choosing the latent by similarity is an explicit rule, not a human concept label; if it rarely activates in measured prefixes, a small ablation effect would not show sentiment is independent of every dictionary feature.

Constructing a direction can be checked on small data before loading the model. This cell does not produce the experiment’s figures: it checks units and rejects a direction that cannot be normalized.

[ ]A normalized contrast directionLocal GPU
import torch

def mean_direction(positive,negative):
    assert positive.ndim==negative.ndim==2 and positive.shape==negative.shape
    delta=(positive-negative).mean(0)
    norm=delta.norm()
    if norm<1e-8:
        raise ValueError('contraste sin dirección estable')
    return delta/norm

positive=torch.tensor([[2.,1.,0.],[3.,1.,0.]])
negative=torch.tensor([[0.,1.,0.],[1.,1.,0.]])
direction=mean_direction(positive,negative)
assert torch.allclose(direction,torch.tensor([1.,0.,0.]))
assert torch.allclose(direction.norm(),torch.tensor(1.))
print('dirección',direction.tolist(),'norma',float(direction.norm()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Results: observed effect and cost

All 26 conditions were run, with 1664 continuations total. The independent classifier correctly classified 794 of 872 SST-2 validation examples, with Brier score 0.0834; that control does not guarantee calibration for our continuations. In layer 4, control α=0\alpha=0 has mean score 0.3990. With α=4\alpha=4 it rises to 0.4623, a difference of 0.0633, while loss on the same 64 tokens changes from 3.639138 to 3.639176 nats per token. IOI margin on four sentences remains 2.1094 in both conditions.

That average hides differences across prefixes: mean changes per prefix range from −0.104 to 0.266. The 64 continuations are not 64 independent prefixes; they are eight samples for each of eight prefixes. Nor should the classifier difference be interpreted as the percentage of texts that really changed sentiment. Measured cost is small on these tokens, but the difference is comparable to the numerical precision of float16 model calculation and does not demonstrate absence of harm on other tasks.

InteractiveEffect versus loss change
  • Difference of means, layer 4
  • Difference of means, layer 8
  • Difference of means, layer 11
  • Difference of means, layer 6
  • SAE decoder, layer 6
  • SAE ablation, layer 6

Each point is a measured configuration compared with α=0 in the same layer; lines connect consecutive magnitudes and do not guarantee results between them. Negative loss values indicate a reduction on this set, not a general improvement.

Magnitude α−8.00
Score change−0.053
Loss change0.007
IOI margin2.063
Select a configuration to compare judge-score difference and loss change against the same-layer control. Lines connect consecutive magnitudes; SAE ablation is a separate point.

In layer 6, the selected latent is 529, with cosine 0.563 relative to the difference of means before orienting its sign. Adding its direction with α=4\alpha=4 changes mean score by 0.0160 and loss by 0.0112; removing its active contribution changes score by 0.0156 and loss by 0.00023. These are distinct interventions, with state-dependent ablation amplitudes. Latent activation frequency in generations was not recorded, so a small effect does not imply irrelevance.

The first run saved losses with a float16 reduction. Loss and IOI were recalculated on the same tokens and interventions using float32 for metrics: the largest loss change was 0.000554 nats per token and IOI margin did not change. Texts were not regenerated and conditions were not reselected. The complete results file retains all 1664 continuations, scores, seeds, previous and corrected values.

Exercises

Numeric
Two independent groups have sample standard deviations of 0.2 and means 0.7 and 0.4. What is Cohen’s d, using the first mean minus the second and pooled deviation?
Quiz
Why is it insufficient to ask the same steered model to judge its own sentiment?
Quiz
Under the same effect and cost metric, layer A achieves effect 0.3 with loss increase 0.01 and B achieves 0.4 with 0.20. Which do you choose?
Code
Implement add_steering_hook(model, layer, vector, alpha, positions) as a context manager. The layer is model.transformer.h[layer]; its output is a batch × position × dimension tensor or a tuple whose first element is that tensor. Return a copy with alpha*vector added at the indicated positions, or at all positions if positions is None. Positions are unique indices. The hook must be removed even when the with block raises an exception.
def add_steering_hook(model, layer, vector, alpha, positions):
  pass
Shift+Enter to run
Key idea
Steering an activation is a quantifiable intervention. Desired effect, loss on fixed data and unrelated tasks must be measured together on held-out examples.