The GPT model and parity with GPT-2
Implement the complete model in pure PyTorch: token and position embeddings, pre-norm causal-attention and MLP blocks, tied weights, a language head, and GPT-2 initialization. Test it rigorously by loading public 124M GPT-2 weights and reproducing the reference implementation's logits.
After this lesson you can
- Implement GPT-2 with matching shapes and names so its weights can be loaded.
- Load public weights and obtain logits matching the reference within tolerance.
- Implement residual-scaled initialization and verify residual-stream variance.
- Count parameters and FLOPs per token and compare them with analytical formulas.
Before you start
Build the model and require it to match
A transformer can produce logits with the correct shape and still be a different model. A mask applied after softmax, a matrix copied in the wrong orientation, or a different activation may go unnoticed if we only look at the most likely word. This lesson’s test is more demanding: load public GPT-2 weights into a custom implementation and compare all logits with those of the Hugging Face reference implementation on the same inputs, with an explicit tolerance. If they agree on one hundred sequences of 1024 positions, each embedding, normalization, head, and transpose is in place; if they do not, the first divergent tensor tells us where to look.
Before writing code, follow the shapes. Change batch size, sequence length, or model in the figure. Parameters belong to matrices shared across positions; forward-pass FLOPs grow with positions, and attention FLOPs grow with their square. These figures are an analytical count under the convention detailed below, not measurements of time or of a particular kernel.
With the initial values, GPT-2 small and one sequence of 1024 positions, the figure shows three things worth retaining. Almost one third of parameters, 38.6 million of 124.4 million, are in the token embedding table. The vocabulary projection is the most expensive individual operation: with and it costs FLOPs per token, more than all projections of one block combined (). At , attention products already account for 13% of the total. Switch to the 513-token project vocabulary and see that, using the vocabulary from p06-l02, readout almost disappears: the model falls to 86 236 416 parameters.
The GPT model implementation takes integer IDs with shape , transforms each ID and position into a vector of dimension , and applies causal blocks. Final output has shape . Training from scratch will use the vocabulary you built with the BPE tokenizer; the public-weight parity test uses GPT-2 vocabulary and IDs. IDs from the custom vocabulary cannot be interpreted using pretrained embeddings from a different tokenizer: ID 300 from our BPE and ID 300 from GPT-2 represent different pieces of text.
Inside a block
Let and be token and position embeddings. The input to the first block at position of a sequence with IDs is , where is row . In the pre-norm block, for a residual input compute
Normalization acts per position, , with and the mean and variance of the coordinates and . Each branch writes to the residual stream by adding its output. The additions require matching shape . After the final block, a final normalization and vocabulary projection produce logits. GPT-2 small uses , , , , and , as specified in its public configuration. The GPT-2 paper (Radford et al., 2019, section 2.3) describes two changes from GPT: normalization moves to the input of each subblock, and another normalization is added after the final block.
Multi-head attention starts with one projection, called c_attn in GPT-2. Its output is split into Q, K, and V, each going from to and then to , with . In each head, for query and key , . The causal mask assigns to before softmax, so row is normalized only over keys :
If instead softmax runs over all keys and future weights are then set to zero, row sums to : allowed positions receive too little mass, increasingly so for earlier queries. In the lab control with seven positions, the worst row retains 0.95% of the mass and output differs by up to 2.6 units. After combining weights and values, undo the reshape (, requiring contiguous() before view) and apply output projection c_proj.
Axis order is part of the function. Transposing to has no parameters, but directly applying view(B, H, T, d_h) to the tensor places channels from different positions in the same “head” and mixes position with channel. A test with misses the error because all rearrangements coincide there; a test with multiple heads and positions detects it.
PyTorch’s scaled_dot_product_attention (SDPA) computes this operation and, depending on backend, can avoid materializing the matrix. To compare with the manual version, match mask, scale, dtype, and dropout. Two details in its documentation matter here. dropout_p is applied whenever positive, even in eval(), so the module must pass dropout_p=0.0 outside training, as the lab does. With is_causal=True, the mask is lower triangular and aligned to the upper left. If there are fewer queries than keys, as when generating with a key-value cache, query still sees only keys . The lab demonstrates this: one query, the last of seven, with is_causal=True attends only to key 0 and its output differs from the correct output by 1.9 units. For this lesson’s model, which always processes the whole sequence, the convention is correct; the inference engine in p10-l02 must build its own mask.
A causality test complements numerical comparison. Run two sequences with the same prefix and change only tokens after position . In evaluation mode, logits through must match within tolerance, while later ones need not. The test detects future leakage but does not by itself establish that the model is correct: a model with wrong weights can also be causal.
GPT-2’s MLP applies a projection (c_fc), the hyperbolic-tangent approximation to GELU,
which differs from exact GELU by at most , and a projection (c_proj). LayerNorm’s , biases, and activation variant are part of the function. In the verification run, replacing only the approximation with exact GELU (F.gelu) shifted logits by up to 0.25 on four sequences of 1024 positions, although argmax still agreed at 99.85% of them. Evaluation disables dropout; no_grad() or inference_mode() avoid storing the graph but do not themselves change module mode.
Tie weights and count without duplication
With tied weights, the token embedding matrix is also the readout matrix: the logit for token at position is , with the final vector after . No second parameter is created. Tying means both references point to the same tensor, lm_head.weight is transformer.wte.weight in the lab, so they receive the sum of both gradients and update together. Copying equal values into two distinct parameters is not tying. The lab control creates such a copy in a tiny model, and after one gradient descent step the tensors already differ by 0.026 while parameter count rises from 4464 to 5488.
The tied model’s state_dict contains both keys, transformer.wte.weight and lm_head.weight, pointing to the same storage. Summing numel() across entries gives 163 037 184 rather than 124 439 808 because it counts the 38 597 376 table parameters twice. model.parameters() does not repeat tensors and gives the correct number. Saving with torch.save preserves sharing; loading with load_state_dict into an already-tied model writes the same value twice to the same tensor, which is harmless. The error appears if the head is reconstructed as a new parameter after loading or a save format materializes both keys as independent tensors.
With biases in all linear layers and LayerNorm, a block has parameters. The QKV projection contributes and output projection ; the MLP contributes and ; the two LayerNorms contribute . The two embedding tables contribute and final LayerNorm . Therefore, with tied readout and no head bias,
For GPT-2 small, token and position tables contribute 38 597 376 and 786 432 parameters, each block 7 087 872, and final normalization 1536, totaling . The lab counts unique PyTorch parameters and checks the formula. If a library excludes the position table from its count, adjust the convention before comparing. Changing vocabulary for the project only changes the first table and shape of the logits, not the internal block dimensions.
FLOPs per token
Count one multiplication and one addition as two FLOPs and count only matrix multiplications. An matrix applied to a vector costs . Per token and block, projections cost , and vocabulary readout costs . Attention depends on how many query-key pairs are computed. A kernel materializing the full matrix does for and another for multiplication by at each position, summed over heads. With the mask, position needs only keys, averaging over . Therefore, a batch forward pass costs
For GPT-2 small with , this gives 284 812 800 FLOPs per token with the dense count and 265 956 864 with the causal count, which the lab prints as forward_matmul_flops_per_token. For reference, : the “two FLOPs per parameter and token” rule is too low because it ignores attention, and it also includes the position table, which is not multiplied. Softmax, activations, normalization, and biases are omitted; these are operations of order or , not . This is an operation model rather than a speed measurement. A real kernel may do extra work or avoid materializing the matrix. For training, each matrix multiplication requires two more of the same size in backpropagation, one for the input gradient and one for the weight gradient. This yields the usual approximation of three times forward-pass compute used by p06-l06, excluding recomputation and optimizer cost.
Initialization: why
GPT initialization samples all linear-layer and embedding weights as independent zero-mean normal variables with standard deviation , zeros biases, sets LayerNorm to and , and reduces standard deviation to in the two projections writing to the residual (attn.c_proj and mlp.c_proj). The GPT-2 paper states that residual-layer weights are scaled at initialization by , where is the number of residual layers. There are two branches per block, so , as in the Hugging Face implementation and nanoGPT (std=0.02/math.sqrt(2 * config.n_layer)).
The question is what happens to the residual stream when branches are stacked. Number the branches in order, , and fix one coordinate and position. After branch , the residual is , where is what branch would write with its output projection unscaled and is the scale factor, without scaling and with it. Start with a purely probabilistic result.
Proof
The variance of a sum is the sum of variances plus twice the sum of pairwise covariances. By hypothesis all cross-covariances vanish, and . Summing the terms gives the equality and bound; with , the factor cancels.
∎The theorem moves the difficulty into its hypotheses. Interestingly, at initialization they hold exactly, taking randomness over sampled weights while inputs can be arbitrary and fixed.
Proof
Covariances. Branch computes for the fixed coordinate’s row, where is its output projection and its internal vector: attention output before c_proj or GELU output before mlp.c_proj. The vector depends on embeddings, previous branches, and the other weights of branch ; is independent of all of them. Let denote information generated by those variables. Because has mean zero and is independent of , . For , and are -measurable, so , and likewise for . Since all means are zero, with the sum of two centered weights, covariances vanish: the are martingale differences.
Variances. is the sum of independent entries of and , so . Conditioning on , the coordinate is a combination of independent entries with coefficients , so . It remains to bound . LayerNorm output satisfies regardless of input: this is where pre-norm acts.
- In the MLP, with . Since because the factor is in , .
- In attention, the part of for head is , a convex combination. By convexity of , its squared norm is at most . Weights depend on and the , but not , and . Summing the heads gives .
In both cases , and the first theorem yields the bound.
∎Two observations clarify scope. First, without scaling (), the theorem’s equality says variance is plus the sum of branch variances, and because LayerNorm returns each branch to the same scale, the sum grows linearly with depth; scaling turns it into an average. Second, the result applies at initialization, when weight independence holds. During training weights become correlated and none of this is guaranteed.
The lab checks this at full size, , , three seeds, and four sequences of 256 positions, with and , the depth of GPT-2 XL. Variance of is 0.0008, or . The largest unscaled branch variance, between 0.13 and 0.15, is well below , and reproduces measured final variance with relative error below 3.5% in all twelve runs: the theorem’s equality is observed. Without scaling, mean final variance is 2.24 at 12 layers and 9.74 at 48, a ratio of 4.36, close to the 4 predicted by linear growth. With scaling it is 0.086 and 0.089, independent of depth. Printed variance aggregates batch, positions, and coordinates for one initialization. Coordinate symmetry makes it an estimate of the theorem’s per-coordinate variance, but it is not the same quantity.
Load without changing the function
The pretrained weight parity test requires matching configuration, IDs, positions, precision, activation, and evaluation mode. The lab uses the same module names as GPT2LMHeadModel (transformer.wte, transformer.h.0.attn.c_attn, lm_head, and so on), so the two state_dict key sets match and the loader rejects missing or extra keys rather than leaving a randomly initialized matrix.
In PyTorch, nn.Linear(d_in, d_out) stores its weight with shape and computes . GPT-2 was published with a Conv1D layer storing the matrix in the opposite orientation, , and computing . Hugging Face retains that class in its GPT-2 implementation, and nanoGPT transposes these matrices on import. Four matrices per block are affected: attn.c_attn (), attn.c_proj (), mlp.c_fc (), and mlp.c_proj (). Biases, embeddings, and LayerNorms are copied unchanged. The lab loader transposes by name, not shape. A loader transposing “when shapes do not match” fixes the three rectangular matrices but leaves the sole square matrix, attn.c_proj, untransposed. The copy succeeds yet computes a different function. In the lab this single error produces a maximum logit difference of 135 and argmax agreement at only 2.7% of positions.
Compare across all logits, positions, and sequences, not only argmax, which can agree even when logits have appreciable errors. This lesson’s criterion is maximum absolute float32 error below over 100 sequences of 1024 random IDs. This is demanding. GPT-2 logits reach 281.8 in absolute value on those inputs, where consecutive float32 values are separated by , so is about three rounding units. A mathematically identical implementation with standard nn.Linear, multiplying by the transpose with a different summation order, yields maximum error , already in the first 64 positions, with identical argmax everywhere. This is rounding rather than a functional error. For this reason the lab’s GPTLinear computes with torch.addmm on a matrix oriented like Conv1D, the same call as the reference. With TF32 disabled and the mathematical SDPA backend in both models, the difference is exactly 0. An ordinary parity test would use a relative tolerance such as torch.testing.assert_close for float32 (, ).
If the test fails, compare the first divergent states in order: embeddings, , QKV, attention output, residual, MLP, final normalization, and logits. A wrongly transposed square matrix retains its shape, so shape checks are necessary but insufficient. Agreement on 100 inputs detects common errors but is not a formal proof of equivalence on all inputs.
The public model and project model serve distinct functions. Loading GPT-2 tests whether the custom architecture reproduces an independent implementation with known weights. To train from scratch on p06-l02 shards, build another instance, GPT(vocab=513, ...), using the vocabulary and separator from the data manifest. This is the class later lessons read.
Lab
You need PyTorch with CUDA, transformers==5.20.2, and a Hugging Face connection the first time, about 550 MB. Run both cells in order; they also work on CPU, more slowly. The first defines the model and runs controls for manual attention versus SDPA, causality, dropout, parameter counts, and residual-stream variance at full-size initialization. The second downloads pinned revision 607a30d783dfa663caf39e06633721c8d4cfcd7e of openai-community/gpt2 to gpt2_cache, configurable via GPT2_CACHE_DIR, and compares logits. On a laptop RTX 4060 the first takes a few seconds and the second about a minute, with GPU memory peaks of about 2.1 and 2.7 GB.
GPTLinear inherits from nn.Linear, so it stores weights in output rows and initialization treats it like any linear layer. Only calculation changes: it transposes the weight to a contiguous copy and calls torch.addmm as Conv1D does. That copy occurs on every pass and costs memory and time. It permits the exact parity described above, and p06-l05 measures its cost. Later project lessons read this cell up to the attention_test() call to reuse class GPT.
"""GPT-2 desde cero con carga de pesos Hugging Face y controles reproducibles."""
import math
import os
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(4)
class GPTLinear(nn.Linear):
def forward(self, x):
weight = self.weight.t().contiguous()
return torch.addmm(self.bias, x.reshape(-1, x.size(-1)), weight).view(*x.shape[:-1], self.out_features)
class CausalSelfAttention(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
assert d % heads == 0
self.heads, self.d = heads, d
self.p = dropout
self.resid_drop = nn.Dropout(dropout)
self.c_attn = GPTLinear(d, 3*d)
self.c_proj = GPTLinear(d, d)
def forward(self, x):
b, t, d = x.shape
q, k, v = self.c_attn(x).split(d, dim=-1)
def split(z):
return z.view(b, t, self.heads, d//self.heads).transpose(1, 2)
out = F.scaled_dot_product_attention(split(q), split(k), split(v),
is_causal=True, dropout_p=self.p if self.training else 0.0)
out = out.transpose(1, 2).contiguous().view(b, t, d)
return self.resid_drop(self.c_proj(out))
class MLP(nn.Module):
def __init__(self, d, dropout):
super().__init__()
self.c_fc = GPTLinear(d, 4*d)
self.c_proj = GPTLinear(4*d, d)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = self.c_fc(x)
x = 0.5*x*(1.0 + torch.tanh(math.sqrt(2.0/math.pi)*(x + 0.044715*torch.pow(x, 3.0))))
return self.dropout(self.c_proj(x))
class Block(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
self.ln_1 = nn.LayerNorm(d, eps=1e-5)
self.attn = CausalSelfAttention(d, heads, dropout)
self.ln_2 = nn.LayerNorm(d, eps=1e-5)
self.mlp = MLP(d, dropout)
def forward(self, x):
x = x + self.attn(self.ln_1(x))
return x + self.mlp(self.ln_2(x))
class Transformer(nn.Module):
def __init__(self, vocab, context, layers, heads, d, dropout):
super().__init__()
self.wte = nn.Embedding(vocab, d)
self.wpe = nn.Embedding(context, d)
self.drop = nn.Dropout(dropout)
self.h = nn.ModuleList([Block(d, heads, dropout) for _ in range(layers)])
self.ln_f = nn.LayerNorm(d, eps=1e-5)
class GPT(nn.Module):
def __init__(self, vocab=50257, context=1024, layers=12, heads=12, d=768, scaled=True, dropout=0.1):
super().__init__()
self.context, self.layers, self.d = context, layers, d
self.transformer = Transformer(vocab, context, layers, heads, d, dropout)
self.transformer.apply(self._init)
self.lm_head = nn.Linear(d, vocab, bias=False)
self.lm_head.weight = self.transformer.wte.weight
if scaled:
for block in self.transformer.h:
nn.init.normal_(block.attn.c_proj.weight, std=0.02/math.sqrt(2*layers))
nn.init.normal_(block.mlp.c_proj.weight, std=0.02/math.sqrt(2*layers))
@staticmethod
def _init(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, mean=0, std=0.02)
if isinstance(module, nn.Linear) and module.bias is not None:
nn.init.zeros_(module.bias)
def forward(self, ids, return_residual=False):
b, t = ids.shape
if t > self.context:
raise ValueError('El contexto supera el límite del modelo')
z = self.transformer.drop(self.transformer.wte(ids) + self.transformer.wpe(torch.arange(t, device=ids.device)))
residuals = [z]
for block in self.transformer.h:
z = block(z)
residuals.append(z)
logits = self.lm_head(self.transformer.ln_f(z))
return (logits, residuals) if return_residual else logits
def count_formula(vocab, context, layers, d):
return vocab*d + context*d + layers*(12*d*d + 13*d) + 2*d
def forward_matmul_flops_per_token(vocab, layers, d, t):
# Cuenta suma y producto separados; solo matmuls densas y atención causal.
return 2*(12*layers*d*d + vocab*d) + 2*layers*d*(t+1)
def load_hf(gpt, reference):
source = reference.state_dict()
target = gpt.state_dict()
assert source.keys() == target.keys(), (source.keys() - target.keys(), target.keys() - source.keys())
transpose = ('.attn.c_attn.weight', '.attn.c_proj.weight',
'.mlp.c_fc.weight', '.mlp.c_proj.weight')
with torch.no_grad():
for name, dest in target.items():
src = source[name]
if name.endswith(transpose):
src = src.T
if src.shape != dest.shape:
raise ValueError(f'Forma distinta: {name}: {src.shape} != {dest.shape}')
dest.copy_(src)
assert gpt.lm_head.weight is gpt.transformer.wte.weight
def attention_test():
torch.manual_seed(11)
q = torch.randn(2, 3, 7, 5)
k = torch.randn(2, 3, 7, 5)
v = torch.randn(2, 3, 7, 5)
mask = torch.tril(torch.ones(7, 7, dtype=torch.bool))
scores = q @ k.transpose(-2, -1) / math.sqrt(5)
expected = scores.masked_fill(~mask, float('-inf')).softmax(-1) @ v
actual = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0)
error = (expected-actual).abs().max().item()
assert error < 1e-6, error
print('atención manual vs SDPA, error máximo:', error, flush=True)
late = scores.softmax(-1) * mask # máscara después del softmax, sin renormalizar
print('máscara tras el softmax: error máximo', round((late @ v - expected).abs().max().item(), 4),
'| masa mínima de una fila', round(late.sum(-1).min().item(), 4), flush=True)
# Una sola consulta (la última posición) frente a las 7 claves: is_causal alinea la máscara
# arriba a la izquierda, así que esa consulta solo ve la clave 0.
alone = F.scaled_dot_product_attention(q[:, :, -1:], k, v, is_causal=True)
assert torch.allclose(alone, v[:, :, :1])
print('última consulta sola con is_causal=True: error frente a la fila correcta',
round((alone - expected[:, :, -1:]).abs().max().item(), 4), '(solo ve la clave 0)', flush=True)
def behavior_test():
torch.manual_seed(91)
model = GPT(vocab=128, context=16, layers=2, heads=4, d=32, dropout=0.5)
ids = torch.randint(0, 128, (4, 16))
changed = ids.clone()
changed[:, 8:] = (changed[:, 8:] + 1) % 128
model.eval()
with torch.no_grad():
a, b = model(ids), model(changed)
again = model(ids)
assert torch.equal(a, again)
assert torch.allclose(a[:, :8], b[:, :8], atol=1e-7, rtol=0)
assert not torch.allclose(a[:, 8:], b[:, 8:], atol=1e-3)
model.train()
with torch.no_grad():
first, second = model(ids), model(ids)
assert not torch.equal(first, second)
attention = CausalSelfAttention(32, 4, dropout=0.5).train()
attention.resid_drop.p = 0.0
x = torch.randn(4, 16, 32)
with torch.no_grad():
first, second = attention(x), attention(x)
assert not torch.equal(first, second)
print('eval determinista, causalidad y dropout de entrenamiento verificados', flush=True)
def count_test():
with torch.device('meta'):
model = GPT()
unique = sum(p.numel() for p in model.parameters())
entries = sum(t.numel() for t in model.state_dict().values())
assert unique == count_formula(50257, 1024, 12, 768) == 124439808
assert entries == unique + 50257*768
print('parámetros únicos con peso atado:', unique, '| suma ingenua del state_dict:', entries, flush=True)
print('FLOPs de matmul por token, T=1024 (atención causal):',
forward_matmul_flops_per_token(50257, 12, 768, 1024), flush=True)
# Copiar no es atar: dos parámetros con los mismos valores se separan en el primer paso.
torch.manual_seed(5)
small = GPT(vocab=64, context=8, layers=1, heads=2, d=16, dropout=0.0)
copy = GPT(vocab=64, context=8, layers=1, heads=2, d=16, dropout=0.0)
copy.lm_head.weight = nn.Parameter(copy.transformer.wte.weight.detach().clone())
copy.load_state_dict(small.state_dict())
for m in (small, copy):
ids = torch.randint(0, 64, (2, 8), generator=torch.Generator().manual_seed(6))
F.cross_entropy(m(ids).reshape(-1, 64), ids.reshape(-1)).backward()
with torch.no_grad():
for p in m.parameters():
p -= 0.1*p.grad
gap = (copy.lm_head.weight - copy.transformer.wte.weight).abs().max().item()
assert small.lm_head.weight is small.transformer.wte.weight and gap > 0
print('copia en vez de atado: parámetros', sum(p.numel() for p in copy.parameters()), 'frente a',
sum(p.numel() for p in small.parameters()), '| separación tras un paso:', round(gap, 6), flush=True)
def init_variance(layer_counts=(12, 48), seeds=(1, 2, 3), batch=4, length=256):
"""Varianza del flujo residual en la inicialización, a tamaño real (d = 768, V = 50257)."""
device = 'cuda' if torch.cuda.is_available() else 'cpu'
sigma, d = 0.02, 768
C = 4*d*d*sigma**4 # cota de Var(u_j) del segundo teorema
summary = {}
for layers in layer_counts:
for scaled in (False, True):
finals = []
for seed in seeds:
torch.manual_seed(seed)
with torch.device(device):
model = GPT(layers=layers, scaled=scaled, dropout=0.0).eval()
branch = []
hooks = [m.register_forward_hook(lambda mod, inp, out: branch.append(out.var(unbiased=False).item()))
for blk in model.transformer.h for m in (blk.attn, blk.mlp)]
ids = torch.randint(0, 50257, (batch, length), generator=torch.Generator().manual_seed(seed+100))
with torch.inference_mode():
_, states = model(ids.to(device), return_residual=True)
for hook in hooks:
hook.remove()
var = [z.var(unbiased=False).item() for z in states]
factor = 2*layers if scaled else 1 # Var(u_j) = factor · Var(rama escrita)
widest = factor*max(branch)
additive = var[0] + sum(branch)
assert widest <= C and abs(additive - var[-1]) <= 0.1*var[-1], (widest, additive, var[-1])
if scaled:
assert var[-1] <= 2*sigma**2 + C
finals.append(var[-1])
print(f'L={layers:2d} escalado={str(scaled):5} semilla={seed} Var(r_0)={var[0]:.5f} '
f'Var(r_L)={var[-1]:.4f} Var(r_0)+suma de ramas={additive:.4f} máx Var(u_j)={widest:.4f}',
flush=True)
if layers == layer_counts[0] and seed == seeds[0]:
print(' por capa:', [round(x, 4) for x in var], flush=True)
del model, states
if device == 'cuda':
torch.cuda.empty_cache()
summary[layers, scaled] = sum(finals)/len(finals)
small, big = layer_counts[0], layer_counts[-1]
print(f'cota del segundo teorema: Var(r_0) + C = {2*sigma**2 + C:.4f}', flush=True)
for scaled in (False, True):
print(f'escalado={scaled}: media de Var(r_L) con L={small}: {summary[small, scaled]:.4f}, '
f'con L={big}: {summary[big, scaled]:.4f}, cociente {summary[big, scaled]/summary[small, scaled]:.2f}', flush=True)
return summary
def parity(sequences=100, length=1024, batch=2):
from transformers import GPT2LMHeadModel
from torch.nn.attention import sdpa_kernel, SDPBackend
revision = '607a30d783dfa663caf39e06633721c8d4cfcd7e'
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
device = 'cuda' if torch.cuda.is_available() else 'cpu'
cache_dir = os.environ.get('GPT2_CACHE_DIR', 'gpt2_cache')
ref = GPT2LMHeadModel.from_pretrained('openai-community/gpt2', revision=revision,
attn_implementation='sdpa', cache_dir=cache_dir).eval()
own = GPT().eval()
count = sum(p.numel() for p in own.parameters())
assert count == count_formula(50257, 1024, 12, 768) == 124439808
load_hf(own, ref)
own.to(device); ref.to(device)
data = torch.randint(0, 50257, (sequences, length), generator=torch.Generator().manual_seed(1729))
def compare(n, t=length):
worst, agree, scale = 0.0, 0, 0.0
with torch.inference_mode(), sdpa_kernel(SDPBackend.MATH):
for start in range(0, n, batch):
ids = data[start:start+batch, :t].to(device)
a, b = own(ids), ref(ids).logits
worst = max(worst, (a-b).abs().max().item())
scale = max(scale, b.abs().max().item())
agree += (a.argmax(-1) == b.argmax(-1)).sum().item()
del ids, a, b
return worst, agree/(n*t), scale
try:
worst, agree, scale = compare(sequences)
assert worst < 1e-4, worst
print(f'PARIDAD float32, {sequences} secuencias de {length} IDs: error máximo {worst}, '
f'argmáx coincidente {agree:.4f}, máximo |logit| {scale:.1f}', flush=True)
# Contraste 1: la misma función con nn.Linear estándar (F.linear) en lugar de addmm.
GPTLinear.forward, saved = nn.Linear.forward, GPTLinear.forward
try:
worst_linear, agree_linear, _ = compare(sequences)
worst_short, _, _ = compare(sequences, 64)
finally:
GPTLinear.forward = saved
print(f'con F.linear: error máximo {worst_linear:.2e} con {length} posiciones '
f'({worst_short:.2e} con las 64 primeras), argmáx coincidente {agree_linear:.4f}', flush=True)
# Contraste 2: un cargador que transpone solo cuando la forma no encaja deja sin
# transponer la única matriz cuadrada, attn.c_proj (768 × 768).
source = ref.state_dict()
with torch.no_grad():
for i, block in enumerate(own.transformer.h):
block.attn.c_proj.weight.copy_(source[f'transformer.h.{i}.attn.c_proj.weight'])
worst_bad, agree_bad, _ = compare(4)
print(f'attn.c_proj sin transponer: error máximo {worst_bad:.2f}, argmáx coincidente {agree_bad:.4f}', flush=True)
print('parámetros:', count, '| FLOPs matmul/token, T=1024:',
forward_matmul_flops_per_token(50257, 12, 768, 1024), flush=True)
finally:
del own, ref
if device == 'cuda':
torch.cuda.empty_cache()
attention_test()
behavior_test()
count_test()
init_variance()npm run lab and open the connection link.What to expect: manual attention and SDPA agree with error on the order of ; masking after softmax deviates by 2.6 units and leaves one row with 0.95% of the mass; a single query with is_causal=True sees only key 0. The count gives 124 439 808 unique parameters versus 163 037 184 for the naive state_dict sum, and the copied rather than tied weights diverge after one step. For and seed 1, the variance test prints variance after each block. Without scaling it grows almost linearly from 0.0008 to 0.13 after the first block and 2.17 after the twelfth; with scaling, from 0.0008 to 0.088. The other seeds and figures are summarized in the initialization section.
parity()npm run lab and open the connection link.In the verification run, RTX 4060, the stated revision, TF32 disabled, and mathematical SDPA in both models, maximum error over logits was exactly 0.0 and argmax agreed at every position. With F.linear, error was ; with attn.c_proj left untransposed, 135.13, with correct argmax at only 2.73% of positions. Bitwise equality depends on using the same kernels on the same device: another GPU or PyTorch version may show a small error, and the criterion determines the outcome.
Exercises
forward method of CausalSelfAttention(d, heads) without using scaled_dot_product_attention. Input x has shape (B, T, d). Project with self.c_attn to 3d, split Q, K and V, reshape each to (B, H, T, d_h) with d_h = d / H, compute QKᵀ / √d_h, place −∞ at future keys (j > i) before softmax, multiply by V, undo the reshape to (B, T, d), and apply self.c_proj. Do not use dropout. The tests compare your output with SDPA using is_causal=True and your own weights, check causality, and verify head and position ordering.import math
import torch
from torch import nn
class CausalSelfAttention(nn.Module):
def __init__(self, d, heads):
super().__init__()
assert d % heads == 0
self.d, self.heads = d, heads
self.c_attn = nn.Linear(d, 3*d)
self.c_proj = nn.Linear(d, d)
def forward(self, x):
raise NotImplementedErrorStep 1 of 3. Why is Cov(u_i, u_j) = 0 for i < j?
A GPT-2 is a stack of pre-norm blocks over a residual stream, with parameters per block and an embedding table that also performs readout: 124 439 808 unique parameters, counted without duplicating the tied tensor. The strong correctness test is parity of all logits with the reference, loading public weights with Conv1D transpositions selected by name. Scaling by has an exact justification at initialization: branches are bounded-variance martingale differences thanks to pre-norm, so residual variance is an average rather than a sum.