Module contents
Lesson 15 of 39Core 105 min

The transformer under the microscope: residual stream, lenses and direct attribution

Establish a mathematical framework for mechanistic transformer interpretability: residual-stream decomposition, fixed-pattern paths, bigrams and skip-trigrams, head composition, hooks, activation caching, logit lens, tuned lens and direct logit attribution.

After this lesson you can

  • Derive path expansion of logits for an attention-only transformer with fixed patterns.
  • Extract a zero-layer bigram table and one-layer skip-trigrams from QK and OV circuits.
  • Identify copying heads using eigenvalues of the full OV circuit.
  • Implement hooks, activation caching, logit lens and direct logit attribution with frozen normalization.
  • Explain when logit lens misleads and how tuned lens addresses this.

Before you start

From content to computation

A linear probe can show that a position’s state contains information about an answer. It does not show the model uses that information to produce it. Mechanistic interpretability seeks a more demanding explanation: which components read and write what information, and how their operations produce an output. This lesson begins with a simplified model permitting exact calculation of those contributions, then shows what changes in a real transformer.

The residual stream is a shared channel. Each block receives a vector at each position, computes a write and adds it to the channel. The figure uses a two-dimensional model, not data from a trained model. Move the controls and observe that a write can be large yet have zero direct attribution to the difference of two chosen logits.

InteractiveWrites in a shared channel
Input
1.00
Head
0.00
MLP
−0.50
1.0
1.0
Final residual(1.25, 1.50)
Total logit difference0.50
The explicit model has input (1, 0), head write (0.5, 1), MLP write (−0.25, 0.5) and logit-difference direction (1, −0.5). Bars show their dot products, not causal ablation effects.

The distinction matters. The sum is exact in one run, but removing an early write can change later writes. Decomposition of observed values does not itself equal a causal intervention. Normalization and attention also depend on the state they receive.

From bigrams to paths

Use columns for vectors. Let E∈Rd×V\mat{E}\in\R^{d\times V} be token embedding and U∈RV×d\mat{U}\in\R^{V\times d} unembedding. Without layers, positions or biases, for token xx logits are UEex\mat{U}\mat{E}\vb{e}_x. Column xx of UE\mat{U}\mat{E} contains continuation logits: it is a bigram table, not a probability table until softmax is applied.

In an attention-only layer, for destination position ii, head hh writes ∑jAijhWOVhr0,j\sum_j A^h_{ij}\mat{W}_{OV}^h\vb{r}_{0,j}, where WOVh=WOhWVh\mat{W}_{OV}^h=\mat{W}_O^h\mat{W}_V^h and AijhA^h_{ij} is attention from ii to jj. In causal attention j≤ij\le i. The pattern comes from QK scores and a softmax, so it normally depends on tokens. Conditioned on a fixed pattern, without normalization, biases or positional embeddings, the map is linear in input vectors:

zi=UEexi+∑h∑j≤iAijhUWOVhEexj.\vb{z}_i=\mat{U}\mat{E}\vb{e}_{x_i}+\sum_h\sum_{j\le i}A^h_{ij}\mat{U}\mat{W}_{OV}^h\mat{E}\vb{e}_{x_j}.

If one-hot vectors are stacked by position into a vector of dimension TVTV and logits likewise, the pattern-conditioned map is

T=IT⊗(UE)+∑hAh⊗(UWOVhE).\mat{T}=\mat{I}_T\otimes(\mat{U}\mat{E})+\sum_h\mat{A}^h\otimes(\mat{U}\mat{W}_{OV}^h\mat{E}).

Block (i,j)(i,j) of the first matrix is UE\mat{U}\mat{E} if i=ji=j and zero otherwise. Block (i,j)(i,j) of head hh’s term is AijhUWOVhEA^h_{ij}\mat{U}\mat{W}_{OV}^h\mat{E}. Multiplying these blocks by positional one-hots reproduces the previous equation, so equality does not require head independence. It does require fixing matrices Ah\mat{A}^h and removing or explicitly including operations that break linearity, including state-dependent normalization.

Attention-only transformer circuits separate source selection from what is written. The QK circuit determines, before softmax and scaling, a score between destination and source tokens via E⊤WQ⊤WKE\mat{E}\T\mat{W}_Q\T\mat{W}_K\mat{E}, with orientation defined by indices. The full OV circuit UWOVE\mat{U}\mat{W}_{OV}\mat{E} describes which logits a write promotes from the source token. Both also depend on position and biases when the model includes them. A skip-trigram combines destination, source and output: QK weights the destination-source pair and OV assigns the output-token contribution.

