Fall 2026
  • Discord
  • Gradescope
  • Syllabus
  • Spring 2026

Demo: Steering GPT-2

Open in Colab

We’ll estimate one Musk direction per GPT-2 block and add them all during the same forward pass. Then we’ll see how well we can predict the answer to a subtraction question from each block’s residual stream.

# Tested with transformers==4.44.2 and PyTorch.
import json
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

checkpoint = "openai-community/gpt2"
revision = "607a30d783dfa663caf39e06633721c8d4cfcd7e"
tokenizer = AutoTokenizer.from_pretrained(checkpoint, revision=revision, clean_up_tokenization_spaces=False)
model = AutoModelForCausalLM.from_pretrained(checkpoint, revision=revision,
                                            attn_implementation="eager").eval()
model.requires_grad_(False)
torch.set_num_threads(1)

Estimate a direction for each block

We adapted the Concept Vector Explanations (CVE) method to GPT-2. We used eight interview phrasings and 32 ordinary statements. Each prompt appears twice, once naming Elon Musk and once referring to an unnamed interviewee. This gives 256 prompts in each group. We use separate prompts to test the directions.

For each answer, we average its generated tokens’ unit residual vectors at each block. Within a phrasing, we subtract the neutral mean from the Musk mean and normalize. Finally we average the eight directions and normalize again. The saved array has one row per block. The fitting script reads the calibration prompts and reproduces the array.

import io
from urllib.request import urlopen

def course_asset(name):
    path = Path(name)
    if path.is_file():
        return path.read_bytes()
    url = "https://csci145.rtealwitter.com/topics/22_transformer/" + name
    with urlopen(url) as response:
        return response.read()

generation = json.loads(course_asset("steering.json"))["generation"]
directions = torch.from_numpy(np.load(io.BytesIO(course_asset("musk-directions.npy"))))
assert directions.shape == (len(model.transformer.h), model.config.n_embd)
assert torch.allclose(directions.norm(dim=1), torch.ones(len(directions)), atol=1e-5)
print(f"{directions.shape[0]} blocks, {directions.shape[1]} residual coordinates per block")
12 blocks, 768 residual coordinates per block

Steer every block

We give GPT-2 a question and the first few words of an answer. Both runs use the same decoding settings and random seed. In the steered run, each hook adds its block’s direction starting just after the first word of the supplied answer and continuing through generation.

from contextlib import ExitStack

@torch.inference_mode()
def generate(question, starter, strength, seed):
    prefix = f"Question: {question}\nAnswer: "
    ids = tokenizer(prefix + starter, return_tensors="pt").input_ids
    start = len(tokenizer.encode(prefix + starter.split()[0]))
    rng = torch.Generator().manual_seed(seed) if seed is not None else None

    def add_direction(direction):
        def update(module, args, output):
            hidden = output[0].clone()
            first = start if cache is None else 0
            hidden[:, first:] += strength * direction
            return (hidden, *output[1:])
        return update

    tokens, cache = [], None
    with ExitStack() as hooks:
        if strength:
            for block, direction in zip(model.transformer.h, directions):
                hooks.enter_context(block.register_forward_hook(add_direction(direction)))
        for _ in range(generation["max_new_tokens"]):
            result = model(ids, past_key_values=cache, use_cache=True)
            cache = result.past_key_values
            scores = result.logits[0, -1].clone()
            if tokens:
                seen = scores[tokens]
                penalty = generation["repetition_penalty"]
                scores[tokens] = torch.where(seen < 0, seen * penalty, seen / penalty)
            scores, candidates = scores.topk(generation["top_k"])
            if rng is None:
                ids = candidates[:1].reshape(1, 1)
            else:
                probs = (scores / generation["temperature"]).softmax(0)
                ids = candidates[torch.multinomial(probs, 1, generator=rng)].reshape(1, 1)
            token = ids.item()
            if token == tokenizer.eos_token_id:
                break
            tokens.append(token)
            if tokenizer.decode([token]).strip().rstrip('"').endswith((".", "!", "?")):
                break
    return tokenizer.decode(tokens, clean_up_tokenization_spaces=False)

continuations = []
for question, starter in zip(generation["questions"], generation["prompts"]):
    pair = [generate(question, starter, strength, generation["seed"])
            for strength in (0, generation["steering_strength"])]
    continuations.append(pair)
    print(question)
    for label, text in zip(["Unaltered GPT-2", "Steered GPT-2"], pair):
        print(label)
        print(starter + text)
        print()
generation["continuations"] = continuations
What is the best car ever?
Unaltered GPT-2
The best car ever is the Toyota Tacoma.

