Electric Sheaves

Lecture 6 — Training Dynamics

Project connection. Project Step 6 trains the 816,640-parameter model of Lecture 5 for 5,000 steps with batch size 64. The empirical table in Section 6 is the reference run for (V,Tmax,d,H,L)=(65,64,128,4,4)(V,T_{\max},d,H,L)=(65,64,128,4,4).

Chapter overview. Initialization, adaptive preconditioning, learning- rate schedules, and gradient clipping can be formulated precisely and tested directly. The broader question—why an overparametrized non-convex model both optimizes and generalizes—has only partial answers. This chapter separates exact calculations and algorithm definitions from empirical observations and theoretical regimes.

0. Setup

Let θRn\theta\in\mathbb R^n be the parameter vector and L(θ)\mathcal L(\theta) the empirical loss. A training method specifies an initial random vector θ0\theta_0, a gradient estimator gtg_t, and an update rule for producing θt\theta_t from θt1\theta_{t-1}.

For a random scalar XX with finite second moment,

Var(X)=E[(XEX)2].\operatorname{Var}(X)=\mathbb E[(X-\mathbb EX)^2].

If XX and YY are independent, then E[XY]=E[X]E[Y]\mathbb E[XY]=\mathbb E[X]\mathbb E[Y]; if they are also centered, the variance of their product is Var(XY)=E[X2]E[Y2]\operatorname{Var}(XY)=\mathbb E[X^2]\mathbb E[Y^2].

1. Initialization as variance bookkeeping

Consider one linear layer

y=Wx,WRm×n,xRn.y=Wx, \qquad W\in\mathbb R^{m\times n}, \quad x\in\mathbb R^n.

Assume the entries WijW_{ij} are independent with mean zero and variance σW2\sigma_W^2, the coordinates xjx_j are independent with mean zero and variance σx2\sigma_x^2, and WW is independent of xx.

Lemma 1.1 (variance through a linear layer). For every output coordinate,

Var(yi)=nσW2σx2.\operatorname{Var}(y_i)=n\sigma_W^2\sigma_x^2.

Proof. Since yi=j=1nWijxjy_i=\sum_{j=1}^nW_{ij}x_j, its summands are centered and pairwise uncorrelated. Each has variance E[Wij2]E[xj2]=σW2σx2\mathbb E[W_{ij}^2]\mathbb E[x_j^2]=\sigma_W^2\sigma_x^2. Variances therefore add. \square

To preserve forward variance, choose σW2=1/n\sigma_W^2=1/n, called fan-in scaling. In the backward relation xˉ=Wyˉ\bar x=W^\top\bar y, the analogous calculation gives σW2=1/m\sigma_W^2=1/m, called fan-out scaling. Xavier, or Glorot, initialization compromises with

σW2=2n+m.\sigma_W^2=\frac{2}{n+m}.

For a symmetric centered input, ReLU sets half of the values to zero and halves the second moment. He initialization compensates by taking σW2=2/n\sigma_W^2=2/n.

Remark 1.2 (depth). If each layer multiplies activation variance by a factor cc, a depth-LL composition multiplies it by cLc^L. A small per-layer scale error therefore becomes exponential in depth. Nonlinear activation means and dependencies make this calculation approximate, but it remains a useful initialization diagnostic.

In a residual network, suppose the stream is updated by 2L2L approximately centered, uncorrelated contributions, each having variance vv. Then

Var(X(L))Var(X(0))+2Lv.\operatorname{Var}(X^{(L)}) \approx\operatorname{Var}(X^{(0)})+2Lv.

Scaling each branch’s output projection by 1/2L1/\sqrt{2L} replaces vv by v/(2L)v/(2L) and keeps the total added variance of order one. The GPT-2-style initialization applies this scaling to each attention WOW_O and MLP W2W_2.

Project observation 1.3. The reference model begins at validation loss 4.3039, close to the uniform value ln65=4.1744\ln65=4.1744. A much larger initial loss indicates logits with excessive spread. The small positive gap comes from the particular unembedding initialization used by PyTorch.

2. Adam and AdamW