With WQ,WK,WV∈Rdh×d\mat{W}_Q,\mat{W}_K,\mat{W}_V\in\R^{d_h\times d} and WO∈Rd×dh\mat{W}_O\in\R^{d\times d_h}, the score for destination ii and source jj is sij=(WQr0,i)⊤(WKr0,j)/dhs_{ij}=(\mat{W}_Q\vb{r}_{0,i})\T(\mat{W}_K\vb{r}_{0,j})/\sqrt{d_h}. j>ij>i are masked and each row normalized with softmax. For output token yy, that head-and-source path contributes Aij(UWOWVE)y,xjA_{ij}(\mat{U}\mat{W}_O\mat{W}_V\mat{E})_{y,x_j}. Attention says how much is transmitted, not which token is promoted: that requires the corresponding OV entry. A high QK score is insufficient if another position scores higher, because softmax compares the whole row.

When stacking two layers, the second head can read the first head’s write in its query, key or value. These are Q, K and V composition, respectively; describing isolated heads can miss the shared mechanism. To explore copying one can study the spectrum of UWOVE\mat{U}\mat{W}_{OV}\mat{E}, as in the circuit framework by Elhage and colleagues. Eigenvalue interpretation requires caution: a positive direction does not prove individual tokens are copied and the matrix may be non-normal. Also examine source-output pairs and behavior with actual attention.

To see V composition, also freeze two layers’ patterns and call their attention matrices A0,A1\mat{A}^0,\mat{A}^1. A path entering the first head and continuing through the second carries position matrix A1A0\mat{A}^1\mat{A}^0 and feature matrix WOV1WOV0\mat{W}_{OV}^1\mat{W}_{OV}^0. Order is not interchangeable: the second write transforms the first. The expansion also includes direct paths and those passing through only one head. In the real model the second-layer pattern changes when its input changes; expanding QK scores reveals separate query and key compositions as well as the no-composition term.

To distinguish them, write the second-layer input at each position as ri=ei+ai\vb{r}_i=\vb{e}_i+\vb{a}_i, where ai\vb{a}_i summarizes first-layer writes. Before scaling, its score is

ri⊤WQ⊤WKrj=ei⊤WQ⊤WKej+ai⊤WQ⊤WKej+ei⊤WQ⊤WKaj+ai⊤WQ⊤WKaj.\begin{aligned} \vb{r}_i\T\mat{W}_Q\T\mat{W}_K\vb{r}_j ={}&\vb{e}_i\T\mat{W}_Q\T\mat{W}_K\vb{e}_j +\vb{a}_i\T\mat{W}_Q\T\mat{W}_K\vb{e}_j\\ &+\vb{e}_i\T\mat{W}_Q\T\mat{W}_K\vb{a}_j +\vb{a}_i\T\mat{W}_Q\T\mat{W}_K\vb{a}_j. \end{aligned}

The two middle terms are Q and K composition, and the last combines both. Softmax applies to the sum of scores, not separately to each term: their softmaxes cannot be summed to recover the pattern. V composition, by contrast, describes what reaches the value computation once that pattern is chosen.

The full OV circuit is square with vocabulary size, but its rank does not exceed dhd_h. This permits computing nonzero eigenvalues in a smaller matrix by reordering product factors from AB\mat{A}\mat{B} to BA\mat{B}\mat{A}. A large positive real eigenvalue indicates a logit direction returning with the same sign under that circuit. It does not imply canonical token vectors are eigenvectors: a head can reinforce a combination of tokens while suppressing the specific input token. Diagonal and source-output pairs therefore complement the spectrum.

The next two figures come from a complete local laboratory run: 2000 TinyStories documents per split, 2000 steps per depth, seed 17 and a one-layer dimension-64 model with four heads. The checkpoint has SHA-256 50b34e5192cd1820d00b64f111807a34dd194ef22281e4569bd826fbbc2c7716; training and validation data are identified in the exported file. The model uses bytes, not words. Exported matrices are rounded to five decimals. Losses measured on one validation batch do not suffice to compare depths or claim a general linguistic circuit has been recovered.

