Module contents
Stage 3 of 9Advanced 100 min

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.

InteractiveTensor shapes through the model
OperationTensor shapeForward-pass FLOPs
Pre-norm block, repeated L = 12 times (bars already multiplied by L)
12. Logits
1 × 1024 × 50257
Product with the transpose of the token table: tied weights, no new parameters. With small d, this readout dominates cost.
Parameters: 0 · FLOPs: 7.90 · 10¹⁰

Parameters: embeddings 39.4 M · 12 blocks 85.1 M · final LN 1 536. FLOP bars: linear projections and attention products, counting multiplication and addition as 2 FLOPs and excluding softmax, normalizations, activations, and biases. This is a count, not a measured time.

Step 12 of 12: Logits
12
1
1024
Vocabulary V
Attention
Unique parameters124 439 808
Forward-pass FLOPs2.92 · 10¹¹
FLOPs per token284 812 800
Attention T² share13.3 %
Analytical trace of a pre-norm GPT with tied embeddings. Change dimensions, vocabulary, and the attention counting convention, and follow each operation.

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 V=50257V=50257 and d=768d=768 it costs 2dV≈7.7×1072dV\approx 7.7\times10^{7} FLOPs per token, more than all projections of one block combined (24d2≈1.4×10724d^2\approx1.4\times10^{7}). At T=1024T=1024, 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 B×TB\times T, transforms each ID and position into a vector of dimension dd, and applies LL causal blocks. Final output has shape B×T×VB\times T\times V. 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 E∈RV×d\mat{E}\in\R^{V\times d} and P∈RTmax⁡×d\mat{P}\in\R^{T_{\max}\times d} be token and position embeddings. The input to the first block at position tt of a sequence with IDs x1,…,xTx_1,\dots,x_T is r0(t)=Ext+Pt\vb{r}_0(t)=\mat{E}_{x_t}+\mat{P}_t, where Ext\mat{E}_{x_t} is row xtx_t. In the pre-norm block, for a residual input X∈RB×T×d\mat{X}\in\R^{B\times T\times d} compute

U=X+Attn⁡(LN⁡1(X)),Y=U+MLP⁡(LN⁡2(U)).\mat{U}=\mat{X}+\operatorname{Attn}(\operatorname{LN}_1(\mat{X})),\qquad \mat{Y}=\mat{U}+\operatorname{MLP}(\operatorname{LN}_2(\mat{U})).

Normalization acts per position, LN⁡(x)=γ⊙(x−μ)/s2+ε+β\operatorname{LN}(\vb{x})=\vb{\gamma}\odot(\vb{x}-\mu)/\sqrt{s^2+\varepsilon}+\vb{\beta}, with μ\mu and s2s^2 the mean and variance of the dd coordinates and ε=10−5\varepsilon=10^{-5}. Each branch writes to the residual stream by adding its output. The additions require matching shape B×T×dB\times T\times d. After the final block, a final normalization and vocabulary projection produce logits. GPT-2 small uses V=50257V=50257, Tmax⁡=1024T_{\max}=1024, d=768d=768, L=12L=12, and H=12H=12, 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 d→3dd\to3d projection, called c_attn in GPT-2. Its B×T×3dB\times T\times 3d output is split into Q, K, and V, each going from B×T×dB\times T\times d to B×T×H×dhB\times T\times H\times d_h and then to B×H×T×dhB\times H\times T\times d_h, with dh=d/H=64d_h=d/H=64. In each head, for query ii and key jj, Sij=qi⊤kj/dhS_{ij}=\vb{q}_i\T\vb{k}_j/\sqrt{d_h}. The causal mask assigns −∞-\infty to j>ij>i before softmax, so row ii is normalized only over keys 1,…,i1,\dots,i:

Aij=eSij∑j′≤ieSij′  (j≤i),Aij=0  (j>i),salida⁡i=∑j≤iAijvj.A_{ij}=\frac{e^{S_{ij}}}{\sum_{j'\le i}e^{S_{ij'}}}\ \ (j\le i),\qquad A_{ij}=0\ \ (j>i),\qquad \operatorname{salida}_i=\sum_{j\le i}A_{ij}\vb{v}_j .

If instead softmax runs over all keys and future weights are then set to zero, row ii sums to ∑j≤ieSij/∑jeSij<1\sum_{j\le i}e^{S_{ij}}/\sum_{j}e^{S_{ij}}<1: 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 (B×H×T×dh→B×T×dB\times H\times T\times d_h\to B\times T\times d, requiring contiguous() before view) and apply output projection c_proj.