For vectors, u2u^{\odot2} denotes coordinatewise squaring, and square roots and divisions in this section are also coordinatewise. Let gtg_t be a minibatch gradient evaluated at θt1\theta_{t-1}, choose 0β1,β2<10\leq\beta_1,\beta_2<1, and initialize m0=v0=0m_0=v_0=0.

Definition 2.1 (adaptive moment estimation; Adam). Adam forms exponential moving averages

mt=β1mt1+(1β1)gt,m^t=mt1β1t,vt=β2vt1+(1β2)gt2,v^t=vt1β2t,\begin{aligned} m_t&=\beta_1m_{t-1}+(1-\beta_1)g_t, &\widehat m_t&=\frac{m_t}{1-\beta_1^t},\\ v_t&=\beta_2v_{t-1}+(1-\beta_2)g_t^{\odot2}, &\widehat v_t&=\frac{v_t}{1-\beta_2^t}, \end{aligned}

and updates

θt=θt1ηtm^tv^t+ε,\theta_t =\theta_{t-1}-\eta_t \frac{\widehat m_t}{\sqrt{\widehat v_t}+\varepsilon},

where ε>0\varepsilon>0 prevents division by zero.

The vector mtm_t estimates a first moment and supplies momentum; vtv_t estimates a coordinatewise second moment and supplies an adaptive diagonal preconditioner. Here a diagonal preconditioner means a coordinatewise rescaling of the update direction.

Proposition 2.2 (loss-scale invariance). Set ε=0\varepsilon=0 and assume v^t,i>0\widehat v_{t,i}>0 for every coordinate under consideration. If the loss and hence every gradient are multiplied by a constant c>0c>0, the Adam update direction is unchanged.

Proof. The first-moment estimate is multiplied by cc, and the second-moment estimate by c2c^2. Thus m^t/v^t\widehat m_t/\sqrt{\widehat v_t} is unchanged. \square

Remark 2.3 (coordinatewise preconditioning). A coordinate with a persistently small gradient also tends to have a small second-moment denominator. Adam therefore reduces sensitivity to coordinatewise gradient scale, though it does not make Adam a true inverse-Hessian method.

If a random gradient has time-independent mean μ\mu, then

E[mt]=(1β1t)μ.\mathbb E[m_t]=(1-\beta_1^t)\mu.

Similarly, if E[gt2]\mathbb E[g_t^{\odot2}] is time-independent, the same factor 1β2t1-\beta_2^t appears for vtv_t. The denominators in Definition 2.1 are therefore exact bias corrections under these stationary-moment assumptions.

Definition 2.4 (AdamW). Given a weight-decay coefficient λ0\lambda\geq0, AdamW uses

θt=(1ηtλ)θt1ηtm^tv^t+ε.\theta_t =(1-\eta_t\lambda)\theta_{t-1} -\eta_t\frac{\widehat m_t}{\sqrt{\widehat v_t}+\varepsilon}.

This is decoupled weight decay: shrinkage is applied directly to the weights rather than being included in the gradient before adaptive preconditioning.

Remark 2.5 (L2L^2 regularization versus AdamW). For plain SGD, adding (λ/2)θ22(\lambda/2)\|\theta\|_2^2 to the loss produces the same first-order update as multiplicative decay. Under Adam, the added gradient λθ\lambda\theta is divided by a coordinate-dependent denominator, so it no longer gives uniform shrinkage. AdamW preserves the latter interpretation.

Hyperparameter aside 2.5. The project uses β2=0.99\beta_2=0.99 instead of 0.999. An exponential moving average has an effective horizon on the order of 1/(1β2)1/(1-\beta_2), so the smaller value adapts its second-moment estimate more quickly at the cost of greater sampling noise. This choice is an empirical convention rather than a theorem.

3. Warmup and cosine decay

Fix endpoints 0<tw<tf0<t_w<t_f and learning rates 0ηminηmax0\leq\eta_{\min}\leq\eta_{\max}. Define the linear-warmup, cosine-decay schedule for 0ttf0\leq t\leq t_f by

