Sam Babichenko

Reading notes / Deep Learning Alchemy

Hyperparameters, scaling, noise and debugging

From Lecture 2 of Stanford CS 312 Deep Learning Alchemy (Fall 2026), taught by Tatsunori Hashimoto and Suhas Kotha

slides quiz answers assignment code

Scale and hyperparameters
NNnumber of non-embedding parameters
DDnumber of training tokens
BBbatch size, in rows of 1,024 tokens (d8 default 64)
η\etapeak learning rate (d8 default 0.003)
λ\lambdaweight-decay coefficient: weight decay shrinks the weights by a factor 1−ηλ1-\eta\lambda per step (d8 default 0.1)
ηopt\eta_{\rm opt}Step Law's optimal learning rate, ηopt=1.79 N−0.713D0.307\eta_{\rm opt}=1.79\,N^{-0.713}D^{0.307}
BoptB_{\rm opt}Step Law's optimal batch size in tokens, Bopt=0.58 D0.571B_{\rm opt}=0.58\,D^{0.571}
Scaling laws
LLfinal validation loss, nats per token
αN\alpha_NKaplan's model-size exponent in L(N)=(Nc/N)αNL(N)=(N_c/N)^{\alpha_N} (0.076)
αD\alpha_DKaplan's data exponent in L(D)=(Dc/D)αDL(D)=(D_c/D)^{\alpha_D} (0.095; 0.103 in the joint fit)
NcN_cfitted scale constant for model size in Kaplan's law L(N)=(Nc/N)αNL(N)=(N_c/N)^{\alpha_N}
DcD_cfitted scale constant for data in Kaplan's law L(D)=(Dc/D)αDL(D)=(D_c/D)^{\alpha_D}
aacoefficient of the power-law term in the course's ladder fit L=aN−b+cL=aN^{-b}+c
bbexponent of model size in the course's ladder fit L=aN−b+cL=aN^{-b}+c
ccconstant term in the course's ladder fit L=aN−b+cL=aN^{-b}+c, the loss the fit approaches as NN grows
Noise and norms
σ\sigmaseed-to-seed standard deviation of d8's final validation loss (0.0029 over ten runs)
ffthe loss as a function of a scale-invariant set of weights ww, so f(cw)=f(w)f(cw)=f(w) for c>0c>0
wwa scale-invariant set of weights, such as a query or key matrix under QK-norm, on which the loss satisfies f(cw)=f(w)f(cw)=f(w)
gggradient of the loss ff with respect to the scale-invariant weights ww; it is orthogonal to ww
ccpositive rescaling factor in f(cw)=f(w)f(cw)=f(w)

Context. Lecture 2 of Hashimoto and Kotha's Stanford course CS 312 (Deep Learning Alchemy) treats deep learning as an experimental science closer to biology than to the rest of computer science. Progress depends on how cleanly researchers run the loop of changing one thing, measuring it, and interpreting the outcome. The lecture covers four practical skills for that loop: tuning hyperparameters, using scaling laws as cheap stand-ins for large runs, quantifying run-to-run noise, and diagnosing failures from internal statistics. Its readings are Step Law (Li et al., 2025) on optimal learning rate and batch size, Kaplan et al. (2020) on scaling laws, and Summers and Dinneen (2021) on nondeterminism. Quiz 1 turns all four skills into quantitative prediction problems on the course's default model: an 8-block, width-512 transformer with about 35M parameters, pre-trained on 614.4M tokens of web text. Reading note: Prediction as understanding: the d8 model organism and supplies most of the d8 measurements below.

A comparison between two training runs is trustworthy only when both runs are properly tuned and their loss gap exceeds run-to-run noise. Untuned baselines have repeatedly reversed published conclusions, and the optimal learning rate shifts with model size, data size, batch size, and warmup. On d8, final validation loss fluctuates by about 0.003 across random seeds, so single runs cannot settle smaller gaps. L=aN−b+cL=aN^{-b}+c: a series of models of increasing size trained under one recipe, fitted and extrapolated to predict larger runs cut experiment cost, and internal statistics pinpoint failures. Yet a ladder can bend just past its fitted range, and an internal metric is informative only against a healthy baseline.

