Two Test Models

Dive into Deep Learning · §9.3

Two Test Models: TinyLM and FashionCNN
byte-level Transformer · convolutional classifier · count-based landmarks · LR sweep protocol · multi-seed significance

From Solvable Quadratics to Neural Network Benchmarks

Motivation

  • Why quadratics aren’t enough: Neural networks have evolving sharpness \lambda_{\max}(\mathbf{x}_t), 40\times cross-layer gradient disparities, and stochastic seed variance.
  • Three experimental pillars:
    1. Two complementary models: TinyLM (single-pass byte Transformer) and FashionCNN (multi-epoch image CNN).
    2. Untrained loss landmarks: Closed-form uniform, unigram, and bigram byte entropies.
    3. Fair tuning protocol: Independent LR sweep per arm from shared seed with 3\times multi-seed significance thresholds.

Benchmark 1: TinyLM on Single-Pass WikiText-103 Bytes

Language Modeling Benchmark

  • Autoregressive byte prediction (V = 256): Predicts the next UTF-8 byte given a context window of 64 consecutive bytes.
  • Single-pass streaming regime:
    • Corpus: First shard of WikiText-103 (\sim 2.7 \times 10^8 UTF-8 bytes of Wikipedia articles).
    • Minibatch: b = 64 windows of 64 bytes (4{,}096 target bytes/step) sampled at random byte offsets.
    • A 2{,}000-step run processes 8.2 \times 10^6 bytes (\sim 3\% of the corpus), so every training step evaluates fresh, unseen text without memorization.
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

Inside TinyLM: Decoder-Only Transformer Architecture

Transformer Structure

  • Embeddings: \mathbf{H}_0 = \mathbf{E}_{\text{tok}}(\mathbf{X}) + \mathbf{E}_{\text{pos}}(0..63) \in \mathbb{R}^{B \times 64 \times 128}, initialized from \mathcal{N}(\mathbf{0}, \mathbf{I}).
  • Two pre-norm residual blocks (d_{\text{model}} = 128, 2\text{ heads}): \mathbf{H} \leftarrow \mathbf{H} + \text{CausalMHA}(\text{LN}_1(\mathbf{H})) \mathbf{H} \leftarrow \mathbf{H} + \text{MLP}_{\text{GELU}}(\text{LN}_2(\mathbf{H}))
  • Readout head: \text{Linear}_{128 \to 256}(\text{LN}(\mathbf{H})) initialized from \mathcal{U}(-1/\sqrt{\text{fan-in}}, 1/\sqrt{\text{fan-in}}).

Parameter Census of TinyLM: Three Structural Groups

Where the Parameters Live

To an optimizer, TinyLM’s 470{,}784 parameters partition into three distinct structural groups:

  • 1. Dense 2D weight matrices (425{,}984 params, 90.5\%): Four block matrices per layer (qkv 128 \to 384, proj 128 \to 128, mlp 128 \to 512 \to 128) plus output head (128 \to 256). Decayed in AdamW (§9.5); internal matrices orthogonalized in Muon (§9.6).
  • 2. Embedding lookup tables (40{,}960 params, 8.7\%): token_emb (256 \times 128) and pos_emb (64 \times 128); receive sparse row gradients proportional to byte frequency.
  • 3. 1D vectors (3{,}840 params, 0.8\%): Linear biases and LayerNorm scales/shifts.

Parameter Census of TinyLM: Three Structural Groups (cont.)

Where the Parameters Live

The census lists every parameter tensor with its shape and size, then the three group totals:

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
...
head.weight            (256, 128)       32768
head.bias              (256,)             256
                           embeddings   40960
                             matrices  425984
                              vectors    3840
                                total  470784

Benchmark 2: FashionCNN on Fashion-MNIST Images

Convolutional Classifier

  • Why a second architecture? Optimizer gaps that are large on Transformers often shrink on convolutional networks.
  • Architecture (421{,}642 parameters):
    • conv1 (1 \to 32, 3 \times 3, ReLU, 2 \times 2 max-pool \to 32 \times 14 \times 14): 320 params.
    • conv2 (32 \to 64, 3 \times 3, ReLU, 2 \times 2 max-pool \to 64 \times 7 \times 7): 18{,}496 params.
    • fc1 (3{,}136 \to 128, ReLU): 401{,}536 params (95\% of total).
    • fc2 (128 \to 10 logits): 1{,}290 params.
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))))

Comparing Our Two Neural Benchmarks Side by Side