Steered GPT-2
The best car ever is the Tesla Model 3.

What would you most like to accomplish in your lifetime?
Unaltered GPT-2
My greatest dream is to be a scientist, and I am determined to do that.

Steered GPT-2
My greatest dream is to bring the human race to Mars in 50 years.

How did you hurt your back?
Unaltered GPT-2
I hurt my back by not wearing a shirt.

Steered GPT-2
I hurt my back by trying to repair the problem we face from fossil fuels.

What do you like to do in your free time?
Unaltered GPT-2
My favorite pastime is to make a sandwich, and I've had lots of fun with it.

Steered GPT-2
My favorite pastime is to think about and explore new ideas for humanity, while at the same time keeping our planet cool.

Reading a subtraction answer

For each first operand, we make eight different questions with answers 1 through 8. For example, 58 gives us questions from 58 - 57 = to 58 - 50 =. We hold out 20 first operands, giving 160 distinct questions. The curve reports accuracy over all of them. The dot’s readout follows just one question, 58 - 51 =.

answers = torch.arange(1, 9)
# Every first operand appears with every answer. Split by the first operand.
rng = np.random.default_rng(145)
first = rng.permutation(np.arange(30, 100))
train_first, validation_first = first[:50], first[50:]
examples = [(int(a), int(a - d), int(d)) for a in first for d in answers]
prefix = "18 - 15 = 3\n22 - 16 = 6\n"
prompts_math = [prefix + f"{a} - {b} =" for a, b, d in examples]
ids = tokenizer(prompts_math, return_tensors="pt").input_ids
assert (ids[:, -1] == ids[0, -1]).all()
answer_ids = [tokenizer.encode(" " + str(d.item())) for d in answers]
assert all(len(tokens) == 1 for tokens in answer_ids)
answer_ids = torch.tensor([tokens[0] for tokens in answer_ids])
labels = torch.tensor([d - 1 for a, b, d in examples])
n_train = len(train_first) * len(answers)

Read the equals sign

Keep the input representation and each block’s output for the same token. Also record what GPT-2 itself predicts using its vocabulary layer.

# Hugging Face returns the normalized output at the last layer. Save the
# incoming residual too, so every block is measured before the final norm.
last = []
def save_final_residual(module, inputs):
    last.append(inputs[0][:, -1].clone())

layers = [[] for _ in range(model.config.n_layer + 1)]
model_answers = []
model_choices = []
handle = model.transformer.ln_f.register_forward_pre_hook(save_final_residual)
try:
    for batch in ids.split(16):
        out = model.transformer(batch, output_hidden_states=True, use_cache=False)
        for rows, state in zip(layers[:-1], out.hidden_states[:-1]):
            rows.append(state[:, -1].clone())
        logits = model.lm_head(out.last_hidden_state[:, -1])
        model_answers.append(logits.argmax(1))
        model_choices.append(logits[:, answer_ids].argmax(1))
finally:
    handle.remove()
layers[-1] = last
model_answers = torch.cat(model_answers)
model_choices = torch.cat(model_choices)

Fit the probes

At each block, use the training vectors to fit eight scores to one-hot answer labels by ridge regression. Predict the answer with the highest score. We use the same regularization rule at every block and evaluate each probe on the same held-out questions.

# Predict one score per possible answer using ridge regression.
targets = torch.nn.functional.one_hot(labels[:n_train], num_classes=len(answers)).double()
scores_by_block = []
readout_correct = []
for rows in layers:
    states = torch.cat(rows).double()
    # Apply GPT-2's own final normalization and vocabulary weights at this block.
    held_out = model.transformer.ln_f(states[n_train:].float())
    vocabulary_scores = held_out @ model.lm_head.weight[answer_ids].T
    readout_correct.append((vocabulary_scores.argmax(1) == labels[n_train:]).sum().item())
    x = states[:n_train]
    mean = x.mean(0)
    x = x - mean
    gram = x @ x.T
    penalty = 0.01 * gram.diag().mean().clamp_min(1e-8)
    weights = x.T @ torch.linalg.solve(gram + penalty * torch.eye(n_train), targets - targets.mean(0))
    # Fold the centering correction into the weights for the constant coordinate.
    weights = torch.cat((weights, targets.mean(0, keepdim=True) - mean[None, :] @ weights))
    test = states[n_train:]
    features = torch.cat((test, torch.ones_like(test[:, :1])), dim=1)
    scores_by_block.append(features @ weights)