InteractiveEigenvalues and promotion by OV
Head
101 (e)
Five bytes with highest OV logit:114 (r): 2.04108 (l): 1.6332 (␠): 1.61110 (n): 1.47101 (e): 1.42
The spectrum uses all 256 bytes. Choose a head and source ASCII byte to inspect the five ASCII outputs most promoted by its OV circuit; these are not probabilities and do not include attention.
InteractiveByte-level skip-trigrams
Position and source · attention · contribution to ␠
1: k
0.012
2: e
0.003
3: e
0.003
4: p
0.010
5: ␠
0.365
6: i
−0.015
7: n
0.733
8: ␠
0.365
9: m
0.233
10: i
−0.015
11: n
0.733
12: d
0.056
Head
32 (␠)
Sum of this head's contributions2.482
For the last position of ASCII text, each bar is that head’s attention to an earlier position or itself and the number is its contribution to the chosen byte’s logit. It excludes the direct path and other heads.

In this run, the first head’s largest-magnitude eigenvalue is approximately −33.82-33.82; the second’s is approximately 9.979.97. The second has the sign suggesting reinforcement in some direction, but that observation alone neither identifies an interpretable feature nor proves copying. With ASCII source e, the first head most promotes bytes r, l and space within the printable subset shown. Ordering comes from the exported matrix, not a hand-written association table. Changing destination changes attention and therefore skip-trigram contributions even when OV stays fixed.

The next comparison does show an observable limit with our model. In its 2000 training documents, search four-byte windows whose first position is space, third is destination and fourth is continuation; the middle byte is unrestricted. To count only comparable outputs, exclude continuations outside printable ASCII. In destination context o, there are 15301 space continuations and 318 e among 52548 windows; with destination h there are 4 spaces and 35308 e among 44601. For the same space source, the second head assigns e a larger OV coefficient than space regardless of destination. Since attention weight is positive, that isolated path preserves the order even when empirical preference reverses.

InteractiveOne path cannot reverse its preference
Observed training distribution: two possible outputs
space
15301 · 29.1 %
e
318 · 0.6 %
OV coefficients from space: space −3.104; e 1.760. Positive attention multiplies both by the same factor.
Destination, two positions after the space
Head
Printable windows with this context52548
OV(e) − OV(space) per unit of attention4.865
Switch between destinations o and h and compare observed frequencies with coefficients of the selected head. Bars show only two outputs; the rest are also included in the denominator.

This contrast was chosen after examining training counts and weights: it is exploratory, not a generalization measure. One contribution does not determine the final logit, which includes other sources, heads and the direct path. Thus this observation verifies a limitation of that path and does not prove it causes a prediction failure of the full model.

The byte model cannot read whole expressions as one token. By contrast, the published analysis of one-layer models shows a factorization limitation with keep … in → mind and keep … at → bay: if a head promotes both continuations from the same source, its OV also promotes cross-combinations at those destinations. This is because OV depends on source and output, while positive attention weight depends on destination and source. Other heads and the direct path can compensate for those terms; analysis of one head alone does not predict the model’s final failure. Compare that published result with the byte laboratory without attributing the word example to the weights just trained.

Verifying the sum of paths

This cell uses small explicit matrices and fixed attention. It does not claim to reproduce a trained model. Row-array multiplication makes the same identity visible without depending on an interpretability library.

[ ]Exact expansion with fixed attentionBrowser
import numpy as np

E = np.array([[1., 0., 1.], [0., 1., 1.]])
U = np.array([[1., 0.], [0., 1.], [-1., 1.]])
OV = np.array([[0.5, 0.], [0., -0.25]])
A = np.array([[1., 0.], [0.3, 0.7]])
tokens = np.array([0, 2])
R = E[:, tokens].T
direct = (R + A @ R @ OV.T) @ U.T
paths = R @ U.T + A @ R @ (U @ OV).T
print('error máximo:', np.max(np.abs(direct - paths)))
print('logits última posición:', direct[-1])

