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.
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 be token embedding and unembedding. Without layers, positions or biases, for token logits are . Column of contains continuation logits: it is a bigram table, not a probability table until softmax is applied.
In an attention-only layer, for destination position , head writes , where and is attention from to . In causal attention . 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:
If one-hot vectors are stacked by position into a vector of dimension and logits likewise, the pattern-conditioned map is
Block of the first matrix is if and zero otherwise. Block of head ’s term is . Multiplying these blocks by positional one-hots reproduces the previous equation, so equality does not require head independence. It does require fixing matrices 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 , with orientation defined by indices. The full OV circuit 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 and , the score for destination and source is . are masked and each row normalized with softmax. For output token , that head-and-source path contributes . 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 , 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 . A path entering the first head and continuing through the second carries position matrix and feature matrix . 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 , where summarizes first-layer writes. Before scaling, its score is
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 . This permits computing nonzero eigenvalues in a smaller matrix by reordering product factors from to . 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.
In this run, the first head’s largest-magnitude eigenvalue is approximately ; the second’s is approximately . 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.
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.
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 minimizes mean over training positions and sequences, where applies final normalization and unembedding to . 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.
Direct logit attribution projects each observed write onto an unembedding direction. For the difference between tokens and , let . Without normalization, the contribution of is . 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 channels define , and . If , then . The contribution of to the difference is and final bias contributes . The denominator is calculated once from total residual using the same 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.
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]))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.
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))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.
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'])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.
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'])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.
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)npm run lab and open the connection link.Exercises
Step 1 of 3. What state does unembedding receive at position i?
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