11.2 Decoder-Only Language Models (GPT)
A single TransformerBlock (Section 11.1) maps a sequence of -dimensional token representations to a sequence of the same shape . To turn a stack of causal Transformer blocks into an autoregressive Generative Pre-trained Transformer (GPT) (Radford et al., 2018; Radford et al., 2019; Brown et al., 2020), we wrap blocks between two boundary layers (Figure 11.2.1):
- Input embedding: A token embedding table maps discrete token IDs to vectors in (optionally adding learned absolute position embeddings when rotary position embeddings are not used inside attention).
- Final normalization and language-modeling head: After causal
TransformerBlocklayers, a final normalization layer stabilizes the residual stream and a linear head projects each position to next-token logits , tying the output projection weights to the input embedding table (Press and Wolf, 2017; Inan et al., 2017).
11.2.1 From Blocks to a Language Model#
A GPT from bottom to top. A table embeds the token ids into the residual stream; causal TransformerBlock layers read from and write to the stream; a final normalization and the transposed table turn each position's vector into logits over the vocabulary. The modern configuration shown here rotates queries and keys inside each attention layer via RoPE; GPT-2 instead adds learned position vectors once at the bottom.
Inside each block, CausalAttention fuses the query, key, and value projections, supports grouped-query attention (num_kv_heads num_heads, Section 10.3), optionally rotates queries and keys via RoPE (rope=True, Section 10.4), and applies the causal mask so position attends only to positions :
class CausalAttention(nn.Module):
"""Fused causal self-attention, optionally rotary; num_kv_heads <
num_heads shares each key-value head across a group of queries."""
def __init__(self, num_hiddens, num_heads, *, bias=False, rope=False,
num_kv_heads=None):
super().__init__()
self.num_heads, self.rope = num_heads, rope
self.num_kv_heads = num_kv_heads or num_heads
self.kv_hiddens = self.num_kv_heads * (num_hiddens // num_heads)
self.W_qkv = nn.Linear(num_hiddens, num_hiddens + 2 * self.kv_hiddens,
bias=bias)
self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)
def qkv(self, X, offset=0, tables=None):
"""Queries, keys, and values of X, each (batch, heads, length, head
width), at positions offset, offset + 1, ...; tables, if given, are
the d2l.rope_tables of these positions."""
B, T, D = X.shape
q, k, v = self.W_qkv(X).split([D, self.kv_hiddens, self.kv_hiddens],
-1)
q = q.reshape(B, T, self.num_heads, -1).transpose(1, 2)
k, v = (u.reshape(B, T, self.num_kv_heads, -1).transpose(1, 2)
for u in (k, v))
if self.rope:
q, k = (d2l.rope(u, offset, tables=tables) for u in (q, k))
return q, k, v
def forward(self, X, keys=None, values=None, mask=None, tables=None):
# Self-attention: X also serves as the keys and the values, and the
# mask is causal, so a block's mask argument must stay None
if mask is not None:
raise ValueError('CausalAttention applies its own mask')
q, k, v = self.qkv(X, tables=tables)
Y = F.scaled_dot_product_attention(
q, k, v, is_causal=True,
enable_gqa=self.num_kv_heads < self.num_heads)
return self.W_o(Y.transpose(1, 2).flatten(2)) # (batch, length, d)Our GPT class stacks num_blks configurable TransformerBlock modules (norm='rms', act='swiglu', pos='rope', pre_norm=True by default, while also supporting GPT-2's norm='layer', act='gelu', pos='learned', bias=True) and ties the output projection to the token embedding table token_emb:
class GPT(nn.Module):
"""Decoder-only transformer language model built from configurable
blocks."""
CausalAttention = CausalAttention # A subclass may replace it
def __init__(self, vocab_size, *, num_hiddens=256, num_heads=8,
num_blks=6, max_len=1024, pos='rope', norm='rms',
act='swiglu', pre_norm=True, bias=False, dropout=0,
num_kv_heads=None, ffn_factory=None):
super().__init__()
assert pos in ('rope', 'learned'), f'unknown pos: {pos!r}'
self.pos, self.max_len, self.num_hiddens = pos, max_len, num_hiddens
self.head_width = num_hiddens // num_heads
self.token_emb = nn.Embedding(vocab_size, num_hiddens)
nn.init.normal_(self.token_emb.weight, std=0.02)
if pos == 'learned':
self.pos_emb = nn.Embedding(max_len, num_hiddens)
nn.init.normal_(self.pos_emb.weight, std=0.02)
attn = lambda: self.CausalAttention(
num_hiddens, num_heads, bias=bias, rope=pos == 'rope',
num_kv_heads=num_kv_heads)
self.blks = nn.ModuleList([
d2l.TransformerBlock(num_hiddens, num_heads, dropout=dropout,
norm=norm, act=act, pre_norm=pre_norm,
bias=bias, attn_factory=attn,
ffn_factory=ffn_factory)
for _ in range(num_blks)])
self.norm = (nn.RMSNorm if norm == 'rms'
else nn.LayerNorm)(num_hiddens, eps=1e-5)
self.init_weights()
def forward(self, X): # X: (batch, T) token ids
H, tables = self.token_emb(X), None # (batch, T, d)
if self.pos == 'learned':
H = H + self.pos_emb(torch.arange(X.shape[1], device=X.device))
else: # RoPE angles of positions 0, ..., T - 1, for every block
tables = d2l.rope_tables(X.shape[1], self.head_width,
device=X.device)
for blk in self.blks: # L blocks, causal attention
H = blk(H, tables=tables)
return F.linear(self.norm(H), self.token_emb.weight) # (batch, T, V)Following GPT-2 (Radford et al., 2019) and Section 11.1.2.2, init_weights draws linear and embedding weights from while scaling the two residual output projections of each block (attention.W_o and ffn.W_2) by :
@d2l.add_to_class(GPT)
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 in self.named_modules():
if isinstance(m, nn.Linear):
std = 0.02 / (2 * L) ** 0.5 if name.endswith(
('W_o', 'W_2')) else 0.02
nn.init.normal_(m.weight, std=std)
if m.bias is not None:
nn.init.zeros_(m.bias)11.2.2 Training a Byte-Level GPT on WikiText-103#
To keep our from-scratch experiments self-contained and free of tokenizer artifacts, we train directly on raw UTF-8 bytes () from WikiText-103 (Merity et al., 2016) using mini-batches of windows of length bytes ( tokens per step):
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
We also define a convenience constructor gpt(...) that builds a freshly initialized GPT ready to train:
gpt moves the model to the GPU, compiles it with torch.compile, and lets fp32 matrix products use the tf32 tensor cores.
torch.set_float32_matmul_precision('high') # fp32 matmuls may use tf32
def gpt(*args, **kwargs): # A fresh model, on the GPU, compiled
return torch.compile(GPT(*args, **kwargs).to(d2l.try_gpu()))11.2.2.1 The Autoregressive Objective#
Given an input window and shifted target window , the causal mask ensures that row of the output logits depends only on . Training minimizes the mean cross-entropy loss across all positions in parallel:
At initialization, before any learning occurs, the model assigns roughly uniform probability to every byte, so the initial cross-entropy loss is close to nats/byte. First, we inspect one shifted input--target window pair (X[0], Y[0]) alongside a lower-triangular causal mask:
start = data.train.tobytes().find(b'the European lobster')
X, Y = data.windows(data.train, [start]) # One window and its targets
print('X[0]:', repr(data.vocab.decode(X[0, :24].tolist())))
print('Y[0]:', repr(data.vocab.decode(Y[0, :24].tolist())))
print(np.asarray(d2l.causal_mask(5)).astype(int))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]]
Evaluating our freshly initialized 6-block GPT ( parameters) on a validation minibatch confirms that its untrained cross-entropy sits close to nats/byte:
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
11.2.2.2 The Training Recipe (LMOptimizer)#
Modern LLM pretraining pairs AdamW (Section 9.5, using standard momentum parameters by default, or in large-batch runs) with selective weight decay (applying weight decay only to 2D linear projection matrices while exempting embeddings, biases, and 1D normalization scales), linear warmup followed by cosine learning-rate decay (Section 9.7), and global gradient-norm clipping ():
class LMOptimizer:
"""AdamW with weight decay on the weight matrices only, a linear warmup
and a cosine decay of the learning rate, and gradient-norm clipping."""
def __init__(self, model, lr, num_steps, warmup, weight_decay=0.1,
max_norm=1.0):
named = list(model.named_parameters())
# Embedding tables are named *emb* (token_emb, pos_emb) by convention
decay = [p for n, p in named if p.ndim == 2 and 'emb' not in n]
rest = [p for n, p in named if p.ndim != 2 or 'emb' in n]
self.optimizer = torch.optim.AdamW(
[{'params': decay, 'weight_decay': weight_decay},
{'params': rest, 'weight_decay': 0.0}], lr=lr)
self.scheduler = torch.optim.lr_scheduler.LambdaLR(
self.optimizer, lambda t: d2l.cosine_warmup(t, num_steps, warmup))
self.params, self.max_norm = decay + rest, max_norm
def zero_grad(self):
self.optimizer.zero_grad()
def step(self):
nn.utils.clip_grad_norm_(self.params, self.max_norm)
self.optimizer.step()
self.scheduler.step()Training our 6-block byte-level GPT (, parameters) for 1,000 steps ( bytes) drives validation cross-entropy well below both the empirical unigram entropy ( nats/byte) and the empirical bigram entropy ( nats/byte) of English Wikipedia text:
model = gpt(len(data.vocab), max_len=128)
num_steps, every = 1000, 50
optimizer = LMOptimizer(model, lr=2e-3, num_steps=num_steps, warmup=100)
steps, train_curve, val_curve, timer = [], [], [], d2l.Timer()
for step in range(every, num_steps + 1, every):
timer.start()
losses = d2l.train_steps(model, data, optimizer, every)
timer.stop() # Training time only, without the validation passes
steps.append(step)
train_curve.append(sum(losses) / every)
val_curve.append(math.log(d2l.lm_perplexity(model, data.val_dataloader())))
d2l.plot(steps, [train_curve, val_curve], 'step', 'loss (nats)',
legend=['train', 'validation'], fmts=('-', '--'))
print(f'step {num_steps}: train {train_curve[-1]:.2f}, '
f'validation {val_curve[-1]:.2f} nats per byte; '
f'{timer.sum():.0f} s of training')step 1000: train 1.36, validation 1.34 nats per byte; 14 s of training
For reference, we compute the empirical unigram and bigram byte entropies directly from the first bytes of the training corpus to verify how far the 6-block Transformer progresses beyond local character statistics:
text = data.train[:10**7].astype(np.int64) # The first 10M training bytes
V = 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
11.2.3 Controlled Comparisons#
11.2.3.1 Run-to-Run Spread and FFN Activation (SwiGLU vs. GELU)#
To separate genuine architectural improvements from random seed noise, we train three independent seeds of our default SwiGLU model and three seeds of a parameter-matched GELU model (act='gelu'):
def train_lm(model, data, lr=2e-3, num_steps=1000, warmup=100):
"""Train with the recipe of the main run; return milliseconds per step."""
optimizer = LMOptimizer(model, lr=lr, num_steps=num_steps, warmup=warmup)
# One untimed call of 50 steps warms up (JAX compiles), the rest is timed
bench = d2l.Benchmark(lambda: d2l.train_steps(model, data, optimizer, 50),
warmup=1, repeats=num_steps // 50 - 1)
return 1000 * bench.time / 50
runs = {'swiglu': [val_curve[-1]], 'gelu': []} # The main run comes first
times = {'swiglu': [], 'gelu': []} # Milliseconds per step
for act, repeats in (('swiglu', 2), ('gelu', 3)):
for _ in range(repeats):
net = gpt(len(data.vocab), act=act, max_len=128)
times[act].append(train_lm(net, data))
runs[act].append(math.log(d2l.lm_perplexity(net,
data.val_dataloader())))
print(f'{act:>6} ({d2l.num_params(net):,} parameters): validation '
+ ', '.join(f'{v:.3f}' for v in runs[act])
+ f'; mean {np.mean(runs[act]):.3f}, range {np.ptp(runs[act]):.3f}')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
Run-to-run variation across random seeds is only nats/byte, whereas SwiGLU consistently beats GELU at the same parameter and FLOP budget by nats/byte.
With train_lm we can also test the other design choice of Section 11.1, the placement of the normalization. At initialization, Section 11.1.2.2 found nothing wrong with post-norm at the weight scale that init_weights uses: tokens stay apart and the query gradients survive. Whether post-norm also trains as well is a separate question. We train the same model with post-norm blocks (pre_norm=False) three times: with 500 warmup steps, with the 100 steps of the main run, and with none. The peak learning rate is that of the main run in all three:
for warmup in (500, 100, 0): # Post-norm: long, pre-norm's, and no warmup
net = gpt(len(data.vocab), pre_norm=False, max_len=128)
train_lm(net, data, warmup=warmup)
loss = math.log(d2l.lm_perplexity(net, data.val_dataloader()))
print(f'post-norm, warmup {warmup:>3}: validation {loss:.3f}')post-norm, warmup 500: validation 1.381
post-norm, warmup 100: validation 3.174
post-norm, warmup 0: validation 3.174
The answer depends on the warmup. With the 100 warmup steps that train the pre-norm model to about nats per byte, the post-norm model ends at , and so does the run without warmup. We have seen this number before: it is the unigram entropy computed above, so these two models have learned how often each byte occurs and nothing about the bytes that precede it. The early updates are too large. When the learning rate rises to its peak within a few steps, the outputs of the attention and FFN sublayers grow far larger than the normalized residual stream to which they are added. After the normalizations every token then ends with nearly the same final vector, and from the same vector at every position only the byte frequencies can be predicted. The gradients that could pull the tokens apart again shrink with the token spread (Section 11.1.2.2), so training does not recover.
With 500 warmup steps the sublayer outputs stay smaller than the stream, and the post-norm model trains to about nats per byte, a little behind the pre-norm model. The warmup that suffices for pre-norm is thus not enough for post-norm. Where the boundary lies we cannot say: it is not sharp, and at intermediate warmup lengths some runs train and others collapse. This is the behavior Xiong et al. (2020) reported for the original Transformer: post-norm needs a long warmup, whereas pre-norm trains without one and converges faster.
11.2.3.2 Comparing Against a Matched Recurrent Baseline#
How does our 6-block GPT compare against the recurrent language model (d2l.RNNLM, Section 8.4.2) given the same parameter count (, parameters) and training steps? We sweep the RNN learning rate across and compare validation loss as a function of window position (loss_by_position):
def rnnlm(vocab_size, num_hiddens): # The tanh RNN LM of the Basics
return d2l.RNNLM(d2l.RNN(256, num_hiddens), vocab_size).to(d2l.try_gpu())
@torch.inference_mode()
def loss_by_position(model, data):
"""Mean validation loss in nats at each position of the window."""
device = next(model.parameters()).device
total, count = 0, 0
for X, Y in data.val_dataloader():
logits = model(X.to(device)) # (batch, T, V)
total += F.cross_entropy(logits.transpose(1, 2), Y.to(device),
reduction='none').sum(0)
count += len(X)
return (total / count).tolist()We now train two RNNLM seeds at each candidate peak learning rate and compare the best recurrent run against GPT across window positions :
rnn_runs = [] # (validation loss, model, ms per step) of every run
for lr in (1e-3, 2e-3, 4e-3):
for _ in range(2):
rnn = rnnlm(len(data.vocab), 1920)
ms = train_lm(rnn, data, lr=lr)
rnn_runs.append((np.mean(loss_by_position(rnn, data)), rnn, ms))
print(f'RNN ({d2l.num_params(rnn):,} parameters), peak rate {lr:g}: '
'validation ' + ', '.join(f'{r[0]:.3f}' for r in rnn_runs[-2:]))
best = min(rnn_runs, key=lambda run: run[0])
positions = (0, 1, 4, 16, 64, 127)
print('validation loss at positions', ', '.join(map(str, positions)))
for name, net, ms in (('GPT', model, np.mean(times['swiglu'])),
('best RNN', *best[1:])):
loss = loss_by_position(net, data)
print(f'{name:>8}: ' + ' '.join(f'{loss[t]:.2f}' for t in positions)
+ f'; {ms:.1f} ms per training step')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
At position (where only a single byte of context is available), GPT and RNNLM start at nearly the same loss. As more prefix context becomes available (), the Transformer's validation loss drops more steeply than the RNN's because self-attention reads any prior byte in hops rather than compressing history through sequential recurrent steps.
11.2.4 Sampling from the Model#
Autoregressive generation (GPT.generate) appends one token at a time: at each step it feeds the current prefix through the model, divides the final position's logits by a temperature , optionally masks all but the top- highest logits to (Fan et al., 2018), and samples the next token from (greedy decoding, the limit , is the case top_k=1):
@d2l.add_to_class(GPT)
@torch.inference_mode()
def generate(self, prefix, num_tokens, temperature=1.0, top_k=None):
"""Sample a continuation of the token-id list prefix."""
ids = torch.tensor(prefix, device=next(self.parameters()).device)
for _ in range(num_tokens): # The tokens stay on the device
logits = self(ids[None, -self.max_len:])[0, -1] / temperature
if top_k is not None:
cutoff = torch.topk(logits, top_k).values[-1]
logits[logits < cutoff] = -torch.inf
ids = torch.cat((ids, torch.multinomial(F.softmax(logits, -1), 1)))
return ids.tolist()Sampling 120-byte continuations of 'The history of the ' under three (temperature, top_k) settings shows how lower temperature and top- filtering trade diversity for local coherence:
prefix = data.vocab.encode('The history of the ')
for temperature, top_k in ((1.0, None), (0.7, 8), (2.0, None)):
out = model.generate(prefix, 120, temperature=temperature, top_k=top_k)
d2l.print_wrapped(f'T={temperature}, top_k={top_k}: '
+ repr(data.vocab.decode(out)))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'
11.2.5 Loading Pretrained GPT-2 (124M)#
Because our GPT class supports norm='layer', act='gelu', pos='learned', and bias=True, it can instantiate OpenAI's 124M-parameter GPT-2 Small architecture () and load the official model.safetensors weights and byte-level BPE tokenizer (gpt2_tokenizer) directly:
GPT2_URL = 'https://huggingface.co/openai-community/gpt2/resolve/main/'
d2l.DATA_HUB['gpt2-weights'] = (
GPT2_URL + 'model.safetensors',
'89a76996d7c6ee89b86618a265483aab73e61d50')
d2l.DATA_HUB['gpt2-merges'] = (
GPT2_URL + 'merges.txt', '396d4d8ec90cb02f4d56e049e0e4add868bcd943')
d2l.DATA_HUB['gpt2-encoder'] = (
GPT2_URL + 'vocab.json', 'f0223209235343bc067d7da838328bced8085ae1')
def gpt2_tokenizer():
"""GPT-2's byte-level BPE tokenizer, assembled by tiktoken."""
import tiktoken # lazy: d2l itself does not require tiktoken
from tiktoken.load import data_gym_to_mergeable_bpe_ranks
return tiktoken.Encoding(
'gpt2', explicit_n_vocab=50257,
pat_str=d2l.BPETokenizer.GPT2_PATTERN,
mergeable_ranks=data_gym_to_mergeable_bpe_ranks(
d2l.download('gpt2-merges', '../data/gpt2'),
d2l.download('gpt2-encoder', '../data/gpt2')),
special_tokens={'<|endoftext|>': 50256})
enc = gpt2_tokenizer()
ids = enc.encode('Attention is all you need.')
print(ids, [enc.decode([i]) for i in ids])[8086, 1463, 318, 477, 345, 761, 13] ['Att', 'ention', ' is', ' all', ' you', ' need', '.']
safetensors checkpoint keys and our GPT module attributes (Conv1D weights have shape (in, out)).| Checkpoint tensor | GPT attribute | Note |
|---|---|---|
wte.weight | token_emb | Shared with output head (V x d) |
wpe.weight | pos_emb | 1,024 learned position vectors |
h.i.ln_1, h.i.ln_2 | blks[i].norm1, blks[i].norm2 | Pre-attention and pre-FFN LayerNorms |
h.i.attn.c_attn | blks[i].attention.W_qkv | Fused QKV (Conv1D) |
h.i.attn.c_proj | blks[i].attention.W_o | Output projection (Conv1D) |
h.i.mlp.c_fc, h.i.mlp.c_proj | blks[i].ffn.W_1, blks[i].ffn.W_2 | Two-layer GELU MLP (Conv1D) |
ln_f | norm | Final LayerNorm before output head |
nn.Linear stores (out, in), so load_gpt2 transposes every Conv1D weight.
def load_gpt2():
"""GPT-2 small (124M) as a GPT with the released weights, in eval
mode."""
from safetensors.torch import load_file # lazy, like tiktoken above
gpt2 = GPT(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
max_len=1024, pos='learned', norm='layer', act='gelu',
pre_norm=True, bias=True)
weights = load_file(d2l.download('gpt2-weights', '../data/gpt2'))
with torch.no_grad():
gpt2.token_emb.weight.copy_(weights['wte.weight'])
gpt2.pos_emb.weight.copy_(weights['wpe.weight'])
gpt2.norm.weight.copy_(weights['ln_f.weight'])
gpt2.norm.bias.copy_(weights['ln_f.bias'])
for i, blk in enumerate(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: (in, out)
module.weight.copy_(W.T if W.ndim == 2 else W)
module.bias.copy_(weights[key + '.bias'])
return gpt2.eval()
gpt2 = load_gpt2().to(d2l.try_gpu())
print(f'{d2l.num_params(gpt2) / 1e6:.1f}M parameters')124.4M parameters
We verify the loaded checkpoint by computing its cross-entropy on the opening paragraph of The Time Machine ( nats/token, or perplexity ) and generating 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
With the pretrained weights verified, we can prompt gpt2.generate using greedy decoding (top_k=1) for a deterministic continuation:
out = gpt2.generate(enc.encode('Alan Turing theorized that computers '
'would one day become'), 16, top_k=1)
d2l.print_wrapped(enc.decode(out))Alan Turing theorized that computers would one day become the most powerful
machines on the planet.
The computer is a computer that
Switching to stochastic top- sampling (temperature=0.8, top_k=50) over 40 subword tokens produces a fluent, varied completion:
out = gpt2.generate(enc.encode('The secret of a good deep learning '
'textbook is'), 40, temperature=0.8,
top_k=50)
d2l.print_wrapped(enc.decode(out))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.
11.2.6 The Modern Recipe#
Comparing the 2019 load_gpt2() configuration against our default GPT highlights the four core upgrades that define modern open-weights decoder-only language models (Table 11.2.2):
- Normalization: Pre-norm
RMSNormwithout biases (Section 11.1.2.4) instead ofLayerNorm, often paired with per-head QK-Norm (Section 11.1.2.5) or sublayer-output normalization (OLMo 2, Gemma 3). - Positions: Rotary Position Embeddings (RoPE) (Section 10.4) inside each attention layer instead of a fixed learned position table
wpe. - Feed-forward network: Bias-free gated
SwiGLU(orGeGLU) instead of a two-layerGELUMLP. - Inference cache & capacity scaling: Grouped-query attention (GQA), sliding-window attention, or low-rank latent compression (MLA) to shrink the KV cache (Section 11.3), and Mixture-of-Experts (MoE) layers (Section 11.7) to scale total parameters without scaling per-token FLOPs.
| Model | Attention and cache | Normalization | Positions | FFN | Dense or MoE |
|---|---|---|---|---|---|
| Mistral 7B (2023) (Jiang et al., 2023) | GQA ; sliding window 4096 | RMSNorm, pre | RoPE, base | SwiGLU | Dense |
| Llama 3 (2024) | GQA (8B), (70B), (405B) | RMSNorm, pre | RoPE, base | SwiGLU | Dense |
| Qwen3 (2025) (Yang et al., 2025) | GQA: dense (32B), MoE (235B-A22B) | RMSNorm, pre; QK-norm | RoPE, base ; YaRN | SwiGLU | Dense, and MoE: 128 experts, 8 active |
| OLMo 2/3 (2024/25) (OLMo et al., 2025; OLMo, 2025) | MHA (7B), GQA (32B); OLMo 3: window 4096 on 3 of 4 layers | RMSNorm on sublayer outputs; QK-norm | RoPE | SwiGLU | Dense |
| DeepSeek-V3 (2024) (DeepSeek-AI et al., 2024) | MLA: KV compressed to a 512-dim latent | RMSNorm, pre | Decoupled RoPE (64-dim shared key) | SwiGLU | MoE: 256 experts + 1 shared, 8 active |
| Gemma 3 (2025) (Team, 2025) | GQA; local:global , window 1024 | RMSNorm, pre and post; QK-norm | RoPE, base global, local | GeGLU | Dense |
| gpt-oss (2025) (OpenAI, 2025) | GQA ; window 128 on alternate layers; learned sinks | RMSNorm, pre | RoPE; YaRN | SwiGLU, clamped | MoE: 128 or 32 experts, 4 active |
11.2.7 Summary#
A decoder-only GPT places causal TransformerBlock layers between a token embedding table and a final normalization plus weight-tied output projection , predicting next-token logits at all sequence positions in a single parallel forward pass ((11.2.1)). Training with AdamW (applying weight decay selectively to 2D matrices), linear warmup, cosine decay, and gradient clipping (LMOptimizer) drives our 4.8M-parameter byte-level GPT well below the bigram entropy of English text within 1,000 steps. In controlled comparisons at matched parameter count and compute, SwiGLU outperforms GELU by roughly nats/byte against a -nat seed spread, and GPT opens a steadily widening advantage over a matched RNNLM at deeper context positions . Contemporary open-weights LLMs (Table 11.2.2) share this pre-norm RMSNorm + RoPE + SwiGLU/GeGLU recipe, differing mainly in how they compress the KV cache (Section 11.3) and whether they replace the dense FFN with a Mixture of Experts (Section 11.7).
11.2.8 Exercises#
-
Ablating the training recipe (
LMOptimizer).LMOptimizercombines four ingredients: selective weight decay ( on 2D weight matrices only), linear warmup (100 steps), cosine decay, and global gradient clipping (). Train our 6-block byte-levelGPTfor 1,000 steps while disabling one ingredient at a time: (a) applying weight decay to all parameters including embeddings and RMSNorm gains, (b) no warmup (warmup=0), (c) constant learning rate (lr=2e-3throughout), and (d) no gradient clipping. Which single change hurts validation loss the most? -
Auditing the GPT-2 checkpoint tensor map. The GPT-2
model.safetensorsfile holds 148 weight/bias tensors (plus 12 legacy causal mask buffersh.i.attn.bias). Write a short check verifying thatd2l.num_params(gpt2)equals the total element count of the 148 parameter tensors in the file (), and explain from your framework's linear-layer weight layout whetherc_attn.weightmust be transposed on load. -
Zero-layer tied-embedding baseline (). Consider
GPTwithnum_blks=0: input token is embedded as , normalized byRMSNorm, and dotted with to produce logits .- What class of statistical language model (-gram order) can a 0-block model represent?
- Why does tying the input and output embeddings () force the symmetric matrix to assign its largest diagonal entry to if all rows of have equal norm, and how does the untied or 1-block model break this symmetry?
-
Comparing bits-per-byte across tokenizers (Byte-level GPT vs. BPE GPT-2). A byte-level model reports cross-entropy in nats/byte, whereas GPT-2 reports cross-entropy in nats/subword-token.
- Show that on any passage of UTF-8 bytes that
enc.encodetokenizes into subword tokens, the exact bits-per-byte (bpb) of a subword model with mean per-token negative log-likelihood (in nats/token) is . - Evaluate both our 4.8M-parameter byte-level
modeland pretrained 124M-parametergpt2in bits-per-byte on the first 10,000 bytes of the WikiText-103 validation set.
- Show that on any passage of UTF-8 bytes that
-
Top- (nucleus) sampling. Extend
GPT.generatewith an optionaltop_pargument () (Holtzman et al., 2020) that sorts the temperature-scaled probabilities in descending order and masks out tokens beyond the smallest prefix whose cumulative probability exceeds . Compare completions fromgpt2on the prompt"Alan Turing theorized that computers would"usingtop_p=0.9, temperature=0.8versus unfilteredtemperature=1.2. -
Learning-rate stability with QK-Norm. Train our 6-block byte-level
GPTacross peak learning rates with standardCausalAttentionversus a variant that appliesRMSNorm(d_h)toqandkinsideCausalAttention.qkv(Section 11.1.2.5). How does QK-Norm shift the maximum stable learning rate?