Setting. The default d8 run makes one pass over 614.4M tokens in 9,375 steps of 64 rows of 1,024 tokens. It uses θ←θ−η m/(v+ϵ)−ηλθ\theta\leftarrow\theta-\eta\,m/(\sqrt v+\epsilon)-\eta\lambda\theta with running averages m←β1m+(1−β1)gm\leftarrow\beta_1m+(1-\beta_1)g and v←β2v+(1−β2)g2v\leftarrow\beta_2v+(1-\beta_2)g^2 (bias corrections omitted): decoupled decay shrinks θ\theta directly rather than passing through v\sqrt v (Loshchilov and Hutter, 2019) at peak rate η=0.003\eta=0.003, with 1% linear warmup, linear decay to zero, weight decay λ=0.1\lambda=0.1, and gradient clipping at norm 1. Validation loss finishes near 2.93 nats per token. d8's blocks are h←h+F(norm(h))h\leftarrow h+F(\mathrm{norm}(h)): each branch reads a normalized copy of the residual stream while the skip path stays unnormalized. Reading note: Signal propagation in depth and apply RMS normalization of each attention head's query and key vectors before their dot product. Reading note: Small-scale proxies for large-scale Transformer training instabilities. Write BB for batch size in rows, NN for non-embedding parameter count, and DD for training token count.

