9.3 Two Test Models
Analytical models such as the two-dimensional quadratic valley explain how curvature and gradient noise govern simple update rules, but evaluating modern optimizers requires empirical measurement on real neural networks. Why does AdamW outperform SGD by a wide margin on Transformers while offering a much smaller advantage on convolutional networks? Answering such questions requires training actual models under a controlled experimental protocol.
Because stochastic training runs vary across random initializations and minibatch draws, a difference between two optimizer configurations is meaningful only if it exceeds the run-to-run variation of a single configuration. This section defines the two benchmark architectures used throughout the rest of this chapter: the byte-level Transformer language model TinyLM ( parameters) and the convolutional classifier FashionCNN ( parameters), along with our shared training loop, learning-rate sweep harness, baseline SGD measurements, and significance thresholds.
import os
import pandas as pd
import random
import textwrap9.3.1 The Language Model TinyLM#
TinyLM is an autoregressive byte-level language model that predicts the next UTF-8 byte () given a context window of consecutive bytes (Section 8.2). A standard -step run with minibatches of windows processes target bytes. To avoid repeating training examples (which would conflate optimization speed with memorization), we train on the first shard of WikiText-103 (Merity et al., 2016) ( UTF-8 bytes of Wikipedia articles). Each training minibatch samples windows at random byte offsets, so a -step run sees only of the corpus and every training step evaluates fresh text. Validation perplexity is measured on consecutive non-overlapping windows of the -byte validation split.
class WikiText103(d2l.DataModule):
"""WikiText-103 as UTF-8 bytes, cut into windows of num_steps bytes."""
def __init__(self, batch_size, num_steps, num_train=None, num_val=None):
super().__init__()
self.save_hyperparameters()
self.vocab = d2l.BPETokenizer(vocab_size=256, specials=()) # Bytes
self.train = self._read('train-00000-of-00002',
'3cbc792dfc0eeedf8d7333acdc15a9f536032d9a')
self.val = self._read('validation-00000-of-00001',
'49d15019b0476afc752bd5f010b5a2aab2de89ca')
self.train, self.val = self.train[:num_train], self.val[:num_val]
def _read(self, split, sha1):
url = ('https://huggingface.co/datasets/Salesforce/wikitext/resolve/'
f'main/wikitext-103-raw-v1/{split}.parquet')
fname = d2l.download(url, os.path.join(self.root, 'wikitext-103'),
sha1)
lines = pd.read_parquet(fname)['text'] # Each line ends with '\n'
return np.frombuffer(b''.join(s.encode() for s in lines), np.uint8)
def windows(self, corpus, starts):
"""Inputs and next-byte targets of the windows at `starts`."""
idx = np.asarray(starts)[:, None] + np.arange(self.num_steps + 1)
array = torch.from_numpy(corpus[idx].astype(np.int64))
return array[:, :-1], array[:, 1:]
def train_dataloader(self): # A pass of minibatches at random offsets
n = len(self.train) - self.num_steps
for _ in range(n // (self.batch_size * self.num_steps)):
yield self.windows(self.train,
torch.randint(n, (self.batch_size,)).numpy())
def val_dataloader(self): # Consecutive, non-overlapping windows
starts = np.arange(0, len(self.val) - self.num_steps, self.num_steps)
for i in range(0, len(starts), self.batch_size):
yield self.windows(self.val, starts[i:i + self.batch_size])Instantiating WikiText103(batch_size=64, num_steps=64) downloads the training and validation shards and decodes the opening bytes of the corpus:
data = WikiText103(batch_size=64, num_steps=64)
print(f'{len(data.train):,} training bytes, '
f'{len(data.val):,} validation bytes')
text = data.vocab.decode(data.train[:300])
print('\n'.join(textwrap.fill(line, 72) for line in text.splitlines()))269,630,498 training bytes, 1,144,248 validation bytes
= Valkyria Chronicles III =
Senjō no Valkyria 3 : Unrecorded Chronicles ( Japanese : 戦場のヴァルキュリア3 ,
lit . Valkyria of the Battlefield 3 ) , commonly referred to as Valkyria
Chronicles III outside Japan , is a tactical role @-@ playing video game
developed by Sega and Media.Vis
9.3.1.1 Architecture and Parameter Groups#
TinyLM is a two-block decoder-only Transformer (Chapter 11) with embedding width , causal attention heads, and a two-layer GELU MLP of hidden width per block. Each sublayer is preceded by LayerNorm (Section 7.3.4.1) and wrapped in a residual connection, followed by a final LayerNorm and linear output head projecting to byte logits. Embedding rows are initialized from , and all linear weights and biases are drawn uniformly from .
class TinyLM(nn.Module):
"""A small decoder-only transformer language model."""
def __init__(self, vocab_size, d_model=128, num_heads=2, num_blks=2,
max_len=64):
super().__init__()
self.num_heads = num_heads
self.token_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Embedding(max_len, d_model)
self.blks = nn.ModuleList([nn.ModuleDict(dict(
norm1=nn.LayerNorm(d_model),
qkv=nn.Linear(d_model, 3 * d_model),
proj=nn.Linear(d_model, d_model),
norm2=nn.LayerNorm(d_model),
mlp=nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(),
nn.Linear(4 * d_model, d_model))))
for _ in range(num_blks)])
self.norm = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size)
def attention(self, blk, X):
B, T, D = X.shape
q, k, v = blk['qkv'](X).chunk(3, dim=-1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
for u in (q, k, v))
Y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return blk['proj'](Y.transpose(1, 2).reshape(B, T, D))
def forward(self, X):
H = self.token_emb(X) + self.pos_emb(torch.arange(X.shape[1],
device=X.device))
for blk in self.blks:
H = H + self.attention(blk, blk['norm1'](H))
H = H + blk['mlp'](blk['norm2'](H))
return self.head(self.norm(H))For an optimizer, the parameters of TinyLM divide into three distinct structural groups that later sections treat differently (e.g., for decoupled weight decay in Section 9.5.3 and matrix orthogonalization in Section 9.6):
- Embeddings (): lookup tables (
token_emb,pos_emb) whose rows receive sparse gradients proportional to token frequency. - Weight matrices (): dense 2D projection matrices (
qkv,proj, the two MLP layers per block, andhead). - 1D vectors (): linear biases and LayerNorm scale/shift vectors.
# nn.Linear and nn.Embedding initialize as described above by default;
# nn.GELU is the exact GELU
model = TinyLM(vocab_size=len(data.vocab))
kinds = {'embeddings': 0, 'matrices': 0, 'vectors': 0}
print(f'{"parameter":<22} {"shape":<14} {"count":>7}')
for name, p in model.named_parameters():
kind = ('embeddings' if 'emb' in name else
'matrices' if p.ndim == 2 else 'vectors')
kinds[kind] += p.numel()
print(f'{name:<22} {str(tuple(p.shape)):<14} {p.numel():>7}')
for kind, count in kinds.items():
print(f'{kind:>37} {count:>7}')
print(f'{"total":>37} {sum(kinds.values()):>7}')parameter shape count
token_emb.weight (256, 128) 32768
pos_emb.weight (64, 128) 8192
blks.0.norm1.weight (128,) 128
blks.0.norm1.bias (128,) 128
blks.0.qkv.weight (384, 128) 49152
blks.0.qkv.bias (384,) 384
blks.0.proj.weight (128, 128) 16384
blks.0.proj.bias (128,) 128
blks.0.norm2.weight (128,) 128
blks.0.norm2.bias (128,) 128
blks.0.mlp.0.weight (512, 128) 65536
blks.0.mlp.0.bias (512,) 512
blks.0.mlp.2.weight (128, 512) 65536
blks.0.mlp.2.bias (128,) 128
blks.1.norm1.weight (128,) 128
blks.1.norm1.bias (128,) 128
blks.1.qkv.weight (384, 128) 49152
blks.1.qkv.bias (384,) 384
blks.1.proj.weight (128, 128) 16384
blks.1.proj.bias (128,) 128
blks.1.norm2.weight (128,) 128
blks.1.norm2.bias (128,) 128
blks.1.mlp.0.weight (512, 128) 65536
blks.1.mlp.0.bias (512,) 512
blks.1.mlp.2.weight (128, 512) 65536
blks.1.mlp.2.bias (128,) 128
norm.weight (128,) 128
norm.bias (128,) 128
head.weight (256, 128) 32768
head.bias (256,) 256
embeddings 40960
matrices 425984
vectors 3840
total 470784
9.3.2 The Image Classifier FashionCNN#
Because optimizer rankings on Transformers differ markedly from those on convolutional networks, our second benchmark is FashionCNN, a classifier for Fashion-MNIST images (Section 3.2). Two convolution + ReLU + max-pooling stages ( and channels) reduce the spatial resolution to , followed by two linear layers (). All layers use uniform initialization, totaling parameters.
class FashionCNN(nn.Module):
"""A compact CNN for Fashion-MNIST: two conv-pool stages, two linear."""
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, X):
X = F.max_pool2d(F.relu(self.conv1(X)), 2)
X = F.max_pool2d(F.relu(self.conv2(X)), 2)
return self.fc2(F.relu(self.fc1(X.flatten(1))))We verify with d2l.num_params that FashionCNN has trainable parameters:
# nn.Conv2d and nn.Linear draw from U(-a, a), a = 1/sqrt(fan-in), by default;
# images arrive as (batch, channel, height, width)
print(f'{d2l.num_params(FashionCNN()):,} parameters')421,642 parameters
With batch size , a -step run makes passes over the Fashion-MNIST training images, so we report held-out test accuracy alongside training loss via evaluate_accuracy:
fashion = d2l.FashionMNIST(batch_size=256)
def evaluate_accuracy(model, batches):
"""Fraction of the examples in batches that model classifies correctly."""
device = next(model.parameters()).device
training, correct, total = model.training, 0, 0
model.eval() # Dropout off, batch norm on running statistics
with torch.inference_mode():
for X, y in batches:
y_hat = model(X.to(device)).argmax(dim=1)
correct += (y_hat == y.to(device)).sum()
total += len(y)
model.train(training)
return float(correct) / total9.3.3 Training Harness and Evaluation Helpers#
Both models map a minibatch to logits and minimize mean cross-entropy loss over a fixed step budget. Table 9.3.1 summarizes the training loop and evaluation utilities saved in d2l.
d2l.| Function | Purpose |
|---|---|
train_steps | Train for num_steps steps (or until stop(step) holds) and return the per-step cross-entropy losses |
lm_perplexity | Compute token perplexity over an iterator of batches (Section 8.3) |
evaluate_accuracy | Compute classification accuracy over an iterator of batches |
final_loss | Mean of the last step losses (inf if diverged) |
smooth | Block average over consecutive windows of losses for plotting |
steps_to_reach | First step at which the -step smoothed loss drops to target (or None) |
lr_sweep | Train from identical initial weights across a list of learning rates and return loss curves and evaluation scores |
We first implement train_steps, which minimizes mean cross-entropy over num_steps minibatches (ignoring padding label -100) or until an optional predicate stop(step) holds:
def train_steps(model, data, optimizer, num_steps, *, stop=None):
"""Minimize the mean cross-entropy of the logits model(X) for the labels
Y over the minibatches (X, Y) of data, leaving out the labels -100, for
num_steps steps or until stop(step) is true; return every step's loss."""
device = d2l.try_gpu()
model.to(device)
losses, step = [], 0
while step < num_steps:
for X, Y in data.train_dataloader():
X, Y = X.to(device), Y.to(device)
logits = model(X)
loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
Y.reshape(-1), ignore_index=-100)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.detach())
step += 1
if step >= num_steps or (stop is not None and stop(step)):
return torch.stack(losses).tolist()Next, lm_perplexity evaluates a language model in inference mode over an iterator of minibatches and returns per token:
def lm_perplexity(model, batches):
"""Perplexity of a language model on the minibatches (X, Y) of batches."""
device = next(model.parameters()).device
modes = {m: m.training for m in model.modules()} # Restored at the end
model.eval() # Dropout off while we measure
total, count = 0, 0
with torch.inference_mode():
for X, Y in batches:
logits = model(X.to(device))
total += F.cross_entropy(logits.flatten(0, 1),
Y.to(device).flatten(), reduction='sum')
count += Y.numel()
for m, training in modes.items():
m.training = training
return math.exp(float(total) / count)To summarize and plot noisy step-loss histories, final_loss averages the last step losses, smooth computes -step block averages, and steps_to_reach finds the first step where the smoothed loss reaches target:
def final_loss(losses, k=100):
"""Mean of the last k losses; infinity if the run diverged."""
v = sum(losses[-k:]) / k
return v if math.isfinite(v) else float('inf')
def smooth(losses, k=25):
"""Means over consecutive blocks of k losses, for plotting."""
return [sum(losses[i:i + k]) / k
for i in range(0, len(losses) - k + 1, k)]
def steps_to_reach(losses, target, k=25):
"""First step at which the smoothed losses reach target; None if they
never do."""
for i, v in enumerate(smooth(losses, k)):
if v <= target:
return k * (i + 1)
return NoneFinally, lr_sweep trains a fresh model from the same random seed for every learning rate in lrs, optionally running evaluate(model) every every steps:
def lr_sweep(make_model, make_optimizer, data, lrs, seed,
num_steps=2000, *, evaluate=None, metric='score', every=None,
verbose=True):
"""Train make_model() with make_optimizer(model, lr) for each lr, from
one initialization; return the loss curves and the evaluations."""
every = every or num_steps
curves, scores = {}, {}
for lr in lrs:
torch.manual_seed(seed) # The same initialization for every lr
model = make_model()
optimizer = make_optimizer(model, lr)
curves[lr], scores[lr] = [], []
for _ in range(num_steps // every):
curves[lr] += train_steps(model, data, optimizer, every)
if evaluate is not None:
scores[lr].append(evaluate(model))
line = f'lr {lr:g}: final loss {final_loss(curves[lr]):.3f}'
if scores[lr]:
line += f', {metric} {scores[lr][-1]:.3f}'
if verbose:
print(line)
return curves, scores9.3.4 Baseline Minibatch SGD Runs and Experimental Protocol#
We now establish our baseline with constant-rate minibatch SGD ( steps, no momentum or weight decay). On TinyLM, an untrained model starts slightly above the uniform-distribution cross-entropy nats/byte (at nats/byte due to initial logit variance; Exercise 1). As reference landmarks on WikiText-103, a unigram byte-frequency table achieves nats/byte and a bigram byte-pair table achieves nats/byte (Exercise 6). Figure 9.3.1 places these landmarks on one scale; every loss in this chapter can be read against it.
Loss landmarks for byte-level language modeling on WikiText-103. Gray: the untrained TinyLM and the uniform guess. Blue: unigram and bigram byte tables. Orange: TinyLM after steps of SGD, measured below, and after the best tuned runs later in this chapter.
We first define the model and plain-SGD factory closures make_lm, sgd, and new_seed:
make_lm = lambda: TinyLM(len(data.vocab))
sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr)
new_seed = lambda: random.getrandbits(31)Running lr_sweep on TinyLM across and plotting the step losses against the uniform-guess baseline exhibits the three canonical learning-rate regimes:
lm_sgd, _ = lr_sweep(make_lm, sgd, data, lrs=[0.1, 0.5, 2.5], seed=new_seed())
d2l.plot(list(range(1, 2001)),
list(lm_sgd.values()) + [[math.log(256)] * 2000],
'step', 'training loss', xscale='log', ylim=[1.5, 6],
legend=[f'lr {lr:g}' for lr in lm_sgd] + ['uniform guess'],
legend_loc='outside', figsize=(5, 2.5))lr 0.1: final loss 2.492
lr 0.5: final loss 2.151
lr 2.5: final loss inf
- Too high (): Exceeds the local stability threshold after the first step and diverges to
infwithin ten steps. - Too low (): Descends smoothly but slowly, reaching only nats/byte (bigram level) at step .
- Well-tuned (): Experiences brief early transient spikes as the network navigates initial high-curvature regions, then recovers and reaches about nats/byte.
On FashionCNN, plain SGD at reaches a training loss of and a held-out test accuracy of :
test_acc = lambda model: evaluate_accuracy(model, fashion.val_dataloader())
cnn_sgd, _ = lr_sweep(FashionCNN, sgd, fashion, lrs=[0.3], seed=new_seed(),
evaluate=test_acc, metric='test accuracy')lr 0.3: final loss 0.221, test accuracy 0.901
9.3.4.1 Comparison Protocol and Significance Thresholds#
Following the Deep Learning Tuning Playbook (Godbole et al., 2023), comparing two optimizers fairly requires treating the learning rate as a nuisance hyperparameter that must be swept independently for each method (lr_sweep over a log-spaced grid from shared initial weights) rather than comparing two optimizers at an arbitrary shared learning rate (Schmidt et al., 2021). Alongside the minimum loss achieved at each optimizer's best learning rate, we track its usable learning-rate range (grid points finishing within nats of the optimum).
Across independent random seeds at a well-tuned learning rate, the final -step training loss (final_loss) and validation loss of TinyLM vary over a range of nats, while FashionCNN varies by in training loss and in test accuracy. Adopting a conservative range margin, we treat a single-run difference as statistically meaningful only if it exceeds nats on TinyLM or training loss ( test accuracy) on FashionCNN; smaller differences are treated as ties unless confirmed across multiple seeds.
9.3.5 Summary#
Our empirical comparisons pair two complementary neural network benchmarks: TinyLM ( parameters: 2D projection matrices, embeddings, and 1D vectors), which trains in a single-pass streaming regime on random -byte windows of WikiText-103 so that a -step run evaluates fresh text on every step, and FashionCNN ( parameters), which trains for epochs on -image minibatches of Fashion-MNIST and is evaluated by both training loss and held-out test accuracy. Closed-form uniform, unigram, and bigram byte entropies anchor the TinyLM loss scale before any training takes place. To separate genuine algorithmic improvements from hyperparameter and seed sensitivity, every comparison sweeps the learning rate independently for each optimizer from identical initial weights, reporting both the optimal loss and the usable learning-rate range against a multi-seed significance threshold of nats on TinyLM ( loss or accuracy on FashionCNN).
9.3.6 Exercises#
-
Initial loss before training.
- If logits are drawn i.i.d. from independently of the target, use to show that the expected initial cross-entropy is approximately .
- Given LayerNorm outputs of mean and variance and head weights/biases drawn from , show that and nats, matching the step- loss of
TinyLM. What is the initial loss if the head weights and bias are initialized to zero?
-
[code] Diagnosing loss curves on
FashionCNN. TrainFashionCNNwith plain SGD across and plot the step losses on a logarithmic step axis against the uniform baseline . For the run that stalls near , inspect the fraction of dead ReLU activations across a minibatch to explain why gradients vanish. -
[code] The edge of divergence on
TinyLM. Sweep plain SGD onTinyLMacross across seeds (lr_sweep(..., verbose=False)). Record the survival rate, the step at which divergent runs fail, and the lowest surviving loss. -
[code] Multi-seed spread and standard error. ● Run seeds of
TinyLMwith AdamW (Section 9.5) at (weight_decay=0), compare the sample standard deviation offinal_lossagainst the normal range estimator , and compute how many seeds are required to detect a -nat difference at two standard errors (). -
[code] Training loss vs. validation loss and overfitting small corpora.
- Explain why
final_loss(averaged over the last training steps) is slightly higher ( nats) than the post-step- validation loss onTinyLM, and verify by evaluating the final checkpoint on held-out training windows. - Restrict the corpus to bytes via
WikiText103(batch_size=64, num_steps=64, num_train=100000)( epochs in steps) and plot training vs. validation loss every steps (every=250).
- Explain why
-
[code] Count-based -gram landmarks. Compute the empirical byte unigram entropy ( nats) and add-one smoothed bigram ( nats) and trigram cross-entropies from the first training bytes of
WikiText103evaluated on the validation split, and compare them against the -step SGD (about nats) and AdamW ( nats, Section 9.5) losses ofTinyLM.