One Window of Length T Trains T Prediction Problems
Motivation
An autoregressive language model factors sequence probability via the chain rule P(x_{1:T+1}) = \prod_{t=1}^T P(x_{t+1} \mid x_{1:t}).
Parallel teacher forcing: Rather than running T separate forward passes for prefixes of length 1, \dots, T, a decoder-only GPT scores all T prefix predictions in one parallel forward pass under a causal mask.
GPT Architecture: Embeddings, Causal Stack, Tied Head
Architecture Overview
Input embedding (\mathbf{E} \in \mathbb{R}^{V \times d}): Maps discrete token IDs x_1, \dots, x_T into initial residual stream vectors in \mathbb{R}^{B \times T \times d}.
Causal Transformer stack (L blocks): Each TransformerBlock applies causal self-attention and a position-wise FFN to the stream.
Final norm & weight-tied output head (\mathbf{E}^\top): Projects normalized stream vectors to vocabulary logits \mathbf{Z} = \mathrm{Norm}(\mathbf{H}^{(L)})\mathbf{E}^\top \in \mathbb{R}^{B \times T \times V}, reusing \mathbf{E} to save V d parameters (38.6\text{M} in GPT-2 Small).
Fused Causal Self-Attention with RoPE and GQA
Causal Attention
Fused QKV projection: Multiplies \mathbf{X} by one matrix \mathbf{W}_{qkv} \in \mathbb{R}^{d \times (d + 2 H_{\text{kv}} d_h)} and splits into H query heads and H_{\text{kv}} \le H key–value heads.
RoPE + Causal mask (is_causal=True): Rotates queries and keys by position angles and masks s > t to -\infty so \partial \mathbf{z}_t / \partial \mathbf{x}_s = \mathbf{0}.
Positional Information: Learned Tables vs. RoPE
Positional Encodings
pos='learned' (GPT-2, 2019): Adds a lookup row \mathbf{p}_t \in \mathbb{R}^d from pos_emb(T_{\max} \times d) once at the bottom of the stack; hard ceiling at T_{\max} = 1{,}024.
pos='rope' (Default / Llama / Qwen): Rotates (\mathbf{q}_t, \mathbf{k}_s) inside every attention layer using precomputed d2l.rope_tables(T, head_width), giving relative scores that scale to 32\text{K}–1\text{M} tokens.
The Complete GPT Forward Pass in Ten Lines
Forward Implementation
Given token IDs X of shape (batch, T), GPT.forward returns next-token logits of shape (batch, T, V) at every position simultaneously:
def forward(self, X): # X: (batch, T) token ids H, tables =self.token_emb(X), None# (batch, T, d)ifself.pos =='learned': H = H +self.pos_emb(torch.arange(X.shape[1], device=X.device))else: # RoPE cosine/sine tables for positions 0, ..., T - 1 tables = d2l.rope_tables(X.shape[1], self.head_width, device=X.device)for blk inself.blks: # L pre-norm causal Transformer blocks H = blk(H, tables=tables)return F.linear(self.norm(H), self.token_emb.weight) # Weight-tied (batch, T, V)
Tying the output projection to self.token_emb.weight means rare tokens receive gradient updates both when they appear in the input prefix and when they are contrasted in the softmax denominator.
Depth-Scaled Weight Initialization (1/√(2L))
Initialization
init_weights draws embeddings and projections from \mathcal{N}(0, 0.02^2) and scales the two residual write matrices (W_o,W_2) by 1/\sqrt{2L}.
With 2L sublayers writing to the pre-norm stream, this keeps the initial stream variance near the embedding variance from block 1 on.
def init_weights(self):"""GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and zero biases; W_o and W_2, which write to the stream, get std 0.02 / sqrt(2L).""" L =len(self.blks)for name, m inself.named_modules():ifisinstance(m, nn.Linear): std =0.02/ (2* L) **0.5if name.endswith( ('W_o', 'W_2')) else0.02 nn.init.normal_(m.weight, std=std)if m.bias isnotNone: nn.init.zeros_(m.bias)
The Autoregressive Cross-Entropy Objective
Training Objective
Given input window \mathbf{x} = (x_1, \dots, x_T) and shifted targets \mathbf{y} = (x_2, \dots, x_{T+1}), training minimizes mean negative log-likelihood across all B \times T positions:
X[0]: 'the European lobster ) a'
Y[0]: 'he European lobster ) an'
[[1 0 0 0 0]
[1 1 0 0 0]
[1 1 1 0 0]
[1 1 1 1 0]
[1 1 1 1 1]]
Byte-Level Language Modeling on WikiText-103
Corpus & Initialization Check
We train a 6-block byte-level GPT(V = 256, d = 256, H = 8, L = 6, T = 128,4.79\text{M} parameters) on 270\text{M} raw UTF-8 bytes of WikiText-103:
data = d2l.WikiText103(batch_size=64, num_steps=128)print(f'{len(data.train) /1e6:.0f}M training bytes, 'f'{len(data.val) /1e6:.2f}M validation bytes, 'f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256
model = gpt(len(data.vocab), max_len=128)loss = math.log(d2l.lm_perplexity(model, [next(data.val_dataloader())]))print(f'{d2l.num_params(model) /1e6:.2f}M parameters; loss before 'f'training {loss:.2f} nats per byte, log 256 = {math.log(256):.2f}')
4.79M parameters; loss before training 5.66 nats per byte, log 256 = 5.55
Sanity check before training: At step 0, random logits assign roughly uniform probability 1/256 to every byte, so the initial loss (5.5\text{--}5.7\text{ nats/byte}) is close to \ln 256 \approx 5.55\text{ nats/byte}.
The Modern Pretraining Optimizer (LMOptimizer)
Optimization Recipe
LMOptimizer combines AdamW (\eta_{\max} = 2 \times 10^{-3}), linear warmup + cosine decay, and global gradient clipping (\le 1.0):\eta_t = \eta_{\max} \cdot \frac{1}{2}\Bigl(1 + \cos\bigl(\pi \tfrac{t - t_w}{S - t_w}\bigr)\Bigr)
Selective weight decay (\lambda = 0.1 on 2D matrices only): Exempts embeddings (*emb*), 1D RMSNorm gains, and biases.
Training Curve and Empirical Entropy Yardsticks
Training Results
Rapid convergence: In 1{,}000 steps (8.2\text{M} bytes, \sim 3\% of the corpus), validation cross-entropy drops from \approx 5.6 to 1.34\text{ nats/byte}(\approx 1.93\text{ bits/byte}).
step 1000: train 1.36, validation 1.34 nats per byte; 14 s of training
Training Curve and Empirical Entropy Yardsticks (cont.)
Training Results
The unigram and bigram yardsticks are plain counts over the first 10\text{M} training bytes:
text = data.train[:10**7].astype(np.int64) # The first 10M training bytesV =len(data.vocab)unigram = np.bincount(text, minlength=V) /len(text)pairs = np.bincount(text[:-1] * V + text[1:], minlength=V * V).reshape(V, V)bigram = pairs / np.maximum(pairs.sum(1, keepdims=True), 1)p = unigram[unigram >0]print(f'unigram {-(p * np.log(p)).sum():.2f}, 'f'bigram {-np.log(bigram[text[:-1], text[1:]]).mean():.2f} 'f'nats per byte')
unigram 3.17, bigram 2.45 nats per byte
Controlled Ablation: Seed Spread vs. SwiGLU Gain
Experimental Rigor
To distinguish genuine architectural improvements from random initialization noise, we train three independent seeds of act='swiglu' and three seeds of parameter-matched act='gelu':
swiglu (4,788,992 parameters): validation 1.339, 1.344, 1.343; mean 1.342, range 0.005
gelu (4,787,456 parameters): validation 1.402, 1.402, 1.402; mean 1.402, range 0.000
Tight run-to-run repeatability: Across three random seeds, validation loss varies by less than 0.01\text{ nats/byte}.
Statistically clear SwiGLU win: At identical parameter count (4.79\text{M}) and step time, SwiGLU beats GELU by \sim 0.06\text{ nats/byte}(> 5\times the seed spread).
Post-norm arm:pre_norm=False blocks with the same 100 warmup steps, or none, end at the unigram entropy, 3.17\text{ nats/byte}: the sublayer outputs outgrow the normalized stream, all tokens end with the same vector, and training does not recover. With 500 warmup steps post-norm trains to about 1.38, a little behind pre-norm (1.34).
Comparison With a Parameter-Matched Recurrent Model
Transformer vs. RNNLM
We train a matched d2l.RNNLM(d_{\text{rnn}} = 1{,}920,4.74\text{M} parameters) across three learning rates and inspect validation loss by window position t \in \{0, 1, 4, 16, 64, 127\}:
RNN (4,739,072 parameters), peak rate 0.001: validation 1.461, 1.461
RNN (4,739,072 parameters), peak rate 0.002: validation 1.474, 1.459
RNN (4,739,072 parameters), peak rate 0.004: validation 1.548, 1.649
validation loss at positions 0, 1, 4, 16, 64, 127
GPT: 2.47 2.15 1.49 1.33 1.33 1.30; 14.1 ms per training step
best RNN: 2.49 2.15 1.56 1.45 1.45 1.44; 10.6 ms per training step
Why the gap widens with context position t: At t = 0 (1 byte of context), both models score about 2.5\text{ nats} (the bigram limit is 2.45). By t = 16 \dots 127, the RNN levels off at about 1.4\text{ nats} because history must squeeze through t sequential \tanh steps, whereas GPT attends directly to any prior byte in O(1) hops (about 1.3\text{ nats}).
Autoregressive Decoding: Temperature and Top-k
Sampling Mechanics
At each decode step, GPT.generate scales logits \mathbf{z}_t \in \mathbb{R}^V by temperature \tau > 0 and truncates to the top-k candidates: p_v = \frac{\exp(z_{t,v} / \tau)}{\sum_{u \in \mathcal{V}_k} \exp(z_{t,u} / \tau)}
Autoregressive Decoding: Temperature and Top-k (cont.)
Sampling Mechanics
\tau = 0.7, k = 8 concentrates probability mass on clean English words, whereas \tau = 2.0 flattens toward gibberish:
T=1.0, top_k=None: 'The history of the 2010 lead in Cecil . The shiwn trees
about his improvement appearances helped attack actual film songs , were
aportimely'
T=0.7, top_k=8: 'The history of the story to the ship wife . \n = = =
Control = = = \n The contrast of the final part of the time , and
interviewers , and the'
T=2.0, top_k=None: 'The history of the
lar��\u038d\u038d���Е�;v���ױ����岙��Ӄ�\x1c,ϐ \n
Trenreodoviti��Ě�\x08q���nve VS ÷tu KopaxodSq ;
�t3nĀohjnetoKcckakizonþon U�6'
Loading Pretrained OpenAI GPT-2 Small (124M)
Checkpoint Loading
Passing GPT-2’s 2019 settings (norm='layer',act='gelu', pos='learned', bias=True) into d2l.GPT instantiates the exact GPT-2 Small architecture:
OpenAI’s original TensorFlow GPT-2 code used Conv1D layers that store weight matrices as (in_features, out_features), whereas PyTorch’s nn.Linear stores (out_features, in_features):
for i, blk inenumerate(gpt2.blks): modules = {f'h.{i}.ln_1': blk.norm1, f'h.{i}.ln_2': blk.norm2,f'h.{i}.attn.c_attn': blk.attention.W_qkv,f'h.{i}.attn.c_proj': blk.attention.W_o,f'h.{i}.mlp.c_fc': blk.ffn.W_1, f'h.{i}.mlp.c_proj': blk.ffn.W_2}for key, module in modules.items(): W = weights[key +'.weight'] # Conv1D layout: (in, out) module.weight.copy_(W.T if W.ndim ==2else W) # Transpose 2D matrices module.bias.copy_(weights[key +'.bias'])
Silent bug hazard: Because c_proj has square shape (768, 768), forgetting .T passes every shape assertion without error—only a perplexity check on real text catches the transposed matrix.
Validating Loaded GPT-2 Small via Perplexity & Text
Checkpoint Verification
Evaluating the loaded 124.4M-parameter gpt2 model on The Time Machine yields a per-token cross-entropy of 3.89\text{ nats} (perplexity e^{3.89} \approx 49, compared to 50{,}257 for uniform guessing) and coherent greedy/sampled continuations:
text = ("The Time Machine, by H. G. Wells. The Time Traveller was ""expounding a recondite matter to us.")x = torch.tensor(enc.encode(text), device=d2l.try_gpu())[None]with torch.inference_mode(): logits = gpt2(x)loss = F.cross_entropy(logits[0, :-1], x[0, 1:])print(f'per-token loss {loss.item():.2f}, 'f'perplexity {loss.exp().item():.0f}')
per-token loss 3.89, perplexity 49
Greedy and Sampled Continuations from GPT-2 Small
Checkpoint Verification
Alan Turing theorized that computers would one day become the most powerful
machines on the planet.
The computer is a computer that
The secret of a good deep learning textbook is that it can be read by
anyone. The easiest way to learn a deep learning language is to read the
book, or the software. It's also the easiest way to learn a framework.
The Architectural Recipe of Modern Open-Weights LLMs
Frontier Comparison
Every major open-weights decoder-only family (2023–2025) shares our default GPT backbone (RMSNorm,RoPE, SwiGLU).
Two frontier axes of differentiation:
KV-cache compression (§11.3): GQA (32{:}8 or 64{:}8), 5{:}1 local/global windows (Gemma 3), or low-rank MLA (DeepSeek-V3).
FFN sparsity (§11.7): Dense SwiGLU vs. fine-grained MoE (128–256 experts).
Concept Check: Parameters, Perplexity, and Symmetry
Check Your Understanding
Test your understanding with three concrete calculations:
Sizing GPT-2 Medium: GPT-2 Medium has L = 24 blocks, width d = 1024, vocabulary V = 50{,}257, T_{\max} = 1024 learned positions, and a weight-tied head. Estimate its total parameter count.
Perplexity as effective branching factor: Our byte-level GPT reaches 1.35\text{ nats/byte}, while GPT-2 Small scores 3.89\text{ nats/token} on The Time Machine. How many equally likely choices does each loss correspond to?
Zero-layer weight-tying pitfall: If num_blks=0 and all rows of \mathbf{E} have unit norm, which next token x_{t+1} always receives the highest logit in \mathbf{z}_t = \mathbf{e}_{x_t}\mathbf{E}^\top?
Answers:
\approx 355\text{M} parameters:24 \times 12(1024)^2 \approx 302.0\text{M} in the blocks + 50{,}257 \times 1024 \approx 51.5\text{M} in token_emb+ 1.0\text{M} in pos_emb.
e^{1.35} \approx 3.9 bytes out of 256 for our byte model; e^{3.89} \approx 49 subword tokens out of 50{,}257 for GPT-2.
x_{t+1} = x_t (repeating the current token): the symmetric Gram matrix \mathbf{E}\mathbf{E}^\top maximizes \mathbf{e}_i^\top \mathbf{e}_j on the diagonal j = i. Attention and FFNs break this symmetry.
Summary: Building and Training a Decoder-Only GPT
Key Takeaways
Causal Stack & Tied Head: Fused \mathbf{W}_{qkv}, RoPE, lower-triangular mask, and shared \mathbf{E} \in \mathbb{R}^{V \times d} train all T prefix predictions in one pass.
1/√(2L) Init & LMOptimizer: AdamW with 2D-only weight decay and warmup + cosine decay reaches 1.34\text{ nats/byte} in 1{,}000 steps.
Controlled Baselines & GPT-2 Loading:SwiGLU beats GELU by 0.06\text{ nats}; loads official 124M GPT-2 directly.