An untuned hyperparameter can reverse a conclusion. Three case studies show how severely default settings can mislead. First, in P[M(D)∈S]≤eεP[M(D′)∈S]+δP[M(D)\in S]\le e^{\varepsilon}P[M(D')\in S]+\delta for every outcome set SS and datasets D,D′D,D' differing in one example, bounding what the model reveals about any individual (Dwork and Roth, 2014) fine-tuning with gradient descent with per-example gradient clipping and Gaussian noise added to the sum, researchers believed large language models could not be fine-tuned privately. Li et al. (2022) overturned that view by showing the standard hyperparameters were nearly 100 times off. Second, Kim et al. (2025) studied data-limited multi-epoch pre-training on 200M tokens with tuned learning rate and epoch count. From 150M to 1.4B parameters, loss stops improving with model size, going 3.84, 3.79, 3.75, and 3.77 (read off plots, like the next four values). There, repeating data more than about 8 times hurts. Adding weight-decay tuning (best values 0.8 to 3.2 instead of 0.1) drops those losses to 3.75, 3.59, 3.51, and 3.46. The tuned curve follows 0.05/N1.02+3.430.05/N^{1.02}+3.43 with NN in billions and reverses the scaling verdict. Third, Wen et al. (2025) raised AdamW's learning rate from 6⋅10−46\cdot10^{-4} to 8⋅10−38\cdot10^{-3} on 130M models. That change halves the steps needed and matches Mars, an optimizer claimed to beat AdamW. They also found that θ←θ−η sign⁡(β1m+(1−β1)g)−ηλθ\theta\leftarrow\theta-\eta\,\operatorname{sign}(\beta_1m+(1-\beta_1)g)-\eta\lambda\theta with m←β2m+(1−β2)gm\leftarrow\beta_2m+(1-\beta_2)g: every coordinate steps by the same magnitude regardless of gradient size (Chen et al., 2023). Reading note: Convergence theory for Muon needs weight decay near 0.6, several times AdamW's. Even d8's basic recipe has 21 hyperparameters. The working rule is to sweep each knob on a logarithmic grid wide enough to bracket its optimum. Interacting knobs, such as learning rate with batch size or warmup, must be tuned jointly.

Optimal learning rate and batch size move with scale. Li et al. (2025) trained about 3,700 dense and models whose MLP splits into many experts with a learned router sending each token to a few of them, growing parameters at fixed compute per token (Shazeer et al., 2017) language models to map how the best learning rate and batch size shift with NN and DD. At fixed NN and DD, final loss forms a smooth bowl in log learning rate and log batch size. Under AdamW, its broad flat bottom drifts slightly with batch size. Fitting models from 60M to 1B parameters on 2B to 100B tokens, holding out the 1B-parameter, 100B-token point, gives Step Law:ηopt=1.79 N−0.713D0.307,Bopt=0.58 D0.571.\begin{aligned}\eta_{\rm opt}&=1.79\,N^{-0.713}D^{0.307},\\B_{\rm opt}&=0.58\,D^{0.571}.\end{aligned}Here BoptB_{\rm opt} is measured in tokens. The optimal batch depends on data size alone. The optimal rate falls with model size and, at the optimal batch, rises with data. On the held-out 1B/100B run, Step Law landed within 0.094% of the grid's best loss. Across six differently shaped 430M models, the optimum stayed inside one narrow band. The fits use cosine decay to a why: using the common final rate of 0.1 times the peak leaves high-peak runs ending at high rates, skewing the optimum downward and spoiling the fits. Plugging d8 (N=30.4N=30.4M, D=614.4D=614.4M) into Step Law gives ηopt≈0.0041\eta_{\rm opt}\approx0.0041 and Bopt≈60,000B_{\rm opt}\approx60{,}000 tokens, or about 59 rows (computed here). Those sit close to d8's 0.003 and 64 rows, even though Step Law uses a 65,536-token vocabulary, 2,048-token rows, attention with linear biases: a distance-proportional penalty added to attention scores in place of position embeddings positions, and a fixed 2,000-step warmup.

Warmup interacts with peak learning rate. On d8, ηt=η t/tw\eta_t=\eta\,t/t_{\rm w} for t≤twt\le t_{\rm w}: linear ramp from 0 to peak η\eta over the opening fraction of steps (1% in d8), keeping early updates small while weights and Adam's moments initialize protects early training and unlocks higher peak rates. Dropping the 1% warmup costs 0.097, 0.111, and 0.094 in final validation loss across three matched seeds. The run does not diverge, but its 1n∑ixi2\sqrt{\tfrac1n\sum_ix_i^2} pooled over logged layer outputs, tracking typical activation magnitude spikes early to more than ten times the warmed-up level. Higher peak rates require longer warmup. Rate 0.009 with 5% warmup reaches 2.9165, beating the 2.93 default. Rate 0.027 finishes at 2.9745 with 5% warmup and improves to 2.9563 with 20% warmup. Across a joint rate-warmup grid, longer warmup raises the best rate and flattens the basin around it. The best warmup for d8 sits at 20 to 30% of training, well above the 1% default. The staff suggest the short horizon may explain why.

Decay length and cheap small-model sweeps. The ηt=η (T−t)/(T−tw)\eta_t=\eta\,(T-t)/(T-t_{\rm w}) for tw≤t≤Tt_{\rm w}\le t\le T: linear cooldown from peak to 0 where small late steps average out gradient noise and drive much of the final loss drop also requires a substantial fraction of the run. On d8, a warmup, constant peak rate, then linear decay to zero over a final fraction of steps. Reading note: Learning-rate schedules and batch size that decays over only the final 2, 5, 10, or 20% of steps ends 0.085, 0.051, 0.030, or 0.009 above full linear decay. Matching linear decay within 0.02 therefore takes about 20% of the run. Loss falls fastest during cooldown, a profile captured by convex guarantees on the final weights themselves rather than an iterate average. Reading note: Learning-rate schedules and batch size (Schaipp et al., 2025). Running these hyperparameter grids on small models is cheap in FLOPs, yet launching many tiny GPU separate GPU programs, one per operation; on small models launch overhead dominates compute wastes hardware. vectorizing map: evaluating one function over a batch of model parameter sets as a single batched GPU operation-style batching of many models together recovers GPU utilization.

Scaling laws predict large runs from small ones. Kaplan et al. (2020) measured how transformer validation loss falls with model size NN, data DD, and compute. When only one resource bottlenecks training, loss follows a power law across six orders of magnitude in NN, eight in compute, and two in DD, with weak dependence on aspect ratio. For model size alone, with fitted scale constant Nc≈8.8×1013N_c\approx8.8\times10^{13},L(N)=(NcN)αN,αN≈0.076.L(N)=\Big(\frac{N_c}{N}\Big)^{\alpha_N},\qquad \alpha_N\approx0.076.On log-log axes, −αN-\alpha_N is the slope, so doubling NN multiplies the loss by 2−αN≈0.952^{-\alpha_N}\approx0.95. For a large model stopped before overfitting, data obeys the same form, L(D)=(Dc/D)αDL(D)=(D_c/D)^{\alpha_D}, with αD≈0.095\alpha_D\approx0.095 and Dc≈5.4×1013D_c\approx5.4\times10^{13} tokens. One formula captures both bottlenecks at once, with NcN_c, DcD_c, and αD\alpha_D refit jointly (αD≈0.103\alpha_D\approx0.103):L(N,D)=[(NcN)αN/αD+DcD]αD.L(N,D)=\Big[\Big(\frac{N_c}{N}\Big)^{\alpha_N/\alpha_D}+\frac{D_c}{D}\Big]^{\alpha_D}.The penalty for insufficient data therefore scales through NαN/αD/D=N0.74/DN^{\alpha_N/\alpha_D}/D=N^{0.74}/D. An 8-times-larger model needs roughly 5 times more data.

Why scaling ladders fail past the fitted range. Extrapolating a ladder of small runs carries three hazards. First, optimal hyperparameters shift along the ladder, so holding them fixed confounds recipe mismatch with model scaling. Second, accounting conventions change the answer; including or excluding embedding parameters in NN altered the compute-optimal allocation between model size and data. Third, a smooth power law can break abruptly just beyond the measured points. In the an open-source language-modeling project publishing code, data, and full training logs project's scaling study, a near-perfect loss-versus-compute fit missed its extrapolated targets by 0.8% and 2.5%, and the largest run diverged.

Testing ladder extrapolation on d4 to d16. Ladders from d4 to d9 compare four recipes: the baseline, a constant learning rate with no decay, dropout 0.2, and peak rate 0.03 (ten times the default). Write NN in millions of total parameters, embeddings included. Fitting L=aN−b+cL=aN^{-b}+c across those six sizes yields 1.46N−0.38+2.551.46N^{-0.38}+2.55 for the baseline, 1.02N−0.35+2.871.02N^{-0.35}+2.87 for constant rate, 2.08N−0.16+1.892.08N^{-0.16}+1.89 for dropout, and 1.23N−0.51+2.821.23N^{-0.51}+2.82 for rate 0.03. At d16 (251.7M total parameters on the same 614.4M tokens), the measured gaps above baseline are +0.244, +0.058, and +0.122. Extrapolating the d4 to d9 fits predicts +0.29, +0.02, and +0.16 (computed here), getting the ranking right but missing the magnitudes. Because of its lower asymptote, the dropout fit mistakenly predicts dropout will beat the baseline before 1B parameters. Recipe changes can also bend the ladder directly. Baseline d9 beats d4 by 0.41. Repeating 75,000 rows for 8 epochs (still 614.4M tokens) cuts that gain to 0.226. Dropping QK-norm at rate 0.006 reverses it completely, leaving d9 0.608 above d4. Because a curve through in-range points almost always looks clean, only extrapolation tests a ladder.

Any single source of randomness matches all of them. Training variance comes from weight initialization, data selection and ordering, nondeterministic GPU arithmetic, and training instability that amplifies tiny perturbations. Summers and Dinneen (2021) trained 100 ResNet-14 models on CIFAR-10 per source and found that each source alone produces virtually the same spread as all of them combined. Accuracy standard deviations run from 0.21 to 0.26%, and cross-entropy standard deviations from 0.0072 to 0.0083. Flipping a single bit in the last place of one initial weight reproduces the entire spread (0.21% and 0.0068). Nonlinear depth drives this amplification. A linear model shows cross-entropy spread near 10−710^{-7}, while adding one hidden layer multiplies it by about 10,000. Sensitivity does not vanish after initialization. Turning on nondeterminism after 50 of 500 epochs leaves the final spread nearly unchanged. Jordan (2024) reports the same full-spread equivalence for 64-epoch CIFAR-10 training, whereas at one epoch each individual source yields 25 to 40% less variance.

Seed spread and single-token sensitivity on d8. Ten d8 runs across paired seeds have a final validation-loss standard deviation of σ=0.0029\sigma=0.0029. Varying only the initialization seed or only the data seed gives roughly the same spread. Two runs with determinism enabled match bit for bit. Across five paired seeds under determinism, altering a single token in one training row (one of 614.4M tokens) opens an early per-step training-loss gap. At rate 0.009, the average peak gap reaches 0.095 before fading. At the default rate, final validation losses still differ by 0.57σ0.57\sigma on average, about half the spread of full reseeding. At rate 0.009, the final gap is several times larger. Any observed loss difference below about 0.003 therefore requires repeated seeds.

Per-step jitter and paired comparisons. Per-step training loss is far noisier than final validation loss because each step averages over a fresh minibatch of text. On d8, standard deviation of per-step training loss minus its centered 51-step running mean over the last 2,000 steps measures 0.0769, 0.0404, and 0.0198 at batch sizes 16, 64, and 256, tracking 0.0464/B0.04\sqrt{64/B}. Across peak rates from 0.0003 to 0.03, it barely changes. Validation loss on a fixed held-out set eliminates this minibatch noise. Comparisons gain power from pairing. Because examples vary widely in text difficulty, evaluating two methods on the same examples can reveal a real difference even when their separate error bars overlap. Even without minibatch noise, full-batch gradient descent still produces loss spikes.

Diagnosing failures from internal statistics. When a training run diverges, stalls, or underperforms, the loss curve shows when it happened and internal statistics show where. Activations locate the failing component, gradients reveal training dynamics, and parameters with optimizer state track slow cumulative drift. Reading these signals has produced several standard remedies. Per-layer activation histograms led to weights with variance 2/(din+dout)2/(d_{in}+d_{out}) so activation and gradient variances hold steady across layers (Glorot and Bengio, 2010), and per-layer gradient norms built the case for placing layer normalization before each branch (Xiong et al., 2020). In a 22B-parameter vision transformer, exploding attention logits motivated adopting QK-norm (Dehghani et al., 2023). In a large Marin run, the parameter norm of the attention gates grew far beyond its values on smaller ladder runs. The early layers' gates stayed nearly shut, so those layers added little to the residual stream. Adding light weight decay restored normal norms.

Scale invariance and parameter-norm equilibrium. Knowing what is normal includes knowing the invariances of the architecture. Some parameter groups are scale-invariant, satisfying f(cw)=f(w)f(cw)=f(w) for any c>0c\gt0. Under QK-norm, each query or key matrix satisfies this property individually. Jointly, all weights writing to the residual stream are scale-invariant as a group because every pre-norm reader normalizes the stream. Differentiating f(cw)=f(w)f(cw)=f(w) at c=1c=1 implies the gradient gg is orthogonal to ww. By Pythagoras' theorem, every plain gradient step lengthens the weights:∥w−ηg∥2=∥w∥2+η2∥g∥2.\|w-\eta g\|^2=\|w\|^2+\eta^2\|g\|^2.Decoupled weight decay acts the other way, multiplying the weights by 1−ηλ1-\eta\lambda per step and shrinking the squared norm by roughly 2ηλ∥w∥22\eta\lambda\|w\|^2. Growth scales as η2\eta^2 while decay scales linearly in η\eta, so the weight norm settles where the two balance. As η\eta decays, that equilibrium drops (van Laarhoven, 2017).

Testing norm equilibrium on d8 and debugging rules. Four d8 runs cross schedule (linear decay vs. constant rate) with weight decay (0.1 vs. 0). Only the run with linear decay and weight decay 0.1 finishes below its peak total parameter norm. It drops 3 to 15% from a peak near step 4,000 as the falling rate lowers the equilibrium. With a constant rate and weight decay 0.1, the norm is still climbing toward equilibrium at the end of training. In both runs without weight decay, the norm never falls. None of the four runs sees its gradient norm double over training, contrasting with the late rise reported by Defazio (2025). Three practical debugging habits follow. Learn what healthy statistics look like and which deviations matter, and change one variable at a time. Compare a failing run against known-good and known-bad references, such as smaller runs on the same ladder.

Limits. The d8 measurements come from one small model, one corpus, and one token budget, mostly from single runs or small seed counts. The course itself cautions that d8 lessons are likely imperfect and invites counterexamples. Step Law is an empirical fit from one data mix up to 1B parameters, leaving a first-principles derivation open. Kaplan et al.'s exponents and resulting compute split were later revised. Summers and Dinneen's main measurements cover small CIFAR-10 and Penn Treebank models. The norm-equilibrium calculation above is exact for plain gradient steps. For AdamW, whose update rescales the gradient coordinatewise, it serves as a heuristic.

Terms

tuned baselines
an untuned learning rate or weight decay has reversed conclusions (DP fine-tuning, data repetition, optimizer comparisons)
Step Law
ηopt=1.79N−0.713D0.307\eta_{\rm opt}=1.79N^{-0.713}D^{0.307}, Bopt=0.58D0.571B_{\rm opt}=0.58D^{0.571} tokens; batch depends on data only
d8 warmup
removing the 1% warmup costs about 0.1; the best warmup is 20 to 30%, and longer warmup raises the best rate
d8 decay
warmup-stable-decay needs about 20% of steps decaying to come within 0.02 of linear decay
Kaplan laws
L(N)∝N−0.076L(N)\propto N^{-0.076}, L(D)∝D−0.095L(D)\propto D^{-0.095}; joint form; data need grows as N0.74N^{0.74}
ladder extrapolation
d4 to d9 fits got d16's order right but not its gaps; QK-norm removal and epoching bend the ladder
σ\sigma for d8
about 0.003, the same from initialization alone or data order alone
instability
one bit changed in one initial weight reproduces the full run-to-run spread (Summers and Dinneen)
late-training jitter
about 0.0464/B0.04\sqrt{64/B}, set by batch size, nearly independent of the learning rate
norm equilibrium
scale-invariant weights grow by η2∥g∥2\eta^2\|g\|^2 per step and decay by about 2ηλ∥w∥22\eta\lambda\|w\|^2; the balance falls with the rate

Sources

Lecture 2, “Basics: hyperparameters, scaling laws, stochasticity, debugging” (Sep 24, 2026), of Stanford CS 312 Deep Learning Alchemy, Fall 2026. Taught by Tatsunori Hashimoto and Suhas Kotha; course staff Kaiyue Wen and Tristan Thrush (CAs).

Course site Lecture slides Online quiz Quiz answers Assignment Assignment code

The lessons, experiments, figures and quiz problems in this note are the course's, shown here with the instructors' permission.

Connected notes

  • Dividing the numerator of softmax attention by its L2 norm, which fixes the output's length, follows the softmax loss curve, while dividing by the sequence length behind a gate, with scores clamped at 5 and gradients clipped, still gives loss spikes.

  • In one-layer linear self-attention, the loss depends only on the product V=u−1U11V=u_{-1}U_{11} and leaves the scale split between the label-value scalar and the key-query matrix free; gradient flow conserves u−12=∥U11∥F2u_{-1}^2=\|U_{11}\|_F^2, which pins the limit on the hyperbola of equivalent global minima.

  • Under μ\muP the optimal learning rate, initialization scale and multipliers are nearly stable in width, so they can be tuned on a small proxy and copied, and a 40M proxy beat the published 6.7B GPT-3 at a tuning cost of 7% of its pretraining cost.

  • With effects θi\theta_i spread around a common mean, the posterior mean pulls each raw estimate toward that mean, and Lindley's version of James-Stein estimates both the mean and the amount of pulling from the spread of the estimates themselves. It beats the raw estimates in total squared error for every configuration of the θi\theta_i once there are four or more, and in Efron's batting example it cuts the total prediction error to 0.28 of that of the raw batting averages.

Threads