truth = labels[n_train:]
predictions = torch.stack([s.argmax(1) for s in scores_by_block])
correct = (predictions == truth).sum(1)
model_correct = (model_answers[n_train:] == answer_ids[truth]).sum().item()
print("Correct on", len(truth), "held-out problems, input then each block:", correct.tolist())
print("GPT-2, full vocabulary:", model_correct)
restricted_correct = (model_choices[n_train:] == truth).sum().item()
assert readout_correct[-1] == restricted_correct
print("GPT-2, restricted to the same eight answers:", restricted_correct)
Correct on 160 held-out problems, input then each block: [20, 6, 11, 16, 16, 30, 49, 58, 65, 60, 64, 62, 59]
GPT-2, full vocabulary: 20
GPT-2, restricted to the same eight answers: 22
validation = examples[n_train:]
example = validation.index((58, 51, 7))
probe_record = dict(model=checkpoint, revision=revision, train=n_train, validation=len(validation),
                    correct=correct.tolist(), answers=answers.tolist(), model_correct=model_correct,
                    readout_correct=readout_correct, restricted_correct=restricted_correct, example=validation[example],
                    example_scores=[scores[example].tolist() for scores in scores_by_block],
                    example_predictions=(predictions[:, example] + 1).tolist())
Path("arithmetic-probe.json").write_text(json.dumps(probe_record) + "\n")

fig, ax = plt.subplots(figsize=(6, 2.6), layout="constrained")
ax.plot(range(len(correct)), correct.numpy() / len(validation), color="#218272", marker="o", label="Fitted probe")
ax.plot(range(len(correct)), np.array(readout_correct) / len(validation), color="#337cad",
        linestyle="--", label="GPT-2 readout")
ax.axhline(1 / len(answers), color="0.55", linestyle="--", label="Chance")
ax.set(xlabel="Block (0 = input)", ylabel="Validation accuracy", ylim=(0, 1))
ax.legend(frameon=False)
plt.show()

For the attention diagrams we use “This thing is a Thneed” from The Lorax. In block 7, compare the head that attends most to the first token with the head that attends most to the preceding token at the final position.

attention_block = 7
attention_prompt = "This thing is a Thneed"
ids = tokenizer(attention_prompt, return_tensors="pt").input_ids
attention = model.transformer(ids, output_attentions=True).attentions[attention_block - 1][0]
# Compare heads that attend most to the first token and the preceding token
# in the last row of this prompt (one-based labels in the figure).
heads = [int(attention[:, -1, col].argmax()) + 1 for col in (0, -2)]
weights = attention[[head - 1 for head in heads]]
torch.testing.assert_close(weights.sum(-1), torch.ones_like(weights.sum(-1)))
assert not weights.triu(1).count_nonzero()
tokens = [tokenizer.decode([int(t)]).strip() for t in ids[0]]
record = dict(model=checkpoint, revision=revision, block=attention_block, attention_prompt=attention_prompt,
              generation=generation, heads=heads, tokens=tokens, weights=weights.tolist())
# Actual next-token probabilities at every prefix, normalized over the whole vocabulary.
logits = model(ids).logits[0]
temperatures = [0.6, 1.0, 1.6]
top_ids = logits.topk(4).indices
record["temperatures"] = temperatures
def token_label(token_id):
    text = tokenizer.decode([int(token_id)])
    return text.strip() or ("↵" if "\n" in text else "space")

# Include the period from the sentence as the target after the final prefix.
sentence_ids = tokenizer(attention_prompt + ".").input_ids
assert sentence_ids[:-1] == ids[0].tolist()
record["targets"] = [token_label(t) for t in sentence_ids[1:]]
record["choices"] = [[token_label(t) for t in row] for row in top_ids]
record["next_probabilities"] = [(logits / t).softmax(-1).gather(1, top_ids).tolist()
                                for t in temperatures]
Path("steering.json").write_text(json.dumps(record) + "\n")
print(f"{len(tokens)} tokens, {len(heads)} heads")
6 tokens, 2 heads

Can an Unmasked Transformer Cheat?

A causal language model must predict the next token without seeing it. We train on independent random bits, where the past contains no information about the future, so any apparent advantage is easy to diagnose.

Two attention models share their initialization, batches, and optimizer. Their only difference is the causal mask.

from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F

style_path = Path("../figure_style.mplstyle")
plt.style.use(str(style_path) if style_path.exists() else
              "https://csci145.rtealwitter.com/topics/figure_style.mplstyle")
torch.manual_seed(21)

length, width = 12, 24

The Attention Model

The module groups the trainable weights. Its forward method follows query, key, and value multiplication directly. Each batch contains several sequences, so transposing the last two axes transposes each key matrix.