η(t)={ηmaxt/tw,0t<tw,ηmin+ηmaxηmin2(1+cosπ(ttw)tftw),twttf.\eta(t)= \begin{cases} \eta_{\max}\,t/t_w,&0\leq t<t_w,\\[4pt] \eta_{\min} +\dfrac{\eta_{\max}-\eta_{\min}}2 \left(1+\cos\dfrac{\pi(t-t_w)}{t_f-t_w}\right), &t_w\leq t\leq t_f. \end{cases}

If training continues beyond tft_f, set η(t)=ηmin\eta(t)=\eta_{\min}. The schedule is continuous, reaches ηmax\eta_{\max} at twt_w, and reaches ηmin\eta_{\min} at tft_f.

Remark 3.1 (warmup). At the beginning of training, moment estimates are based on few samples and model activations may change rapidly. Warmup limits the size of early steps. Its practical value is well established, but no single general theorem explains the best warmup length.

Remark 3.2 (decay and stochastic noise). Near a minimizer, random gradient error may dominate the mean gradient. For a quadratic model with constant step size, the iterates fluctuate in a stationary neighborhood whose size decreases with the step size. Learning-rate decay reduces this noise floor. A finite cosine schedule resembles the noise-control role of Robbins—Monro decay but does not satisfy its infinite-horizon conditions.

The reference run uses ηmax=3×103\eta_{\max}=3\times10^{-3}, tw=100t_w=100, tf=5000t_f=5000, and ηmin=3×104\eta_{\min}=3\times10^{-4}.

4. Gradient clipping

Let g2=(igi2)1/2\|g\|_2=(\sum_i g_i^2)^{1/2} be the Euclidean norm.

Definition 4.1 (global norm clipping). For a threshold c>0c>0, replace a gradient gg by

clipc(g)={g,g2c,cg/g2,g2>c.\operatorname{clip}_c(g) =\begin{cases} g,&\|g\|_2\leq c,\\ c\,g/\|g\|_2,&\|g\|_2>c. \end{cases}

Thus clipping preserves direction and bounds the norm by cc.

Remark 4.2 (bias). Even if gg is an unbiased stochastic gradient, the nonlinear random vector clipc(g)\operatorname{clip}_c(g) is generally not unbiased. Clipping therefore violates a hypothesis of the basic Robbins—Monro theorem. It is used as protection against rare large updates rather than as an exact estimator.

Project observation 4.3. In the reference run, pre-clipping norms stay between 0.298 and 0.414 and never reach the threshold 1.0. Clipping is inactive in that run. Logging the norm is what makes this conclusion possible.

5. Partial theories of deep-network training

The Hessian of a twice differentiable loss is 2L(θ)\nabla^2\mathcal L(\theta), the matrix of second partial derivatives. A point with zero gradient is stationary. A stationary point with Hessian having both positive and negative eigenvalues is a saddle point. A model is overparametrized relative to a dataset when it has enough degrees of freedom to fit, and often exactly interpolate, the training observations.

5.1 Landscape observations

Remark 5.1 (high-dimensional saddles). In high dimension, requiring every Hessian eigenvalue to be positive is a strong condition. Many non-minimizing stationary points are saddles, and stochastic noise can help an optimizer leave directions of negative curvature. This geometric heuristic does not by itself prove convergence for a transformer.

Remark 5.2 (mode connectivity). Empirically, independently trained overparametrized networks can often be connected by low-loss curves in parameter space. Global minimizers may form large sets rather than isolated points. Parameter symmetries, such as hidden-unit permutations, guarantee some multiplicity; the observed connectivity is a stronger phenomenon.

5.2 Neural tangent kernel

For fixed training inputs x1,,xNx_1,\ldots,x_N and a scalar network output fθ(x)f_\theta(x), define the empirical neural tangent kernel (NTK) by

Kθ(i,j)=θfθ(xi),θfθ(xj).K_\theta(i,j) =\left\langle\nabla_\theta f_\theta(x_i), \nabla_\theta f_\theta(x_j)\right\rangle.

It is positive semidefinite because, for every uRNu\in\mathbb R^N, uKθu=iuiθfθ(xi)20u^\top K_\theta u=\|\sum_i u_i\nabla_\theta f_\theta(x_i)\|^2\geq0. A symmetric matrix KK is positive definite if uKu>0u^\top Ku>0 for every nonzero uu. Gradient flow is the continuous-time equation θ˙(t)=θL(θ(t))\dot\theta(t)=-\nabla_\theta\mathcal L(\theta(t)).

Theorem 5.3 (neural-tangent-kernel dynamics). Let yRNy\in\mathbb R^N be the target vector and use squared loss

L(θ)=12Ni=1N(fθ(xi)yi)2.\mathcal L(\theta)=\frac1{2N}\sum_{i=1}^N (f_\theta(x_i)-y_i)^2.

Suppose that along gradient flow the kernel is a fixed matrix Kθ(t)=KK_{\theta(t)}=K. If f(t)=(fθ(t)(xi))i=1Nf(t)=(f_{\theta(t)}(x_i))_{i=1}^N, then

f˙(t)=1NK(f(t)y).\dot f(t)=-\frac1N K(f(t)-y).

If KK is positive definite with smallest eigenvalue λmin>0\lambda_{\min}>0, then

L(θ(t))e2λmint/NL(θ(0)),\mathcal L(\theta(t)) \leq e^{-2\lambda_{\min}t/N}\mathcal L(\theta(0)),

so the training predictions converge to yy.

Proof. The chain rule and the gradient-flow equation give

f˙i=θfi,θ˙=1NjK(i,j)(fjyj).\dot f_i =\langle\nabla_\theta f_i,\dot\theta\rangle =-\frac1N\sum_jK(i,j)(f_j-y_j).

For e=fye=f-y,

ddte2=(2/N)eKe(2λmin/N)e2.\frac{d}{dt}\|e\|^2=-(2/N)e^\top Ke \leq-(2\lambda_{\min}/N)\|e\|^2.

Integrating this differential inequality proves the bound. \square

Remark 5.4 (infinite-width limit and limitation). For certain fixed-depth network families with inverse-square-root width scaling, random initialization, and regular activations, the initial empirical NTK converges as width tends to infinity to a deterministic kernel and changes negligibly on finite training intervals. Theorem 5.3 then describes the limiting output dynamics. Because the kernel is fixed, features remain close to initialization; this rigorous regime does not explain practical feature learning such as the changing embedding geometry in Step 3.

5.3 Double descent

The interpolation threshold is the capacity at which a model first achieves essentially zero training error.

Observation 5.2 (double descent). In many model families, test error first follows a classical decreasing-then-increasing curve as capacity grows, peaks near the interpolation threshold, and decreases again in the overparametrized regime.

Remark 5.5 (implicit regularization). Implicit regularization is a preference induced by the optimization algorithm without an explicit penalty in the loss. In linear regression, gradient methods can select a minimum-norm interpolating solution, and increasing dimension supplies additional low-norm interpolants. This gives a precise double-descent analysis in that setting. The analogous explanation for nonlinear feature-learning networks remains incomplete.

5.4 Edge of stability

For λ>0\lambda>0, consider the quadratic function L(θ)=12λθ2\mathcal L(\theta)=\tfrac12\lambda\theta^2, gradient descent with constant step size η\eta updates θt=(1ηλ)θt1\theta_t=(1-\eta\lambda)\theta_{t-1}. It is stable exactly when 0<ηλ<20<\eta\lambda<2.

Empirical remark 5.3 (edge of stability). In trained networks, the largest Hessian eigenvalue often grows toward approximately 2/η2/\eta and remains near that boundary while the loss decreases non-monotonically. This edge-of-stability behavior is reproducible but not explained by the one-dimensional quadratic theory.

5.5 Status of the claims

Theoretical aside 5.4. Variance calculations, Adam’s scale invariance, and stochastic-approximation convergence under stated hypotheses are exact. The NTK is a theorem about a limiting regime. Mode connectivity, double descent in nonlinear networks, edge of stability, and practical warmup behavior are empirical phenomena with only partial theories. Why the solutions selected by large-scale training generalize remains open.

6. The reference training run

The reference optimizer is AdamW with ηmax=3×103\eta_{\max}=3\times10^{-3}, λ=0.1\lambda=0.1, (β1,β2)=(0.9,0.99)(\beta_1,\beta_2)=(0.9,0.99), 100 warmup steps, cosine decay through step 5,000, and clipping threshold 1.0.

steptrain lossvalidation lossvalidation bits/chargapgradient normlearning rate
04.30644.30396.2090
5001.65561.81342.6160.1580.3222.96×1032.96\times10^{-3}
10001.47141.66052.3960.1890.3102.78×1032.78\times10^{-3}
15001.40191.60872.3210.2070.3042.49×1032.49\times10^{-3}
20001.34781.56792.2620.2200.3022.12×1032.12\times10^{-3}
25001.30281.53842.2190.2350.2981.69×1031.69\times10^{-3}
30001.27131.52092.1940.2500.3251.27×1031.27\times10^{-3}
35001.23631.51972.1920.2830.3348.78×1048.78\times10^{-4}
40001.20371.51882.1910.3150.3735.68×1045.68\times10^{-4}
45001.18481.50932.1770.3250.4143.69×1043.69\times10^{-4}
50001.16561.51782.1900.3520.3993.00×1043.00\times10^{-4}

Empirical observations 6.1. The initial loss is near lnV\ln V. Most improvement occurs in the first 500 steps. The training—validation gap grows from 0.158 to 0.352, indicating increasing overfit. Validation loss is essentially flat after step 3,000 and is best at step 4,500 rather than at the final step; a production run would retain the best validation checkpoint. Pre-clipping gradient norms rise late while the learning rate falls. The actual step scale ηtgt\eta_t\|g_t\| still shrinks. The norm trend is consistent with movement into a sharper region, but gradient norm alone is not a direct Hessian measurement.

Benchmark aside 6.2. The add-one bigram obtains 3.5417 bits per character. The final transformer obtains 2.1897, and the best checkpoint obtains 2.1774. The reference computation uses 816,640 parameters and about 73 minutes of laptop CPU time, closing roughly half of the bits-per-character gap between the bigram and the approximate one-bit Shannon benchmark. Samples acquire character frequencies, word forms, line breaks, and SPEAKER: structure in that order; this qualitative ordering motivates the scaling discussion in Lecture 7.

Summary

Variance-preserving initialization controls the scale of forward signals and backward gradients; residual branches motivate the 1/2L1/\sqrt{2L} output scaling. Adam combines momentum with a diagonal second-moment preconditioner, and AdamW separates weight decay from that preconditioner. Warmup limits unreliable early steps, cosine decay reduces late stochastic motion, and clipping bounds rare large gradients at the cost of bias. These algorithmic statements are more complete than the theory of feature learning and generalization: NTK results describe an infinite-width regime, while double descent and edge-of-stability behavior remain only partially explained.

Exercises (paired with Step 6)

A star marks a Project Step 6 task.

  1. ★ Prove Lemma 1.1, derive fan-in and fan-out scalings, and derive the 1/2L1/\sqrt{2L} residual correction.
  2. ★ Write AdamW in full, prove Proposition 2.2, and verify the bias- correction formulas under stationary first and second moments.
  3. Prove that L2L^2 regularization and decoupled weight decay agree for plain SGD to first order but differ under Adam. Express the discrepancy using v^t\widehat v_t.
  4. ★ Implement the warmup—cosine schedule and test its values at t=0,tw,tft=0,t_w,t_f.
  5. ★ Compare depth and width at fixed parameter count. State carefully why the experiment neither proves nor refutes Lecture 2’s worst-case depth separation theorem.
  6. For a one-dimensional quadratic loss with additive mean-zero gradient noise of variance σ2\sigma^2, compute the stationary variance of constant-step SGD and determine its scaling with η\eta.
  7. Analyze double descent in minimum-norm linear regression as the feature dimension crosses the sample size.
  8. For L(θ)=12aθ2\mathcal L(\theta)=\tfrac12a\theta^2, prove the stability boundary ηa=2\eta a=2 and explain why it does not itself explain network edge-of- stability behavior.

Pointers

Glorot and Bengio (2010); He et al. (2015); Kingma and Ba, Adam (2014); Loshchilov and Hutter, AdamW (2017); Jacot et al., Neural Tangent Kernel (2018); Belkin et al., Reconciling Modern Machine-Learning Practice and the Classical Bias—Variance Trade-Off (2019); Cohen et al., Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability (2021). See the resources page and Project Step 6.