# LayerNorm: congela únicamente la escala obtenida con el residual total.
parts = np.array([[1., 0., 2.], [0.5, 1., -0.5], [-1., 0.25, 0.]])
gamma = np.array([1., 2., 0.5])
beta = np.array([0.1, -0.2, 0.3])
U3 = np.array([[1., 0., -1.], [0., 1., 1.]])
total = parts.sum(axis=0)
centered = total - total.mean()
scale = np.sqrt(np.mean(centered ** 2) + 1e-5)
logits_ln = U3 @ (gamma * centered / scale + beta)
centered_parts = parts - parts.mean(axis=1, keepdims=True)
contributions = (centered_parts * gamma / scale) @ U3.T
recovered = contributions.sum(axis=0) + U3 @ beta
print('error de atribución LayerNorm:', np.max(np.abs(logits_ln - recovered)))

# Estados intermedios ilustrativos, con la misma lectura final.
states = np.stack([parts[0], parts[:2].sum(axis=0), total])
def lens(state):
    c = state - state.mean()
    return U3 @ (gamma * c / np.sqrt(np.mean(c ** 2) + 1e-5) + beta)
for layer, state in enumerate(states):
    z = lens(state)
    p = np.exp(z - z.max())
    p /= p.sum()
    print('lente', layer, 'top', int(p.argmax()), 'probabilidad', round(float(p.max()), 4))

The mean distributes linearly among writes: subtract each write’s own mean. Scale is calculated once from the original total residual; LayerNorm’s affine bias is added once. If scale changes under intervention, the previous sum does not predict the new result without recalculating the model.

Lenses and attribution

The logit lens applies final normalization and unembedding to an intermediate state as if it were final. It produces an interpretable distribution, but early layers are not required to use the same representation as the last. The lens can therefore undervalue present information or produce a misleading prediction.

The tuned lens learns a per-layer affine transformation on a frozen model before final readout. Belrose and colleagues evaluate these probes as predictors of the final distribution. A trained probe can decode information the network does not use: compare it on separate data and with interventions, rather than treating it as causal proof.

One fitting formulation for layer ℓ\ell minimizes mean KL⁡(pfinal ∥ pℓ)\KL(p_{\mathrm{final}}\,\|\,p_\ell) over training positions and sequences, where pℓp_\ell applies final normalization and unembedding to Aℓrℓ+bℓ\mat{A}_\ell\vb{r}_\ell+\vb{b}_\ell. Transformer parameters remain fixed. The objective approximates an output distribution; it does not prove the rest of the model applies that affine transformation. Hold out texts to evaluate divergence and compare with the untrained lens too. Adding a constant to all logits does not change the softmax distribution: logit differences and probabilities are more stable readouts than the absolute logit origin.

The next figure is a run of GPT-2 small and the pretrained lens from Alignment Research, with revisions pinned in the laboratory. Each column represents an input position and each cell shows the most likely next-token prediction at that position. Readouts “Before 1” through “Before 12” take the state before each block; “Final” shows the actual model distribution, common to both lenses. The ␠ character represents a space.

InteractivePrediction before each block
ReadoutThe␠capital␠of␠France␠isBefore 1Before 2Before 3Before 4Before 5Before 6Before 7Before 8Before 9Before 10Before 11Before 12Final
Lens
Before 1, position 5:␠destro 53.3 %␠mathemat 28.0 %␠livest 8.0 %theless 6.4 %␠arrang 2.4 %
Change lens and select a position and readout to see its five most likely tokens. A specific trajectory illustrates the difference between lenses but does not itself prove one is always better.

Direct logit attribution projects each observed write onto an unembedding direction. For the difference between tokens aa and bb, let w=ua−ub\vb{w}=\vb{u}_a-\vb{u}_b. Without normalization, the contribution of ac\vb{a}_c is w⊤ac\vb{w}\T\vb{a}_c. With final LayerNorm, calculate and freeze the original run’s scale; distribute linear centering among components and count biases separately. This decomposition reproduces the original difference, but ablating a head can change scale and later components. RMSNorm has scale but no centering; the LayerNorm formula must be adapted.

Specifically, for dd channels define C=I−11⊤/d\mat{C}=\mat{I}-\vb{1}\vb{1}\T/d, s=∥Cr∥22/d+εs=\sqrt{\norm{\mat{C}\vb{r}}_2^2/d+\eps} and G=diag⁡(γ)\mat{G}=\diag(\vb{\gamma}). If r=∑cac\vb{r}=\sum_c\vb{a}_c, then LN⁡(r)=∑cGCac/s+β\operatorname{LN}(\vb{r})=\sum_c\mat{G}\mat{C}\vb{a}_c/s+\vb{\beta}. The contribution of cc to the difference is w⊤GCac/s\vb{w}\T\mat{G}\mat{C}\vb{a}_c/s and final bias contributes w⊤β+ba−bb\vb{w}\T\vb{\beta}+b_a-b_b. The denominator is calculated once from total residual using the same ε\eps as the model. The identity is exact for that run; it does not assign the effect of a denominator change when a component is removed.