Axis order is part of the function. Transposing B×T×H×dhB\times T\times H\times d_h to B×H×T×dhB\times H\times T\times d_h has no parameters, but directly applying view(B, H, T, d_h) to the B×T×dB\times T\times d tensor places channels from different positions in the same “head” and mixes position with channel. A test with H=T=1H=T=1 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 T×TT\times T 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 ii still sees only keys 1,…,i1,\dots,i. 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 ii. In evaluation mode, logits through ii 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 d→4dd\to 4d projection (c_fc), the hyperbolic-tangent approximation to GELU,

GELU⁡(z)≈12z(1+tanh⁡(2/π (z+0.044715 z3))),\operatorname{GELU}(z)\approx \tfrac12 z\Bigl(1+\tanh\bigl(\sqrt{2/\pi}\,(z+0.044715\,z^3)\bigr)\Bigr),

which differs from exact GELU z Φ(z)z\,\Phi(z) by at most 4.7×10−44.7\times10^{-4}, and a 4d→d4d\to d projection (c_proj). LayerNorm’s ε\varepsilon, 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 vv at position tt is ztv=Ev htz_{tv}=\mat{E}_v\,\vb{h}_t, with ht\vb{h}_t the final vector after LN⁡f\operatorname{LN}_f. No second VdVd 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 12d2+13d12d^2+13d parameters. The QKV projection contributes 3d2+3d3d^2+3d and output projection d2+dd^2+d; the MLP contributes 4d2+4d4d^2+4d and 4d2+d4d^2+d; the two LayerNorms contribute 4d4d. The two embedding tables contribute Vd+Tmax⁡dVd+T_{\max}d and final LayerNorm 2d2d. Therefore, with tied readout and no head bias,

N=Vd+Tmax⁡d+L(12d2+13d)+2d.N=Vd+T_{\max}d+L(12d^2+13d)+2d.

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 N=124 439 808N=124\,439\,808. 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 m×nm\times n matrix applied to a vector costs 2mn2mn. Per token and block, projections cost 2(3d2+d2+4d2+4d2)=24d22(3d^2+d^2+4d^2+4d^2)=24d^2, and vocabulary readout costs 2dV2dV. Attention depends on how many query-key pairs are computed. A kernel materializing the full matrix does 2Td2Td for QK⊤\mat{Q}\mat{K}\T and another 2Td2Td for multiplication by V\mat{V} at each position, summed over heads. With the mask, position ii needs only ii keys, averaging (T+1)/2(T+1)/2 over i=1,…,Ti=1,\dots,T. Therefore, a batch forward pass costs

BT (24Ld2+2dV)+4LBT2d⏟denseorBT (24Ld2+2dV)+2LBT(T+1)d⏟causal ideal.\underbrace{BT\,(24Ld^2+2dV)+4LBT^2d}_{\text{dense}} \qquad\text{or}\qquad \underbrace{BT\,(24Ld^2+2dV)+2LBT(T+1)d}_{\text{causal ideal}} .

For GPT-2 small with T=1024T=1024, 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, 2N=248 879 6162N=248\,879\,616: 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 BTdBTd or BT2HBT^2H, not BTd2BTd^2. 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 1/2L1/\sqrt{2L}