Complementary Regimes

  • Single-pass vs. multi-epoch exposure (2{,}000 steps):
    • TinyLM sees 0.03 epochs (3\% of 270\text{M} bytes)—fresh unseen text on every step without memorization.
    • FashionCNN sees 8.5 epochs (512\text{K} evaluations over 60\text{K} images) and requires held-out test accuracy to track overfitting.
  • Complementary parameter geometry:
    • TinyLM spreads 90.5\% of weights across 9 Transformer matrices plus sparse embeddings; FashionCNN concentrates 95\% of weights in fc1.

Shared Training Harness and Evaluation Utilities

Experimental Infrastructure

  • Controlled sweep & loop (lr_sweep, train_steps): Clones shared seed-0 initial weights across a log-spaced \eta grid and runs T = 2{,}000 minibatches.
  • Smoothed trajectory metrics (final_loss, steps_to_reach): Averages the last k = 100 step losses and finds the first 25-step block reaching a target threshold.
  • Held-out evaluation (lm_perplexity, evaluate_accuracy): Scores 1.1\text{M} validation bytes or 10{,}000 test images in eval mode.

Information-Theoretic Landmarks Before Any Training

Calibrating the Loss Scale

  • Untrained step 1 (\approx 5.71 nats): Random head logits z_i \sim \mathcal{N}(0, s^2) with s^2 \approx 1/3 add variance penalty s^2/2 \approx 0.17 above uniform.
  • Uniform random guess (5.55 nats): \ln 256 (\ln 10 \approx 2.30 on FashionCNN).
  • Unigram byte frequency (\approx 3.18 nats): Marginal UTF-8 counts without context.
  • Bigram table (\approx 2.50 nats): Conditional p(b_t \mid b_{t-1}); beating 2.50 nats demonstrates multi-byte context learning.

Baseline Minibatch SGD on TinyLM Across Three Rates

Three Canonical Regimes

  • Sweeping plain minibatch SGD (no momentum, no weight decay, 2{,}000 steps) across \eta \in \{0.1, 0.5, 2.5\} from identical initial weights reveals three distinct trajectories:
    • \eta = 0.1 (blue): Smooth, monotonic descent that finishes at about 2.5 nats—barely reaching the bigram table landmark (2.5).
    • \eta = 0.5 (orange): Spikes upward by >1 nat in the first 30 steps, then recovers and reaches about 2.1 nats.
    • \eta = 2.5 (green): Drops on step 1, explodes above 6 nats on step 2, and diverges to inf within 10 steps.

lr 0.1: final loss 2.492
lr 0.5: final loss 2.151
lr 2.5: final loss inf

Diagnosing Learning-Rate Failure Modes from Loss Curves

Reading Training Logs

  • \eta = 0.1 (Under-budgeted travel): Smooth descent still dropping at step 2{,}000; cumulative travel B_T = \eta T = 200 is too small \to raise \eta.
  • \eta = 0.5 (Near initial sharpness edge 2/L): Early >1-nat spike in steps 1\text{--}30, then fast descent to about 2.1 nats \to add warmup (§9.7) or clipping (§9.10).
  • \eta = 2.5 (Exceeds 2/\lambda_{\max}): Step 1 overshoots into a steeper basin and diverges to inf \to lower \eta.

Baseline Minibatch SGD on FashionCNN

Classification Baseline

  • Running the exact same 2{,}000-step train_steps loop on FashionCNN (b = 256 images) with plain SGD at \eta = 0.3 establishes our image classification baseline:
    • Final training loss: \approx 0.22\text{--}0.23 nats (down from uniform \ln 10 \approx 2.30).
    • Held-out test accuracy: \approx 89.5\%\text{--}90.5\%.
  • Together, TinyLM (about 2.1 nats under plain SGD) and FashionCNN (0.22 loss / 90\% test accuracy) serve as the reference baselines for §9.4–§9.10.
lr 0.3: final loss 0.221, test accuracy 0.901

Fair Comparisons: The Nuisance Parameter Protocol

Experimental Design

  • Why fixed-\eta comparisons fail: Plain SGD multiplies raw gradients (\eta^\star \approx 0.5), whereas AdamW normalizes step lengths (\eta^\star \approx 3 \times 10^{-3}).
  • Nuisance hyperparameter tuning (Godbole et al., 2023): Sweep \eta independently on a log-spaced grid for every optimizer arm from shared seed-0 weights.
  • Report both peak and width: Extract the tuned score at \eta^\star and the usable LR range finishing within +0.15 nats of \eta^\star.

Reporting Both Peak Performance and Usable LR Range

Robustness vs. Peak Score