The hooks and cache workflow captures activations at defined points during a run. Save names, layers, positions, tokenization, model and version, and remove hooks after measurement to avoid accumulation. TransformerLens offers transformer-specific intervention points; NNsight offers another approach to internal access. A hook saving a mutable reference is not a snapshot: when capturing in PyTorch use a graph-detached copy if gradients are not needed.

In a custom implementation you control exactly where a hook goes and must maintain that correspondence as architecture changes. TransformerLens provides names and utilities to analyze states and heads, but conventions and weight processing depend on version. NNsight and NDIF separate intervention description from execution, which may be remote. No interface automatically makes similarly named activations equivalent: compare shapes, tokenization and logits on the same input, as the laboratory comparison does.

Local laboratory: train and inspect three depths

This laboratory needs PyTorch, NumPy, datasets and TinyStories access. It streams documents from official splits at a pinned revision and records hashes of bytes used. It works with UTF-8 bytes as a 256-symbol vocabulary: one position is a byte, not necessarily a character or word. Documents are joined by newlines; windows can cross that separator. It uses no positions, normalization, MLP or biases so displayed circuits exactly correspond to computation. Eigenvalue and byte-pair readouts depend on trained weights and do not themselves prove useful copying.

By default it trains zero, one and two layers with 2000 documents per split and 2000 steps per model. Adjust budget to your hardware. To check the pipeline with 16 documents and 4 steps, set ORYON_QUICK=1 before running; that test does not establish learned circuits. ORYON_M30_DIR selects the output directory, containing checkpoints with weights, configuration, revision and hashes. Printed evaluation is one batch, suitable for checking the pipeline but not scientific model comparison. For a conclusion measure many validation batches with intervals and independent seeds.

Hooks capture copies of embeddings and writes and are removed afterward. Reconstruction should agree with original logits up to rounding. The full OV matrix is expressed in the byte vocabulary and the three highest-logit outputs for source byte e are shown. A head with positive eigenvalues does not necessarily copy all bytes; inspect attention pattern and test interventions.

[ ]Train and inspect attention modelsLocal GPU
import os, json, hashlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from datasets import load_dataset

REV = 'f54c09fd23315a6f9c86f9dc80f725de7d8f9c64'
QUICK = os.environ.get('ORYON_QUICK') == '1'
ROOT = Path(os.environ.get('ORYON_M30_DIR', './oryon-m30-l15'))
ROOT.mkdir(parents=True, exist_ok=True)
torch.manual_seed(17)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
docs = 16 if QUICK else 2000
steps = 4 if QUICK else 2000
T, D, H, B = (16, 16, 2, 4) if QUICK else (64, 64, 4, 16)

def data(split):
    ds = load_dataset('roneneldan/TinyStories', split=split, streaming=True, revision=REV)
    texts = [row['text'] for _, row in zip(range(docs), ds)]
    stream = b'\n'.join(t.encode('utf-8') for t in texts)
    return torch.tensor(list(stream), dtype=torch.long), hashlib.sha256(stream).hexdigest()

train, train_hash = data('train')
val, val_hash = data('validation')
assert len(train) > T + 1 and len(val) > T + 1