GPT initialization samples all linear-layer and embedding weights as independent zero-mean normal variables with standard deviation σ=0.02\sigma=0.02, zeros biases, sets LayerNorm to γ=1\vb{\gamma}=\vb{1} and β=0\vb{\beta}=\vb{0}, and reduces standard deviation to σ/2L\sigma/\sqrt{2L} 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 1/N1/\sqrt{N}, where NN is the number of residual layers. There are two branches per block, so N=2LN=2L, 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 2L2L branches in order, j=1,…,2Lj=1,\dots,2L, and fix one coordinate and position. After branch kk, the residual is rk=r0+s∑j≤kujr_k=r_0+s\sum_{j\le k}u_j, where uju_j is what branch jj would write with its output projection unscaled and ss is the scale factor, s=1s=1 without scaling and s=1/2Ls=1/\sqrt{2L} 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 Var⁡(s uj)=s2Var⁡(uj)≤s2C\operatorname{Var}(s\,u_j)=s^2\operatorname{Var}(u_j)\le s^2C. Summing the 2L2L terms gives the equality and bound; with s2=1/(2L)s^2=1/(2L), the factor 2L2L 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 jj computes uj=Wjhju_j=\mat{W}_j\vb{h}_j for the fixed coordinate’s row, where Wj\mat{W}_j is its output projection and hj\vb{h}_j its internal vector: attention output before c_proj or GELU output before mlp.c_proj. The vector hj\vb{h}_j depends on embeddings, previous branches, and the other weights of branch jj; Wj\mat{W}_j is independent of all of them. Let Fj−1\mathcal{F}_{j-1} denote information generated by those variables. Because Wj\mat{W}_j has mean zero and is independent of Fj−1\mathcal{F}_{j-1}, E[uj∣Fj−1]=E[Wj] hj=0\mathbb{E}[u_j\mid\mathcal{F}_{j-1}]=\mathbb{E}[\mat{W}_j]\,\vb{h}_j=0. For i<ji<j, uiu_i and r0r_0 are Fj−1\mathcal{F}_{j-1}-measurable, so E[uiuj]=E[ui E[uj∣Fj−1]]=0\mathbb{E}[u_iu_j]=\mathbb{E}\bigl[u_i\,\mathbb{E}[u_j\mid\mathcal{F}_{j-1}]\bigr]=0, and likewise for r0r_0. Since all means are zero, with r0r_0 the sum of two centered weights, covariances vanish: the uju_j are martingale differences.

Variances. r0r_0 is the sum of independent entries of E\mat{E} and P\mat{P}, so Var⁡(r0)=2σ2\operatorname{Var}(r_0)=2\sigma^2. Conditioning on hj\vb{h}_j, the coordinate uju_j is a combination of independent N(0,σ2)\mathcal{N}(0,\sigma^2) entries with coefficients hj\vb{h}_j, so Var⁡(uj)=σ2 E∥hj∥2\operatorname{Var}(u_j)=\sigma^2\,\mathbb{E}\norm{\vb{h}_j}^2. It remains to bound E∥hj∥2\mathbb{E}\norm{\vb{h}_j}^2. LayerNorm output y\vb{y} satisfies ∥y∥2=d s2/(s2+ε)≤d\norm{\vb{y}}^2=d\,s^2/(s^2+\varepsilon)\le d regardless of input: this is where pre-norm acts.

  • In the MLP, h=GELU⁡(Ay)\vb{h}=\operatorname{GELU}(\mat{A}\vb{y}) with A∈R4d×d\mat{A}\in\R^{4d\times d}. Since ∣GELU⁡(z)∣≤∣z∣\abs{\operatorname{GELU}(z)}\le\abs{z} because the factor 12(1+tanh⁡⋅)\tfrac12(1+\tanh\cdot) is in (0,1)(0,1), E∥h∥2≤E∥Ay∥2=4d σ2 E∥y∥2≤4d2σ2\mathbb{E}\norm{\vb{h}}^2\le\mathbb{E}\norm{\mat{A}\vb{y}}^2=4d\,\sigma^2\,\mathbb{E}\norm{\vb{y}}^2\le4d^2\sigma^2.
  • In attention, the part of hi\vb{h}_i for head cc is ∑t≤iAitcvtc\sum_{t\le i}A^{c}_{it}\vb{v}^{c}_t, a convex combination. By convexity of ∥⋅∥2\norm{\cdot}^2, its squared norm is at most ∑tAitc∥vtc∥2\sum_t A^{c}_{it}\norm{\vb{v}^c_t}^2. Weights AcA^c depend on WQ,WK\mat{W}_Q,\mat{W}_K and the yt\vb{y}_t, but not WV\mat{W}_V, and E[∥vtc∥2∣yt]=dhσ2∥yt∥2≤dhdσ2\mathbb{E}[\norm{\vb{v}^c_t}^2\mid\vb{y}_t]=d_h\sigma^2\norm{\vb{y}_t}^2\le d_hd\sigma^2. Summing the HH heads gives E∥hi∥2≤Hdhdσ2=d2σ2\mathbb{E}\norm{\vb{h}_i}^2\le Hd_hd\sigma^2=d^2\sigma^2.

In both cases Var⁡(uj)≤4d2σ4\operatorname{Var}(u_j)\le4d^2\sigma^4, and the first theorem yields the bound.

∎