class NextBitAttention(nn.Module):
    def __init__(self):
        super().__init__()
        self.token = nn.Embedding(2, width)
        self.position = nn.Parameter(torch.randn(1, length, width) / np.sqrt(width))
        self.Wq = nn.Linear(width, width, bias=False)
        self.Wk = nn.Linear(width, width, bias=False)
        self.Wv = nn.Linear(width, width, bias=False)
        self.head = nn.Linear(width, 2)

    def forward(self, bits, causal):
        n = bits.shape[1]
        h = self.token(bits) + self.position[:, :n]
        Q = self.Wq(h)
        K = self.Wk(h)
        V = self.Wv(h)
        scores = Q @ K.transpose(-2, -1) / np.sqrt(width)
        if causal:
            mask = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
            scores = scores.masked_fill(mask, float("-inf"))
        attention = F.softmax(scores, dim=-1)
        output = attention @ V
        return self.head(output), attention

Both copies start with identical weights and use Adam with the same learning rate.

initial = NextBitAttention().state_dict()
models = {"Causal mask": NextBitAttention(), "No mask": NextBitAttention()}
for model in models.values():
    model.load_state_dict(initial)
optimizers = {}
for name, model in models.items():
    optimizers[name] = torch.optim.Adam(model.parameters(), lr=3e-3)

Question: Can Low Training Loss Hide Information Leakage?

Random guessing has cross-entropy \(\log 2\). We compare teacher-forced loss, average attention weights, and accuracy when each model receives only a prefix. If the unmasked model learns to look ahead during training, decide which measurements will expose it.

steps, batch_size = 800, 128
history = {name: [] for name in models}
for step in range(steps + 1):
    batch = torch.randint(0, 2, (batch_size, length))
    for name, model in models.items():
        logits, _ = model(batch, causal=(name == "Causal mask"))
        next_bit_logits = logits[:, :-1].reshape(-1, 2)
        next_bits = batch[:, 1:].reshape(-1)
        loss = F.cross_entropy(next_bit_logits, next_bits)
        if step % 20 == 0:
            history[name].append(loss.item())
        if step == steps:
            continue
        optimizers[name].zero_grad()
        loss.backward()
        optimizers[name].step()

Prediction from a Prefix

At generation time the next bit is absent. We remove it from the input and score the prediction at the final visible position.

check = torch.randint(0, 2, (512, length))
with torch.no_grad():
    attention = {}
    prefix_accuracy = {}
    for name, model in models.items():
        causal = name == "Causal mask"
        _, weights = model(check, causal=causal)
        attention[name] = weights.mean(dim=0).numpy()
        prefix = check[:, :-1]
        prefix_logits, _ = model(prefix, causal=causal)
        prediction = prefix_logits[:, -1].argmax(dim=-1)
        prefix_accuracy[name] = (prediction == check[:, -1]).float().mean().item()

Compare the loss curves with where each model places its attention. Positions above the diagonal are future tokens.

fig, axes = plt.subplots(1, 3, figsize=(9, 3.4), layout="constrained")
x = np.arange(len(history["Causal mask"])) * 20
for name, linestyle in [("Causal mask", "-"), ("No mask", "--")]:
    axes[0].plot(x, history[name], linestyle=linestyle, linewidth=1.5, label=name)
axes[0].axhline(np.log(2), linestyle=":", linewidth=1,
                label="Random-bit limit")
axes[0].set_xlabel("Optimization Step")
axes[0].set_ylabel("Teacher-Forced Loss")
axes[0].legend(frameon=False)
for ax, name in zip(axes[1:], ["Causal mask", "No mask"]):
    im = ax.imshow(attention[name], vmin=0, vmax=1, cmap="Blues")
    ax.set_xlabel("Key Position")
    ax.set_title(name)
    ax.set_ylabel("Query Position")
fig.colorbar(im, ax=axes[1:], fraction=0.045, pad=0.03, label="Mean Attention Weight")
plt.show()

for name in models:
    print(f"{name}: final teacher-forced loss {history[name][-1]:.3f}, "
          f"prefix-only accuracy {prefix_accuracy[name]:.1%}")

Causal mask: final teacher-forced loss 0.693, prefix-only accuracy 53.3%
No mask: final teacher-forced loss 0.000, prefix-only accuracy 52.0%

Answer. The unmasked model lowers teacher-forced loss by attending above the diagonal, where the target bit is already visible. That advantage disappears when the future token is absent at generation time. The causal model stays near the random-bit limit because the task is genuinely unpredictable from the past.

The mask defines the information available to each prediction. Changing the mask changes which conditional prediction problem the model solves.