class Head(nn.Module):
    def __init__(self):
        super().__init__()
        self.q = nn.Linear(D, D // H, bias=False)
        self.k = nn.Linear(D, D // H, bias=False)
        self.v = nn.Linear(D, D // H, bias=False)
        self.o = nn.Linear(D // H, D, bias=False)
    def forward(self, r):
        score = self.q(r) @ self.k(r).transpose(-1, -2) / (D // H) ** 0.5
        mask = torch.ones(r.shape[1], r.shape[1], device=r.device, dtype=torch.bool).tril()
        A = score.masked_fill(~mask, float('-inf')).softmax(-1)
        return self.o(A @ self.v(r))

class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.heads = nn.ModuleList([Head() for _ in range(H)])
    def forward(self, r):
        return r + sum(head(r) for head in self.heads)

class Net(nn.Module):
    def __init__(self, depth):
        super().__init__()
        self.embed = nn.Embedding(256, D)
        self.blocks = nn.ModuleList([Block() for _ in range(depth)])
        self.unembed = nn.Linear(D, 256, bias=False)
    def forward(self, x):
        r = self.embed(x)
        for block in self.blocks:
            r = block(r)
        return self.unembed(r)

def batch(data, generator):
    starts = torch.randint(len(data) - T, (B,), generator=generator)
    idx = starts[:, None] + torch.arange(T + 1)
    chunks = data[idx].to(device)
    return chunks[:, :-1], chunks[:, 1:]

for depth in range(3):
    torch.manual_seed(17)
    model = Net(depth).to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=0.001)
    gen = torch.Generator().manual_seed(170 + depth)
    for step in range(steps):
        x, y = batch(train, gen)
        loss = F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1))
        opt.zero_grad(set_to_none=True)
        loss.backward()
        opt.step()
    x, y = batch(val, torch.Generator().manual_seed(31))
    with torch.no_grad():
        val_loss = F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1)).item()
    cfg = dict(depth=depth, width=D, heads=H, context=T, steps=steps, train_sha256=train_hash, validation_sha256=val_hash, revision=REV, byte_tokenizer=True)
    torch.save({'config': cfg, 'state_dict': model.state_dict()}, ROOT / f'depth-{depth}.pt')
    print(json.dumps({'depth': depth, 'steps': steps, 'validation_loss': val_loss}, ensure_ascii=False))

# Cada columna de esta tabla son los logits de continuación de un byte.
zero = Net(0).to(device)
zero.load_state_dict(torch.load(ROOT / 'depth-0.pt', map_location=device, weights_only=True)['state_dict'])
with torch.no_grad():
    bigrams = zero.unembed.weight @ zero.embed.weight.T
    test_byte = torch.tensor([[ord('e')]], device=device)
    print('Error de tabla de bigramas:', (zero(test_byte)[0, 0] - bigrams[:, ord('e')]).abs().max().item())
    print('Top 3 bytes tras e:', bigrams[:, ord('e')].topk(3).indices.tolist())

# Inspecciona la ejecución de una capa y retira todos los hooks.
checkpoint = torch.load(ROOT / 'depth-1.pt', map_location=device, weights_only=True)
one = Net(1).to(device)
one.load_state_dict(checkpoint['state_dict'])
one.eval()
cache = {}
handles = [one.embed.register_forward_hook(lambda module, args, out: cache.__setitem__('embedding', out.detach().clone()))]
for index, head in enumerate(one.blocks[0].heads):
    handles.append(head.register_forward_hook(lambda module, args, out, index=index: cache.__setitem__(f'head{index}', out.detach().clone())))
prompt = torch.tensor([list(b'keep in mind')], device=device)
with torch.no_grad():
    logits = one(prompt)
for handle in handles:
    handle.remove()
reconstructed = one.unembed(cache['embedding'] + sum(cache[f'head{i}'] for i in range(H)))
print('Error máximo de reconstrucción:', (reconstructed - logits).abs().max().item())
with torch.no_grad():
    early = one.unembed(cache['embedding'])
    print('Lente, top byte antes y después:', early[0, -1].argmax().item(), logits[0, -1].argmax().item())