Two observations clarify scope. First, without scaling (s=1s=1), the theorem’s equality says variance is 2σ22\sigma^2 plus the sum of 2L2L 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, d=768d=768, V=50257V=50257, three seeds, and four sequences of 256 positions, with L=12L=12 and L=48L=48, the depth of GPT-2 XL. Variance of r0r_0 is 0.0008, or 2σ22\sigma^2. The largest unscaled branch variance, between 0.13 and 0.15, is well below C=4⋅7682⋅0.024≈0.377C=4\cdot768^2\cdot0.02^4\approx0.377, and Var⁡(r0)+s2∑jVar⁡(uj)\operatorname{Var}(r_0)+s^2\sum_j\operatorname{Var}(u_j) 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 dout×dind_{\mathrm{out}}\times d_{\mathrm{in}} and computes xW⊤+b\vb{x}\mat{W}\T+\vb{b}. GPT-2 was published with a Conv1D layer storing the matrix in the opposite orientation, din×doutd_{\mathrm{in}}\times d_{\mathrm{out}}, and computing xW+b\vb{x}\mat{W}+\vb{b}. 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 (768×2304768\times2304), attn.c_proj (768×768768\times768), mlp.c_fc (768×3072768\times3072), and mlp.c_proj (3072×7683072\times768). 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 max⁡∣zpropio−zref∣\max\abs{z_{\mathrm{propio}}-z_{\mathrm{ref}}} 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 10−410^{-4} 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 2−15≈3.05×10−52^{-15}\approx3.05\times10^{-5}, so 10−410^{-4} 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 6.5×10−46.5\times10^{-4}, already 1.5×10−41.5\times10^{-4} 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 (rtol=1.3×10−6\text{rtol}=1.3\times10^{-6}, atol=10−5\text{atol}=10^{-5}).

If the test fails, compare the first divergent states in order: embeddings, LN⁡1\operatorname{LN}_1, 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.

[ ]Custom GPT and controlsLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What to expect: manual attention and SDPA agree with error on the order of 10−710^{-7}; 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 L=12L=12 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 L=48L=48 figures are summarized in the initialization section.

[ ]Parity with public GPT-2Local GPU
parity()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 100×1024×50257100\times1024\times50257 logits was exactly 0.0 and argmax agreed at every position. With F.linear, error was 6.48×10−46.48\times10^{-4}; 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 10−410^{-4} criterion determines the outcome.

Exercises

NumericCount parameters once
nanoGPT trains the GPT-2 small configuration (12 layers, d = 768, context 1024, 12 heads, tied token and readout weights, LayerNorm and linear biases, no head bias), but pads its vocabulary from 50 257 IDs to 50 304, the next multiple of 64, for GPU-friendly matrix dimensions. How many unique parameters does that model have?
NumericFLOPs per token with context 512
Using the text's convention (multiplication plus addition count as 2 FLOPs, only matrix multiplications, ideal causal attention where position i uses i keys, logits at every position), how many FLOPs per token does a forward pass of GPT-2 small (V = 50 257, d = 768, L = 12) cost on sequences of T = 512?
QuizA load without errors that loads incorrectly
Your loader walks through GPT-2's state_dict and, for each tensor, transposes it if its shape differs from the destination and copies it unchanged if shapes match. Loading ends without errors or extra keys, but logits differ from the reference by more than 100 and argmax barely agrees. What is the cause?
QuizWhen should the mask be applied?
A colleague computes softmax for each score row over all T keys, then multiplies by a triangular mask without renormalizing. They verify that output shape is correct and future-key weights are exactly zero. What is wrong?
CodeCausal attention without SDPA
Complete the 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 NotImplementedError
Shift+Enter to run
ProofWhy variance does not grow with depth
Prove: At GPT-2 initialization, the residual after 2L branches is r = r_0 + s · (u_1 + ... + u_2L), where u_j = W_j h_j is branch j's output with its output projection W_j unscaled and s = 1/sqrt(2L). Prove that Var(r) is bounded independently of L.
0
Independent N(0, σ²) weights, zero biases, LayerNorm with gain 1 and bias 0, no dropout. Vector h_j depends on embeddings, previous branches, and the other weights of branch j, but not on W_j.

Step 1 of 3. Why is Cov(u_i, u_j) = 0 for i < j?

Key idea

A GPT-2 is a stack of pre-norm blocks over a residual stream, with 12d2+13d12d^2+13d 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 1/2L1/\sqrt{2L} 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.