When evaluating a learning-rate sweep lr_sweep on a log-spaced grid (e.g., factors of \sim 3\times), we extract two distinct metrics for each optimizer:

  • 1. Tuned score at the grid optimum \eta^\star: The lowest final_loss (or validation loss) achieved across the grid points tested, starting from identical initial weights.
  • 2. Usable learning-rate range: The span of grid learning rates that finish within +0.15 nats of the optimum (>10\times the multi-seed spread).
    • Example on TinyLM: Under plain SGD across \{0.1, 0.5, 2.5\}, only a single grid point (\eta = 0.5 at about 2.1 nats) is usable (\eta = 0.1 is about 0.35 nats worse; \eta = 2.5 diverges to inf).
    • As we will see in §9.5–§9.6, adaptive and orthogonalized optimizers widen this usable window across an order of magnitude (10^{-3} to 10^{-2} or 3 \times 10^{-2}).

Multi-Seed Spread and the 3× Significance Threshold

Statistical Rigor

  • Run-to-run seed variation: Different initial weights and minibatch draws shift 5-seed ranges by 0.010\text{--}0.015 nats on TinyLM and 0.8\%\text{--}1.0\% accuracy on FashionCNN.
  • Single-run 3\times decision threshold:
    • TinyLM: Require \ge 0.05 nats/byte improvement.
    • FashionCNN: Require \ge 0.06 loss or \ge 3.0\% accuracy improvement.
  • Smaller single-run gaps are treated as statistical ties unless averaged across multiple seeds.

Concept Check: Landmarks, Curve Diagnosis, and Seeds

Check Your Understanding

Apply the experimental protocol of this section to three concrete questions:

  1. Zero-initialized head: In Exercise 1, an untrained TinyLM with default random head weights (s^2 \approx 1/3) starts at \ln 256 + s^2/2 \approx 5.71 nats. What is its step-1 loss if the output head weights and biases are initialized to exact zeros?
  2. Result or statistical tie? In a single 2{,}000-step run from shared initial weights, Optimizer A finishes at 1.57 nats on TinyLM and 90.4\% accuracy on FashionCNN, while Optimizer B finishes at 1.59 nats and 89.6\% accuracy. Which optimizer wins?
  3. Training vs. validation loss on TinyLM: Why is TinyLM’s post-step-2{,}000 validation loss typically 0.02\text{--}0.03 nats lower than final_loss?

Concept Check: Landmarks, Curve Diagnosis, and Seeds (answers)

Check Your Understanding

Answers:

  1. Zero head weights and biases produce zero logits (\mathbf{z} = \mathbf{0}), giving an exact uniform distribution p_i = 1/256 and initial loss \ln 256 \approx 5.545 nats (0.17 nats lower from step 1).
  2. Both are ties. On TinyLM, |1.57 - 1.59| = 0.02 < 0.05 nats; on FashionCNN, |90.4\% - 89.6\%| = 0.8\% < 3.0\%. Resolving a 0.02-nat gap requires averaging across multiple seeds.
  3. Because TinyLM sees fresh text on every step (no overfitting) and is still improving between steps 1{,}900 and 2{,}000, final_loss averages steps 1{,}901\text{--}2{,}000 whereas validation evaluates the final step-2{,}000 weights.

Summary: Test Models, Landmarks, and Tuning Protocol

Key Takeaways

Component Specification Key Numbers to Remember Pedagogical Role
TinyLM on WikiText-103 2-block Transformer, d=128, 2 heads, 64 \times 64 byte batches 470{,}784 params (90\% matrices, 9\% emb, 1\% vectors); 3\% corpus in 2{,}000 steps Single-pass pretraining benchmark without memorization
FashionCNN on Fashion-MNIST 2 Conv-ReLU-Pool stages + 2 FC layers, b = 256 images 421{,}642 params (95\% in fc1); 8.5 epochs in 2{,}000 steps Multi-epoch classification benchmark with held-out accuracy
Untrained Loss Landmarks Closed-form / count-based byte predictors Untrained 5.71 \to Uniform 5.55 \to Unigram 3.2 \to Bigram 2.5 nats Anchors what a given nats/byte value means semantically
Plain SGD Baselines 2{,}000 steps, constant \eta, tuned on grid TinyLM at \eta=0.5: \approx 2.1 nats; FashionCNN at \eta=0.3: 0.22 loss / 90\% acc Reference bar that Momentum, AdamW, and Muon must beat
Comparison & Significance Independent LR sweep per arm from shared seed Single-run threshold: 0.05 nats (TinyLM), 0.06 loss / 3\% acc (FashionCNN) Separates algorithmic gains from nuisance tuning & seed noise