E, U = one.embed.weight.T.detach(), one.unembed.weight.detach()
for i, head in enumerate(one.blocks[0].heads):
    OV = head.o.weight @ head.v.weight
    full = U @ OV @ E
    eig = torch.linalg.eigvals(full).detach().cpu().numpy()
    source = ord('e')
    top = torch.topk(full[:, source], 3).indices.tolist()
    print('Cabeza', i, 'top bytes desde e:', top, 'mayor módulo:', float(np.abs(eig).max()))
    with torch.no_grad():
        r = cache['embedding']
        scores = (head.q(r) @ head.k(r).transpose(-1, -2)) / (D // H) ** 0.5
        attention = scores[0, -1].softmax(-1)
        target = int(logits[0, -1].argmax())
        terms = attention * full[target, prompt[0]]
        j = int(terms.abs().argmax())
        print('Skip-trigrama destino/origen/salida:', int(prompt[0, -1]), int(prompt[0, j]), target, 'posición origen:', j, 'contribución:', float(terms[j]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To compare with TransformerLens 4.4, copy the same weights to a native one-layer model without normalization. Position and biases, absent from our model, are zeroed. Compare CPU logits and number of captured activations; allow small differences from operation order and device. API 4 replaces the former HookedTransformer with TransformerBridge; consult the migration guide when using another version.

[ ]Comparison with TransformerLensLocal GPU
from transformer_lens import TransformerBridgeConfig
from transformer_lens.model_bridge import TransformerBridge
import transformer_lens.model_bridge.sources.native

cfg_bridge = TransformerBridgeConfig(d_model=D, d_head=D // H, n_layers=1, n_ctx=T,
                                      n_heads=H, d_vocab=256, attn_only=True,
                                      normalization_type=None)
bridge = TransformerBridge.boot_native(cfg_bridge, device='cpu')
params = dict(bridge.named_parameters())
prefix = 'layers.0._original_component.attn._original_component.'
with torch.no_grad():
    params['tok_embed._original_component.weight'].copy_(one.embed.weight.cpu())
    params['pos._original_component.weight'].zero_()
    params['head._original_component.weight'].copy_(one.unembed.weight.cpu())
    for name in ('q', 'k', 'v'):
        weights = [getattr(head, name).weight.cpu() for head in one.blocks[0].heads]
        params[prefix + name + '._original_component.weight'].copy_(torch.cat(weights, dim=0))
        params[prefix + name + '._original_component.bias'].zero_()
    params[prefix + 'o._original_component.weight'].copy_(torch.cat([head.o.weight.cpu() for head in one.blocks[0].heads], dim=1))
    params[prefix + 'o._original_component.bias'].zero_()
    out, tl_cache = bridge.run_with_cache(prompt.cpu(), return_cache_object=False)
    print('Error máximo TransformerLens frente a implementación propia:', (out - logits.cpu()).abs().max().item())
    print('Número de activaciones cacheadas:', len(tl_cache))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To reproduce the lens figure install transformers, tuned-lens==0.2.0 and their dependencies. GPT-2 and published lens parameters are downloaded at explicit revisions; the exported file also records the parameter hash. In this particular combination, tuned-lens 0.2 checks a class removed from TransformerLens 4. The cell disables that detection branch only in this process because the model here is from Hugging Face. It does not modify installed packages. The final row uses actual logits without applying normalization again.

[ ]GPT-2 readouts with two lensesLocal GPU
import json, hashlib, os
from pathlib import Path
import torch
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer, AutoModelForCausalLM
from tuned_lens.nn.lenses import LogitLens, TunedLens
import tuned_lens.model_surgery as surgery

MODEL_REV = '607a30d783dfa663caf39e06633721c8d4cfcd7e'
LENS_REV = '1ac7285852a22309f571c2555efc37375d0c4cda'
model_id = 'openai-community/gpt2'
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=MODEL_REV)
model = AutoModelForCausalLM.from_pretrained(model_id, revision=MODEL_REV).eval()
root = Path(snapshot_download('AlignmentResearch/tuned-lens', repo_type='space', revision=LENS_REV, allow_patterns=['lens/gpt2/*'])) / 'lens' / 'gpt2'
# tuned-lens 0.2 consulta HookedTransformer, retirado en TL 4. Solo durante
# la construcción de estas lentes HF desactivamos esa rama y la restauramos.
previous = surgery._transformer_lens_available
try:
    surgery._transformer_lens_available = False
    logit_lens = LogitLens.from_model(model).eval()
    tuned = TunedLens.from_model_and_pretrained(model, str(root), weights_only=True).eval()
finally:
    surgery._transformer_lens_available = previous
text = 'The capital of France is'
tokens = tokenizer(text, return_tensors='pt')
with torch.no_grad():
    result = model(**tokens, output_hidden_states=True)
    rows = []
    for layer, state in enumerate(result.hidden_states[:-1]):
        row = []
        for mode, lens in [('logit', logit_lens), ('tuned', tuned)]:
            prob = lens(state, layer).softmax(-1)
            values, ids = prob.topk(5, dim=-1)
            row.append([[{'token': tokenizer.decode(int(i)), 'prob': round(float(v), 6)} for v, i in zip(vs, ix)] for vs, ix in zip(values[0], ids[0])])
        rows.append({'layer': layer, 'logit': row[0], 'tuned': row[1]})
    probs = result.logits.softmax(-1)
    values, ids = probs.topk(5, dim=-1)
    final = [[{'token': tokenizer.decode(int(i)), 'prob': round(float(v), 6)} for v, i in zip(vs, ix)] for vs, ix in zip(values[0], ids[0])]
    rows.append({'layer': 12, 'logit': final, 'tuned': final})
out = {'model': model_id, 'model_revision': MODEL_REV, 'lens_revision': LENS_REV,
       'lens_params_sha256': hashlib.sha256((root / 'params.pt').read_bytes()).hexdigest(),
       'text': text, 'tokens': [tokenizer.decode(int(i)) for i in tokens['input_ids'][0]], 'rows': rows}
ROOT = Path(os.environ.get('ORYON_M30_DIR', './oryon-m30-l15'))
ROOT.mkdir(parents=True, exist_ok=True)
dest = ROOT / 'lens-data.json'
dest.write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Guardado', dest, out['lens_params_sha256'], 'tokens:', out['tokens'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell exports data for the two circuit figures from the checkpoint just trained. Each run produces its own data and hash. To reconstruct published figures use the full budget and compare hash; small differences between devices and versions can change weights. The ASCII subset only limits interactive tables: the spectrum is calculated over all 256 bytes.

[ ]Export QK and OV circuitsLocal GPU
import json, hashlib
from pathlib import Path
import numpy as np
import torch

path = ROOT / 'depth-1.pt'
ck = torch.load(path, map_location='cpu', weights_only=True)
s, cfg = ck['state_dict'], ck['config']
E = s['embed.weight'].numpy().T
U = s['unembed.weight'].numpy()
alphabet = np.arange(32, 127)
heads = []
for h in range(cfg['heads']):
    prefix = f'blocks.0.heads.{h}.'
    Q, K, V, O = (s[prefix + n + '.weight'].numpy() for n in ('q', 'k', 'v', 'o'))
    qk = E[:, alphabet].T @ Q.T @ K @ E[:, alphabet] / np.sqrt(Q.shape[0])
    full = U @ O @ V @ E
    ov = full[np.ix_(alphabet, alphabet)]
    eig = np.linalg.eigvals(full)
    heads.append({'qk': np.round(qk, 5).tolist(), 'ov': np.round(ov, 5).tolist(),
                  'eigen': [[round(float(x.real), 5), round(float(x.imag), 5)] for x in eig]})
out = {'config': cfg, 'checkpoint_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
       'alphabet': alphabet.tolist(), 'heads': heads}
dest = ROOT / 'circuit-data.json'
dest.write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Exportado:', dest, 'SHA-256 checkpoint:', out['checkpoint_sha256'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell reproduces the previous counts on already-loaded training bytes. Texts are joined by newline as in training. In short mode the numbers correspond to 16 documents, not the published figure.

[ ]Count four-byte contextsLocal GPU
x = train.numpy()
source, destination, continuation = x[:-3], x[2:-1], x[3:]
for destination_byte in (ord('o'), ord('h')):
    mask = (source == ord(' ')) & (destination == destination_byte) & (continuation >= 32) & (continuation <= 126)
    target = continuation[mask]
    print(chr(destination_byte), 'total:', len(target), 'espacio:', int((target == ord(' ')).sum()), 'e:', int((target == ord('e')).sum()))
print('SHA-256 bytes de entrenamiento:', train_hash)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Derive the logit expansion of an attention-only layer with fixed patterns.
0
Assume token embeddings, fixed causal attention, and no normalization, biases or position.

Step 1 of 3. What state does unembedding receive at position i?

Code
Implement logit_lens(cache, W_U, ln_final, k). cache has shape (layers, positions, dimension); ln_final is a function preserving that shape; W_U has shape (vocabulary, dimension). Return top-k indices in descending order per layer and position.
def logit_lens(cache, W_U, ln_final, k):
  # Completa la lectura y ordena los logits.
  pass
Shift+Enter to run
Quiz
A head has near-zero direct attribution to the final logit difference. What can you conclude?
Numeric
A write is (2, 1), the unembedding difference direction is (1, −1) and frozen scale is 2. Without centering or biases, what is the attribution?
Key idea
The residual sum permits exact accounting of one run. Attributing a causal mechanism requires intervention and checking how the rest of the computation changes.