From Transformer Matrix Flows to Modern Optimizer Derivations (SGD → AdamW → Muon)
Starting from autoregressive language modeling, we classify the four tensor families in VRAM across inference and training, derive cross-entropy and linear-layer backpropagation, trace four generations of entrywise optimizers, and derive the matrix optimizer Muon from induced operator norms and Newton-Schulz iterations.
Deep learning courses and production codebases often meet across a noticeable conceptual gap. Chapters on neural architectures—such as the Transformer[1]—revolve around three-dimensional activation tensors, multi-head subspace projections, and causal attention matrices. Chapters on optimization—such as SGD[2] and AdamW[3]—collapse every parameter in the network into a flat vector and study scalar coordinate updates on quadratic bowls.
The moment you open an actual large language model pretraining script, the seam between those two narratives surfaces as concrete questions about memory layout, matrix contractions, and operator geometry. This post follows a single bottom-up chain of derivations to align both halves into one coherent picture.
Specifically, we work through five connected questions in order:
GPU memory simultaneously holds token embedding tables, projection weights, attention score matrices, the KV Cache, gradient buffers, and momentum states. What mathematical role does each of these "matrices" play, which ones belong to the model itself, and which ones exist only transiently during inference or training?
Chat inference generates one token at a time sequentially—so why does training code have no token-by-token loop, feeding the entire sequence into the network at once? And why does training the exact same model require several times more VRAM than running inference?
The loss function outputs a single scalar . Through what exact matrix algebra does loss.backward() produce a two-dimensional gradient matrix matching the shape of each weight matrix —and why is the singular value spectrum of so heavily skewed?
Moving from SGD to Momentum, Adam, and AdamW, what specific mathematical limitation did each generation solve, and how are bias correction and decoupled weight decay derived from first principles?
When a parameter is a two-dimensional linear operator of shape , what geometric structure do entrywise adaptive methods ignore? How does the matrix optimizer Muon[4][5] derive the semi-orthogonal update direction from induced operator norms, and how does it replace singular value decomposition with five half-precision matrix multiplications?
We start from the autoregressive factorization of sequence probability and classify every tensor in inference and training into four lifecycle families (Section 1). Next, we derive the forward and backward equations of a single training step, exposing the sum-of-outer-products structure of linear-layer gradients (Section 2). Under a unified variational principle—local linearization plus a proximal penalty or norm-ball constraint—we then derive four generations of entrywise optimizers (SGDMomentumAdamAdamW, Section 3) followed by two-dimensional spectral optimizers (ShampooMuon Moonshot AI's RMS-aligned scaling, Sections 4–5). Finally, we close the loop with a GPU roofline analysis, controlled ablation benchmarks, and a self-contained single-file PyTorch implementation (Sections 6–7).
#Bird's-Eye Overview: Model, Inference, Training, and Optimizers on One Map
Before diving into local equations, it helps to see how the pieces fit together globally. An LLM itself is nothing more than a fixed set of static parameter matrices persisted on disk and in VRAM—comprising the boundary vocabulary tables , stacked layers of 2D linear operators , and 1D normalization gain vectors . Around that single set of parameters , inference and training form two distinct dataflows:
Inference is a read-only one-way pipeline (Section 1): remains frozen throughout. Input prompt tokens first pass through a parallel Prefill GEMM stage that populates the historical KV Cache; subsequent Decode steps feed a single new token row via matrix-vector products (GEMV) to sample one token at a time, freeing transient activations immediately after each layer.
Training is a parameter-mutating four-step closed loop (Sections 2–5): to propagate prediction errors back through every layer, 1. Parallel Forward must retain intermediate activations in VRAM; 2. Cross-Entropy Loss reduces all token predictions into a single scalar ; 3. Backward applies the chain-rule contraction to sum out the batch-and-token axis, producing a gradient matrix of the exact same shape as each parameter; finally, 4. Optimizer Step combines with historical states to overwrite —routing boundary lookup/scoring tables to entrywise AdamW (Section 3) and the internal 2D linear operators (>95% of non-embedding parameters) to spectral Muon (Sections 4–5).
Bird's-Eye Overview: How Static Parameters Sit Between Read-Only Inference and the 4-Step Training Loop
MODEL · STATIC PARAMS ΘBoundary TablesInternal 2D OpsShapes fixed by architecture; saved in checkpointsRead-only in inference · Updated in trainingINFERENCE · READ-ONLY PIPELINE (SEC. 1)1. Prefill (GEMM)Parallel prefix pass2. KV CacheStores past K, V3. Decode 1-row GEMV samples next tokenTRAINING · 4-STEP CLOSED LOOP (SEC. 2–5)1. Forward PassCaches activations X2. CE LossReduces to scalar L3. Backward4. Update ΘAdamW + Muon
Blue denotes static model parameters ; teal denotes transient activations or updates; violet denotes the inference KV Cache or momentum buffers; orange denotes backward gradient matrices.
#1. Autoregressive Factorization and the Four Tensor Families in VRAM
#1.1 What a Language Model Computes: Chain Rule of Probability and Token Embeddings
Let the vocabulary contain discrete tokens. Given a token sequence of length , the product rule of probability decomposes the joint distribution of the entire sequence—with zero approximation—into a product of next-token conditional probabilities given each prefix:
Here denotes the collection of all learnable parameters. The modeling objective of an LLM is to construct a -parameterized function that takes a prefix , outputs a vector of unnormalized log-scores (logits) over all candidate next tokens, and maps them to a valid probability distribution via Softmax:
Because discrete token IDs are arbitrary dictionary indices—token 500 is not "twice" token 250—calculus derivatives cannot act directly on integers. The network therefore begins with a token embedding matrix that maps each integer ID to row in continuous space . Writing for the one-hot column vector with a only at index , row lookup is algebraically identical to the sparse matrix product .
Row lookup alone is still not enough on a sequence of length : inner products in self-attention are permutation-equivariant with respect to token order (without positional information, swapping "cat chased dog" into "dog chased cat" merely permutes the output rows without changing their representations). Adding absolute or relative positional encodings produces the initial hidden state (or a 3D tensor in across a batch of sequences). Every subsequent sublayer adds its output back onto this shared highway via , known as the residual stream.
#1.2 Forward Equations of a Single Transformer Block
Modern open-weights LLMs (such as Llama, Qwen, and DeepSeek) almost universally adopt a bias-free Pre-RMSNorm decoder block[1][6]. Given a single sequence's residual stream with hidden width , define row-wise root-mean-square normalization on a row vector as , where guards against division by zero, is a learnable per-channel gain vector, and denotes elementwise (Hadamard) multiplication (whose backward orthogonality we derive in Section 2.1). Each Transformer layer then applies two sublayers:
Sublayer 1: Multi-Head Causal Self-Attention. Row-wise normalization is projected by three linear matrices into queries, keys, and values:
where . Computing a single inner product across the full -dimensional space would give each token only one scalar attention distribution per layer, forcing coreference, syntactic modification, and local collocations to compete for the same weights. Instead, the hidden width is partitioned into parallel subspaces (attention heads) of width . In batched code, a tensor is reshaped to and transposed to . On head 's slices , scaled causal dot-product attention computes:
Here both the score matrix and the probability matrix have shape . The causal mask equals on and below the main diagonal () and strictly above it (, where position would peek at a future token ). Since , row-wise Softmax turns into a strictly lower-triangular stochastic matrix whose -th output row depends only on positions .
Why divide by ? Suppose the coordinates of and are independent with zero mean and unit variance. Each product term has and , so the variance of the full dot product grows linearly with subspace width:
Without dividing by , at or the dot product's standard deviation reaches –, pushing the largest entry in each row far above the rest and driving toward a one-hot corner. Differentiating the quotient shows that the local Jacobian of Softmax is (where the Kronecker delta is if and otherwise); once saturates to s and s, every entry of that Jacobian vanishes for both and , starving the query and key projections of gradient[1]. Dividing by restores unit variance.
Concatenating all heads back along the last axis into , multiplying by (), and adding back to the residual pathway yields .
Sublayer 2: Position-wise FFN / MLP. Normalizing again via , the hidden representation expands through (classically ), passes through an elementwise nonlinearity such as , projects back down via , and joins the residual stream:
After stacked blocks, a final RMSNorm followed by the language-modeling head () produces the full-sequence logit matrix .
Note on PyTorch nn.Linear weight shapes: calling nn.Linear(in_features=64, out_features=256, bias=False) stores .weight with transposed shape (256, 64)—that is, —and evaluates in the forward pass. Because C/CUDA arrays are row-major, laying out the weights of each output neuron contiguously along a row makes inner-product reads sequential in memory. Throughout this post, every 2D weight matrix follows PyTorch's layout with rows and columns.
Every multi-dimensional array appearing in the equations above is casually called a "matrix," yet by mathematical definition, shape dependence, and memory lifetime, they partition cleanly into four distinct families:
Mathematical Roles and Lifetimes of the Four Tensor Families in VRAM
FAMILY 1 · PARAMETERSStatic WeightsShape fixed by model config; independent of length TFrozen in inference · Updated by optimizer in trainingFAMILY 2 · ACTIVATIONSActivationsComputed on the fly per input batch (incl. attention P)Freed per layer in inference · Cached in training for bwdFAMILY 3 · INFERENCE CACHEKV CacheStores past token keys & values; appends 1 row/stepInference-only resident · Never allocated in trainingFAMILY 4 · TRAINING STATESGrads & StatesSame-shape gradient G, 1st moment M, 2nd moment VTraining-only · Muon drops V on all internal 2D layers1 · PARAMETERSStatic WeightsIndependent of T; the only tensors saved to diskRead-only in inference · Updated in training2 · ACTIVATIONSActivationsComputed per input batch, incl. attention matrix PFreed in inference · Cached in training for bwd3 · INFERENCE CACHEKV CacheSaves past keys & values; grows by 1 row per stepInference-only · Not allocated in training4 · TRAINING STATESGrads & StatesSame-shape grad G, momentum M, second moment VMuon eliminates V across all internal 2D layers
Static parameter shapes depend only on architecture hyperparameters; dynamic activations scale with batch B and sequence length T; the KV Cache grows token-by-token only during decoding; gradients and optimizer states are allocated alongside parameters only during training.
For newcomers, the easiest pair of objects to conflate is the projection weights versus the attention probability matrix . The former are Family 1 static parameters: whether the prompt is 4 tokens or 4,096 tokens long, their shape is permanently , and they are the actual weights modified by the optimizer. The latter is a Family 2 transient activation: its dimensions stretch and shrink with the current sequence length , capturing pairwise token alignments inside a single forward pass—never saved to a checkpoint and never directly stepped by an optimizer.
Static Projection Weights vs. Transient Attention Matrix
Family 1 Static Params: Query & Key ProjectionsUpdated by OptSaved to weightsShape fixed by hidden width D, independent of TDefines subspace maps for queries and keysPrimary target of spectral optimizer Muon (Sec. 4)Family 2 Activation: Causal Attention MatrixTransient ValueNot a parameter4×4 for a 4-token input; 100×100 for 100 tokensUpper triangle is 0 by causal mask; freed after stepUsed in backward pass only to route upstream gradsFamily 1 Params: Projection WeightsUpdated by OptSaved to diskFixed shape D×D, independent of sequence length TInternal 2D operators updated by MuonFamily 2 Activation: Attention MatrixTransient DataNot trainableScales as T×T per sequence; discarded after stepUpper triangle is 0 to block future token leakage
Projection matrices have fixed shape shared across all inputs; the attention matrix has dynamic shape representing temporary token-to-token routing inside one sequence.
Comparing the mini Transformer used in Section 7 () against a production 7B-class model summarizes all 14 tensors across the pipeline:
14 Tensor Types Across Transformer Inference and Training
Tensor & Symbol
Family
Mini Shape
Typical 7B Shape
Inference
Training
Inputs & targets
Token IDs
Prefix only
Shifted by 1 token
Token emb
1. Parameter
Read-only lookup
AdamW step
Pos emb
1. Parameter
Parameter-free RoPE
Broadcast add
AdamW step
Attention
1. Parameter
Four
Read-only GEMM
Muon orthogonal step
FFN
1. Parameter
Read-only GEMM
Muon orthogonal step
Norm gain
1. Parameter
1D
1D
Channel scale
AdamW (wd=0)
LM head
1. Parameter
Last-row logits
AdamW step
Residual & norm
2. Activation
Freed per layer
Cached for backward
Multi-head
2. Activation
Freed per layer
Cached for backward
Attention
2. Activation
Freed per layer
Cached or recomputed
Logit tensor
2. Activation
Last row only
Full-seq CE loss
Cache
3. KV Cache
+1 row per step
Not allocated
Weight grad
4. Train State
Same as param
Same as param
Not allocated
Written in backward
Opt states
4. Train State
Same as param
Same as param
Not allocated
Resident (Muon drops )
Production models (e.g., Llama 3 / Qwen) commonly use Grouped-Query Attention (GQA) to shrink the output rows of for a smaller KV Cache, and add a gate matrix in SwiGLU FFNs; all remain dense 2D linear operators.
#1.4 Why Inference Needs a KV Cache While Training Runs in Parallel
A second payoff of classifying these four families comes from examining the lower-triangular causal mask , which explains both the two-stage structure of inference (Prefill vs. Decode) and parallel Teacher Forcing during training.
Consider inference first. Future tokens do not exist yet: given a user prompt , the model must predict , append to the sequence, and only then predict .
Prefill stage: all prompt tokens are known simultaneously, so multiplies via dense matrix-matrix multiplication (GEMM), computing keys and values across all positions at once and sampling the first generated token from row 's logits.
Autoregressive Decode stage and redundancy: at step , when is available and we want , feeding the entire prefix back through the network would recompute identical hidden states and identical projections , bit-for-bit, because the causal mask at every layer forbids positions from reading position . Moreover, sampling requires only the final output row :
Neither historical queries nor the upper rows of the attention table are needed. By caching and in VRAM (the KV Cache), step feeds only the single new row , computes via matrix-vector products (GEMV), appends as row of the cache to form , and executes a lightweight product.
Counting multiply-accumulate operations (MACs, where ) per layer of width makes the asymptotic gap explicit. Without a KV Cache, recomputing projections at length costs and attention costs ; summed from to , cumulative work scales as . With a KV Cache, each decode step projects a single row in and attends over cached keys in , reducing cumulative work to .
Now contrast training. During training, the complete ground-truth sequence from the corpus is already on hand. Feeding as input and the one-token-shifted sequence as targets (Teacher Forcing), the causal mask blocks row from attending to any column inside the matrix itself. One parallel GEMM is therefore mathematically identical to running prefix-prediction tasks at once—saturating GPU Tensor Cores without ever allocating a KV Cache.
Full-Flow LLM Inference Matrix Shapes: Tracking Dimension Alignment & Contraction with Unit Blocks
STAGE 1 · PREFILLParallel prompt pass (prefix T₀=3, hidden D=4, head dim 2, FFN dim 6, vocab V=6)1. Lookup & head projection: shared inner D=4 (blue) contracts out, leaving 3 rows × 2 cols3 rowsSame shape for K and V:← Saved to KV CacheReused in Decode steps2. Causal attention & head concat: Q Kᵀ cancels inner dim 2 into lower-triangular [3×3], then × VH1H2Dashed cell = 0Causal future mask3. FFN (4→6→4) & LM head: take only the last row [1×4] × head [4×6] = logits [1×6]row 3STAGE 2 · DECODE + KV CACHEStep t=4: activations collapse to 1 row [1×4]; KV Cache appends 1 new row3 old + 1 new2H+FFNStatic weights (blue) keep fixed shapes; 3-row Prefill activations shrink to 1-row strips in DecodeViolet cells are cached K, V from prefix tokens 1..3; clay cells are the single new row appended at t=41 · PREFILL (3-ROW PARALLEL GEMM)Project: [3×4] × [4×2] → inner 4 cancels to [3×2]Causal attention: [3×2]×[2×3] = [3×3] lower-triTake row 3 [1×4] × LM head [4×6] = logits [1×6]2 · DECODE (1-ROW QUERY + APPEND ROW 4)3 old+1Attention shrinks from [3×3] to a 1-row strip [1×4]Clay cells mark the single new row appended to cacheStatic weights stay fixed; dynamic activations are 1 row
Each discrete square represents one scalar entry (). Dashed arcs connect matching inner dimensions summed out in matrix multiplication; moving from Stage 1 to Stage 2 collapses every -row activation into a single -row strip while appending just row to the violet KV Cache.
#1.5 Unfolding the Matrices: Hand-Tracing a 3-Token Sentence Through Prefill and Decode
Compact matrix equations and block-shape diagrams summarize the architecture cleanly, yet newcomers often hit a wall when asking what happens inside the brackets: how do actual numbers transform step by step from token IDs to attention outputs? Shrinking the dimensions to hand-calculable integers lets us unfold every matrix on the page.
Take a 5-token toy vocabulary (0:<pad>, 1:cat, 2:chases, 3:dog, 4:runs), hidden width , and single-head width . Suppose the input prompt is the 3-token prefix ["cat", "chases", "dog"], mapped to integer IDs .
Step 1: Embedding lookup as one-hot row selection. Unfold the static embedding table . Indexing rows is algebraically identical to left-multiplying by a one-hot selector matrix (omitting positional offsets here and taking the normalized hidden state directly as , whose three rows already share identical RMS):
Nothing mysterious happens here: embedding lookup simply copies rows 1, 2, and 3 out of the vocabulary table into a activation matrix, leaving unused vocabulary rows (0 and 4) untouched.
Step 2: Linear projections into . Multiply on the right by the static transposed projection matrices :
For instance, top-left entry is the dot product of row 1 of () with column 1 of (): . Notice that linear projections remix feature columns strictly within each token's own row—the 3 tokens have not exchanged information yet. Meanwhile, and are saved into VRAM as the initial 3-row KV Cache.
Step 3: Four-stage causal self-attention (dot products mask Softmax weighted sum of ). Now tokens interact across positions. First multiply by to get all pairwise dot products:
Divide by , add the causal mask (replacing every above-diagonal entry with ), and apply row-wise Softmax (since , future weights vanish identically):
Multiplying the lower-triangular probability table into yields:
Reading one row at a time strips away all abstraction:
Row 1 ("cat"): , seeing only itself;
Row 2 ("chases"): , pulling of "cat"'s value vector into "chases" while remaining blind to future token "dog";
Row 3 ("dog"): , pooling context across all 3 prefix tokens. At the end of Prefill, only this final row is projected through the FFN and LM head —suppose sampling picks token 4:runs.
Step 4: Advancing to Decode step (why a single row suffices). To predict token 5 given newly sampled 4:runs, causal masking guarantees that rows 1..3 of and would never change even if we reran the whole 4-word sequence. So step 4 does not build a input matrix: it looks up only the single row and runs three vector-matrix products:
Appending as row 4 of the cached tables forms , after which attention reduces to a single dot-product strip:
Taking that 4-weight average of gives —without ever materializing the upper 3 rows of a attention matrix.
Unfolded Numeric Walkthrough: Cell-by-Cell Matrix Transformations in 3-Token Prefill and Step-4 Decode
Replacing abstract symbols with hand-verifiable numbers (, scale ). Stage 1 shows how causal masking turns each output row into a convex combination of visible value vectors; Stage 2 shows step-4 decoding computing from a single query row and a 1-row append to the violet KV Cache.
The two empirical figures below quantify both memory footprint and compute scaling. In the 6-layer float32 model of the first chart (, 4 bytes per parameter), static weights total parameters ( in embeddings/head and in internal 2D matrices), occupying ; during training at , cached forward activations across the 6 layers take ; and under Muon+AdamW, dropping the second-moment buffer from all internal 2D matrices leaves only of states on the boundary layers. The second chart tracks cumulative MACs across a 4-layer model decoding 112 tokens from to .
VRAM Breakdown of a 6-Layer Transformer Across Inference and Three Training Optimizers
Measured tensor byte counts on a 6-layer Transformer (, 8 heads, fp32, batch , length ). Training retains forward activations and allocates gradients plus state buffers; Muon+AdamW eliminates second-moment on all internal 2D layers (keeping only 4.2 MB on boundary params).
Autoregressive Decoding from Prefix 8 to Length 120: KV Cache Cuts Cumulative MACs to Near-Linear
Sequence length (Prefill finishes at , followed by 112 Decode steps for )
4-layer Transformer () after an 8-token Prefill (), followed by 112 autoregressive Decode steps (). Cumulative MACs drop from 6,758.5M to 109.7M (-98.4%).
With "optimizers only mutate Family 1 static parameters " established, the next question is how a single scalar loss differentiates backward into a full two-dimensional gradient matrix for every weight layer.
#2. Normalization Scale Invariance and Matrix Backpropagation
Walking through the calculus inside a single training step explains why forward activations dominate training VRAM and establishes two foundational properties used throughout the rest of the post: how RMSNorm fixes the input RMS scale of hidden layers, and why linear-layer gradients form a sum of rank-one outer products.
#2.1 Origin of RMSNorm and Proof of Radial Gradient Orthogonality
Original Transformers used LayerNorm: given a token vector , compute its mean , then its variance , and output . On GPUs, because variance depends on the mean, every token vector requires two cross-channel reductions whose memory latency outweighs arithmetic cost.
In 2019, Zhang and Sennrich hypothesized that LayerNorm stabilizes deep networks not through mean-centering (shift invariance), but through rescaling vector magnitude (scale invariance)[6]. Dropping mean subtraction and bias yields Root Mean Square Layer Normalization (RMSNorm):
where is initialized to all ones. Two algebraic consequences follow directly:
Unit-RMS forward outputs: as with , satisfies . Consequently, every linear projection immediately following RMSNorm receives input vectors normalized to unit root-mean-square magnitude—a fact that directly dictates the natural operator norm for measuring weight updates in Section 4.
Inverse-scale backward gradients and radial orthogonality: at , for any scalar , . Let the downstream loss be with upstream gradient , and set . Differentiating with respect to coordinate (using ) gives:
In vector form:
Since , left-multiplying by yields:
Thus the gradient propagated back to is strictly orthogonal to itself (zero directional derivative along radial rescaling of ) and scales inversely with : inflating activations by shrinks backward gradients by , preventing norm explosion in deep residual stacks[6].
#2.2 Derivative of Cross-Entropy Loss with Respect to Logits
Now trace a training batch of sequences of length , giving next-token prediction positions. Flatten the final logits into , and let denote the ground-truth next token at position .
Cross-entropy loss averages the negative log-likelihood of the true token across all positions:
where . At random initialization, all logits are nearly equal so , placing the theoretical initial loss right at ( for , or for ).
Differentiating with respect to logit —noting that row 's probabilities depend only on row 's logits—eliminates all terms :
Collecting entries yields the root backward error matrix :
Its sign structure is transparent: on the ground-truth column , since , the derivative is negative, instructing gradient descent to push that logit up; on every incorrect column , the derivative is positive and proportional to the probability mass mistakenly assigned to token ; and every row sums identically to .
#2.3 Linear-Layer Matrix Calculus and the Root Cause of Spectral Skew
With the top-level error matrix in hand, consider any internal bias-free linear layer , where flattened inputs are , weights are , outputs are , and the upstream gradient () has arrived from above.
Expanding coordinate by coordinate:
Ask where a single scalar weight participates: across every token , appears exclusively in output channel 's term with local derivative (and whenever ). Summing over all paths via the multivariable chain rule gives:
By definition of matrix multiplication, the right-hand side is entry of times . By the same reasoning, input coordinate contributes to all output channels of row with , yielding . Together:
where and are the column vectors for token 's upstream error and layer input.
STAGE 1 · FORWARD & LOSSParallel forward & all-token loss (batch tokens N=5, in=4, out=3, vocab V=6)Cached for Stage 3to LMheadV=6 vocab5-rowmean CEScalar (1×1)Backward rootSTAGE 2 & 3 · BACKWARDUpstream grad [5×3] splits: left propagates error; right transposes to cancel N=5Left branch (to lower layer): inner 3 cancels, keeps N=5Forward multiplies by Wᵀ [4×3]; backward by W [3×4]Right branch (weight grad): token axis N=5 sums outN=5 colsN=5 cancels out: G [3×4] matches W [3×4] cell for cellSTAGE 4 · OPTIMIZER STEPGiven the 12-cell gradient G [3×4]: entrywise AdamW vs matrix-spectral MuonA · Entrywise AdamW: scales all 12 cells independentlyCells never see each other (ideal for embeddings & head)Stores two 12-cell state buffers: M and VB · Matrix-Spectral Muon: drops V, orthogonalizes [3×4]NS5Flattens full singular spectrum (for internal 2D layers)No second-moment V [3×4] needed (50% less state VRAM)1 · FORWARD (N=5 PARALLEL & CACHED)X [5×4] stays in VRAM to compute G in backward pass2 · BACKWARD (TRANSPOSE CANCELS N=5)Weight grad: 5 cols of ΔYᵀ pair with 5 rows of XN=5 sums out: G [3×4] matches W [3×4] cell for cellLeft branch [5×3]×[3×4] = [5×4] flows to earlier layers3 · OPTIMIZER (CELLWISE VS WHOLE-MATRIX)NS5Muon: orthogonalizes [3×4] as one operator, drops VAdamW: stores V [3×4], scales 12 cells independently2D hidden layers → Muon; embeddings & head → AdamW
Batch tokens (clay rows), input dim (blue cols), output dim (violet cols). Stage 2 right shows how the horizontal columns of pair with and cancel the vertical rows of cached , leaving a -cell gradient identical in shape to .
These two compact equations simultaneously explain four central facts of LLM engineering and optimization:
Why always has the exact shape of : the batch-and-token dimension is the shared inner axis contracted out in , leaving regardless of batch size or context length .
Why training VRAM dwarfs inference VRAM: evaluating in the backward pass explicitly requires the forward activation saved from Stage 1. Attention behaves identically—differentiating and gives , , , and , requiring forward (FlashAttention avoids materializing the matrix in HBM by recomputing tiles in SRAM, but and layer inputs still stay resident unless activation checkpointing trades extra forward compute for memory).
Why zero_grad() is required before backward: when full batches exceed GPU memory, training splits each step into micro-batches and calls loss.backward() repeatedly so PyTorch accumulates (+=) each micro-batch's into W.grad before stepping once. Standard single-batch steps must therefore zero out stale gradients explicitly.
Why neural network gradient matrices exhibit extreme singular-value skew: look at the outer-product sum . Natural language token frequencies follow a heavy-tailed Zipf distribution, so frequent function words and shared syntactic directions dominate every batch, concentrating the eigenvalues of into a handful of top principal components. Consequently, is severely anisotropic: its top few singular values are orders of magnitude larger than the dozens or hundreds of tail singular directions carrying rare facts and fine-grained contextual circuits.
#2.4 Unfolding Backpropagation: Hand-Tracing 2-Token Cross-Entropy and Outer-Product Gradients
Let us likewise substitute concrete numbers into Sections 2.2 and 2.3 so we can watch a single scalar loss differentiate back into a 2D weight gradient matrix —and see firsthand why naturally exhibits severe singular-value skew.
Step 1: From logits to top-level gradient . Consider token positions over a 3-word vocabulary , with ground-truth target IDs and (one-hot matrix ). Suppose forward logits are:
Mean cross-entropy is the scalar . Plugging and into with gives:
Every sign has a direct physical meaning: ground-truth columns receive negative derivatives () so gradient descent pushes those target scores up, while wrong candidates receive positive derivatives () proportional to the probability mass mistakenly assigned to them.
Step 2: Forward caching and two-way backward split inside . Zoom into an internal linear layer mapping . Let the cached forward input for our tokens be and weights be :
Suppose upstream backpropagation hands back . The backward pass splits into two matrix products:
Left branch (propagating error to earlier layer input ): multiply by (untransposed), contracting out to recover a activation gradient matching :
Right branch (joining with cached to form weight gradient ): transpose and multiply into . Expanding across tokens exposes the sum of rank-one outer products :
Inspect the resulting gradient : because both tokens shared the frequent prefix features in columns 1 and 2, row 1 is row 2 across the first two columns; only column 3 ( vs. , contributed by token 2's unique 3rd coordinate 1) breaks exact collinearity. Taking the square roots of the eigenvalues of gives the two singular values of :
Even across a 2-token toy batch, shared input directions open a singular-value gap—setting the stage for Section 4.
STEP 1 · CROSS-ENTROPY GRADIENT UNFOLDEDTeal = true target cols (neg grad → raises logit); orange = wrong cols (pos grad → lowers logit)2.01.00.00.02.01.0softmax0.670.240.090.090.670.24−100010-0.17+0.12+0.05+0.05-0.17+0.12STEP 2 · LINEAR WEIGHT GRADIENT: TRANSPOSE MATMUL = SUM OF OUTER PRODUCTSToken axis N=2 contracts out; because both tokens share [1, 2] in cols 1..2, G has a 67× singular-value skew (2.45 vs 0.037)-0.6-0.40.20.2×120121=-0.6-1.20.00.20.40.0token 1 outer+-0.4-0.8-0.40.20.40.2token 2 outer=-1.0-2.0-0.40.40.80.2Only col 3 (clay -0.4, 0.2) breaks row collinearity → dominant σ₁=2.45 vs tiny σ₂=0.0371 · CROSS-ENTROPY GRADIENT0.670.240.090.090.670.24−100010-0.17+0.12+0.05+0.05-0.17+0.12True col = -0.17Wrong cols > 0Subtracting ηΔ raises true-token logits2 · WEIGHT GRAD = TOKEN OUTER SUM-0.6-0.40.20.2×120121-0.6-1.20.00.20.40.0+-0.4-0.8-0.40.20.40.2=-1.0-2.0-0.40.40.80.2σ₁ = 2.45σ₂ = 0.037 (67×)Shared prefix features naturally skew singular values
Step 1 shows assigning negative entries to ground-truth columns and positive entries elsewhere; Step 2 unfolds as the cellwise sum of token rank-1 matrices , revealing how shared features create a 67× singular-value skew.
Once is computed, how should optimizer.step() update the weights? We begin with flat vectors and derive four generations of entrywise optimizers.
#3. Proximal Steepest Descent and Four Generations of Entrywise Optimizers
To compare SGD, Momentum, Adam, AdamW, and eventually Muon on equal footing, we formulate first-order updates in proximal steepest-descent form.
Let be the parameter vector after step , and let be the current mini-batch gradient. A first-order Taylor expansion around gives . Because this linear approximation holds only locally—minimizing a bare linear function over would diverge to —we add a quadratic proximal penalty measuring step size:
with learning rate . Setting the gradient of this strictly convex quadratic with respect to to zero yields:
This is classical Stochastic Gradient Descent (SGD)[2]. Crucially, the statement that " is the steepest descent step" depends entirely on choosing the isotropic Euclidean norm to measure parameter displacement. Whenever loss curvature varies wildly across directions, Euclidean distance becomes a poor local metric.
#3.1 Generation 1: SGD Bottlenecks Under Ill-Conditioned Curvature
Its gradient is , its unique minimum sits at , and its condition number is . Under vanilla gradient descent, the two coordinates decouple into geometric progressions:
Preventing divergence along the steep wall requires , imposing a strict ceiling on the learning rate:
Whenever , the factor is negative, so flips sign every step and zigzags across the canyon walls. Worse still, capping forces the contraction factor along the flat valley floor to satisfy:
Using , shrinking 's initial error by takes steps. In deep networks where Hessian condition numbers routinely reach –, progress along flat directions crawls.
#3.2 Generation 2: Polyak Heavy-Ball Momentum and Nesterov Lookahead Reformulation
How can we damp sign-flipping oscillations across steep walls while accelerating consistent progress down the valley floor? In 1964, Boris Polyak drew on the damped mechanics of a heavy ball rolling on a potential surface, accumulating an exponential moving average (EMA) of past gradients[7]:
(Implementations often omit as , absorbing the constant into .) Evaluating steady-state gain on two canonical gradient sequences shows why this works:
Consistent flat direction ( every step): for large , , preserving full forward drive (or amplifying effective step size by at in the unscaled convention);
Alternating steep direction ( flipping sign every step): the steady-state amplitude is
At , , damping cross-wall oscillation by nearly . On convex quadratics, optimal momentum improves iteration complexity from to .
In 1983, Yurii Nesterov observed a further refinement: since momentum is about to carry the iterate forward by anyway, rather than evaluating the gradient at the old point , we should step to the lookahead point first and evaluate the gradient there to correct course earlier[8]:
At first glance, evaluating seems to require a second forward/backward pass at a temporary point. Deep learning frameworks (both PyTorch's SGD(..., nesterov=True) and Muon below) eliminate that extra pass via a change of variables: store the lookahead point itself as the model parameter , so the standard backward pass directly yields . Defining gives with . Expressing in terms of :
Setting produces the exact two-line recurrence M = mu * M + G; tilde_M = G + mu * M used inside Muon in Section 7. Compared with heavy-ball momentum , Nesterov lookahead weights the freshest gradient by , braking earlier around curved ravines.
#3.3 Generation 3: Adaptive Preconditioning and Adam's Bias Correction
Momentum tames curvature within a layer, but deep Transformers also exhibit multi-order-of-magnitude gradient disparities across layers and token frequencies: a rare token's embedding row may see gradients of while an attention projection sees .
Returning to the proximal framework, replace the isotropic Euclidean penalty with a coordinate-weighted diagonal Riemannian metric for :
Three classic algorithms construct progressively:
AdaGrad (Duchi et al., 2011)[9]: accumulate all historical squared gradients and set . Optimal for sparse convex online learning, its non-decreasing denominator steadily shrinks effective learning rates toward zero over tens of thousands of non-convex training steps.
RMSProp (Hinton, 2012): introduce a decay factor (e.g., or ) to replace infinite summation with a leaky EMA over an effective window of steps: , dividing by .
Adam (Kingma & Ba, 2015) and cold-start bias correction[10]: combine first-moment momentum in the numerator with second-moment in the denominator, initialized at :
(where denotes elementwise ). Why is bias correction essential? Unrolling back to by induction gives:
Taking expectations on both sides—letting and writing so the non-stationarity remainder under locally stationary gradients—the finite geometric series yields:
Similarly, . Because and carry the remaining weights and , both raw estimators are biased toward zero early in training. At step with standard defaults , the uncorrected ratio for any nonzero gradient has magnitude:
Because is much closer to than , the denominator is biased toward zero far more strongly than the numerator, inflating the very first step by (or at ) and risking early divergence.
Dividing each EMA by the sum of its weights and yields the unbiased estimators :
Now at step , while smoothly as . Statistically, acts as a per-coordinate empirical signal-to-noise ratio (SNR): near a minimum where , mini-batch variance keeps while sign cancellation drives , automatically annealing step sizes[10].
#3.4 Generation 4: Non-Equivalence of Regularization and Decoupled Weight Decay (AdamW)
Without norm control on overparameterized networks, minimizing finite-sample cross-entropy drives redundant weights to large magnitudes, sharpening logits and hurting generalization. From a Bayesian MAP perspective, placing an isotropic zero-mean Gaussian prior on the parameters adds a quadratic penalty to the loss:
Independently, Hanson and Pratt (1988) defined weight decay as directly shrinking parameters each step via . Substituting into vanilla SGD gives:
Setting makes the two identical. Because of this coincidence, deep learning libraries implemented weight_decay by adding wd * theta onto g_t before running the optimizer. Yet once Adam became popular, models trained with Adam + regularization generalized noticeably worse than SGD + Momentum.
In 2019, Loshchilov and Hutter proved why the two are inequivalent under adaptive preconditioning[3]. Consider any preconditioned update with symmetric positive-definite preconditioner and decoupled decay rate :
Does there exist a fixed differentiable regularizer such that running the same preconditioner without decoupled decay on produces the exact same iterate? First, when evolves with historical gradients, no time-independent function can match it at all; even if is held constant, equating the two updates requires:
Canceling common terms and left-multiplying by yields the exact condition:
Two conclusions follow immediately:
Necessary and sufficient condition: isotropic regularization equals weight decay if and only if is a scalar multiple of the identity (SGD).
Distortion of coupled inside Adam: in Adam, varies across coordinates. Mixing into both contaminates and (taking to inspect a single step) produces:
Coordinate 's effective shrinkage rate becomes , divided by its historical gradient RMS: active weights with large gradients () barely decay at all, whereas quiet weights () are aggressively crushed—the exact opposite of an isotropic Gaussian prior.
AdamW fixes this by decoupling weight shrinkage from the adaptive gradient ratio:
Dataflow Comparison: Coupled Regularization vs. Decoupled Weight Decay (AdamW)
Under coupled , the penalty enters the gradient and gets divided by , distorting per-coordinate shrinkage; AdamW applies uniform multiplicative decay directly to the weights.
The numerical verification below illustrates both derivations: the left panel plots 26 steps of SGD, Momentum, and AdamW on the canyon ; the right panel runs Adam+L2 versus AdamW on two redundant parameters initialized at under zero-mean alternating gradient noise of amplitude versus , showing Adam+L2's noisy coordinate stalling at while both AdamW trajectories overlap identically down to .
Entrywise Optimizer Verification: Ill-Conditioned Trajectories and Coupled Decay Distortion
0.00.51.01.52.02.5↑ Parameter value050100150Step t →Adam+L2 high-grad stalls at 2.39AdamW both decay equally to 0.74Adam+L2 low-grad shrinks to 0.39
0.00.51.01.52.02.5↑ Parameter value050100150Step t →Adam+L2 high-grad stalls at 2.39AdamW both decay equally to 0.74Adam+L2 low-grad shrinks to 0.39
Left: 26 steps on (). Right: decay toward zero under zero-mean alternating noise ( amp 40, amp 0.05, init , ).
One practical corollary: why is weight_decay set to 0.0 on 1D RMSNorm gains (and biases) in AdamW? Initialized to , rescales unit-RMS activations per channel and accounts for less than of model parameters; pulling toward does not regularize high-rank capacity and merely dampens layer outputs.
#4. From Entrywise Norms to 2D Operator Spectral Norms: Deriving Muon
AdamW gives us the modern entrywise baseline. Now return to the structural facts from Sections 1 and 2: over of non-embedding parameters in a Transformer () are 2D linear operators whose gradients have heavily skewed singular spectra. What geometry does AdamW implicitly impose when handed such a 2D matrix?
#4.1 AdamW's Hidden Geometry: Steepest Descent Under the Entrywise Max Norm
To compare non-Euclidean norms cleanly, rewrite the proximal penalty of Section 3 in constrained normalized steepest descent form. Let denote the Frobenius inner product, with Frobenius norm . Given any matrix norm and step budget , steepest descent on the -ball solves:
(By Lagrangian duality, the ball-constrained solution shares the exact direction of the quadratic penalty problem while fixing step length ; under the Frobenius norm , for instance, .)
Now inspect Adam in the memoryless limit (): each entry steps by (SignSGD). That is the exact steepest-descent step under the entrywise max norm (the norm of the flattened matrix):
Geometrically, AdamW is EMA-smoothed steepest descent under the entrywise norm[12].
Treating a linear map as uncoupled scalar boxes has two fundamental limitations:
Basis dependence: rotating the hidden representation by an orthogonal basis change () leaves Euclidean/RMS geometry invariant, yet entrywise sign is not rotation-equivariant ().
Equalizing entries does not equalize singular subspaces: if is dominated by a rank- outer product , taking elementwise signs yields —still a rank- matrix! Dividing each cell by cannot amplify updates along the dozens of low-singular-value subspaces buried underneath dominant directions.
Substituting the exact gradient matrix hand-computed in Section 2.4 into step of bias-corrected Adam (, , neglecting tiny ) makes this blind spot concrete:
All six cells now have unit magnitude, yet because row 2 has become the exact negative of row 1, the update has collapsed into a rank-1 matrix ()—completely erasing the subtle column-3 feature signal () that distinguished token 2 from token 1. By contrast, the semi-orthogonal polar factor derived next maps the very same to the full-rank matrix (orthogonal rows, ), automatically steering of neuron 2's step along the novel 3rd feature.
#4.2 Algebraic Simplification from Shampoo to Its Stateless Limit
How can we precondition a matrix gradient without losing row-column coupling? Flattening into full-matrix AdaGrad would require an covariance matrix— floats for a single layer, completely intractable.
In 2018, Gupta, Koren, and Singer proposed Shampoo[11], factoring the preconditioner via a Kronecker product into a left row-covariance accumulator and a right column-covariance accumulator , stepping along . Why the exponent rather than AdaGrad's ? Because both and are quadratic in (units ), multiplying on the left by () and on the right by () together cancel one power of , matching AdaGrad's zero-order scaling .
Subsequent experiments revealed a striking empirical fact: turning off cross-step accumulation in Shampoo and evaluating the instantaneous stateless form (where is the Moore-Penrose pseudoinverse) on the current momentum matrix not only avoids degradation, but often converges faster[12]. Let us simplify that expression algebraically.
Let have rank with reduced singular value decomposition (SVD):
where has orthonormal columns (), has positive singular values , and has orthonormal columns (). (Note also the Frobenius identity .) Forming the left and right Gram matrices gives:
Taking the power of the pseudoinverse on the active range space raises each positive diagonal entry of to , i.e., :
Multiplying all three factors and applying , :
Every nonzero singular value —no matter how many orders of magnitude apart—cancels out identically to . When has full rank (which holds almost surely under stochastic gradients), is the nearest semi-orthogonal matrix to ( if , or if ; if , it is a rank- partial isometry).
#4.3 First-Principles Derivation: Steepest Descent Under the Induced Operator Norm
In Old Optimizer, New Norm (2024), Bernstein and Newhouse proved that needs no second-order curvature approximation to justify it: it is the exact first-order steepest-descent step under the natural induced operator norm of hidden linear layers[12]. Here is the complete proof.
Consider a hidden linear map taking to . Recall from Section 2.1 that RMSNorm normalizes hidden token vectors in root-mean-square norm:
Perturbing shifts the layer's output on input by . To keep the maximum output RMS perturbation bounded across arbitrary layer widths , the physically meaningful ruler on is the worst-case output RMS change per unit input RMS—the induced operator norm:
where is the largest singular value (spectral norm) of .
Given the current lookahead momentum matrix with reduced SVD (), steepest descent inside this induced operator-norm ball solves:
By cyclic invariance of the trace:
Since , Cauchy-Schwarz and the definition of bound every term :
Because , summing over yields a tight lower bound on the objective:
When is equality achieved? If and only if holds simultaneously for every active singular direction . Substituting the semi-orthogonal candidate
verifies feasibility () and attains the lower bound identically: (unique whenever ).
That is the geometric core of Muon: a Frobenius ball steps proportionally to raw skewed singular values, an entrywise cube equalizes isolated matrix cells, whereas the operator ball advances all orthogonal feature subspaces at the exact same speed.
Geometric Comparison of Steepest Descent Under Three Matrix Norm Balls
1 · FROBENIUS NORM BALLPreserves singular-value skewStep dominated by top σ₁2 · ENTRYWISE MAX NORMEMA-smoothed form gives AdamWBalances entries, keeps low rank3 · OPERATOR SPECTRAL NORMMaps all singular values to 1Tail subspaces learn at full speed1 · FROBENIUS NORM BALLDominated by top singular dirTail subspaces barely move2 · ENTRYWISE MAX NORMSmoothed form corresponds to AdamWLeaves matrix rank skew intact3 · SPECTRAL NORM (MUON)Exact induced operator-norm stepEvery orthogonal subspace steps by 1
Under the Frobenius ball, updates concentrate along the top singular direction; under the entrywise cube, cell magnitudes equalize without fixing low-rank skew; under the operator spectral norm, all nonzero singular values map to .
#4.4 Deriving the Dual-Optimizer Parameter Routing Rule from Induced Norms
Every production Muon recipe follows a strict parameter split: internal 2D hidden projections (W_q, W_k, W_v, W_o, W_up, W_down) go to Muon, while boundary embeddings (tok_emb, pos_emb), the output lm_head, and 1D RMSNorm gains stay on AdamW[4][5].
Why shouldn't and —which are also 2D matrices—be globally orthogonalized? Checking the induced norms of their own input and output spaces gives the answer directly[12]:
Token embedding table (): as shown in Section 1.1, the input is a one-hot vector naturally measured in norm , while the output enters the residual stream measured in . Because a convex function over the polytope attains its maximum at one of the extreme vertices :
This norm takes an independent maximum over vocabulary rows—vocabulary rows are geometrically decoupled (the exact steepest step normalizes each active row independently rather than orthogonalizing across tokens). Furthermore, a mini-batch activates at most rows while most rows are zero; global orthogonalization would mix frequent and rare token subspaces.
2. Output LM head (): taking a unit-RMS hidden vector to logits , Softmax shifts are controlled by . Its induced norm again decouples row by row across the vocabulary. Routing tok_emb and lm_head to AdamW respects row-wise decoupling while adapting per-token logit scales[4][5].
3. 1D RMSNorm vector : viewed as a matrix, its rank is at most with a single singular value , so no inter-direction skew exists; orthogonalizing it would collapse per-channel gains into a unit vector.
Dual-Optimizer Parameter Routing Dictated by Input-Output Space Norms
Only 2D linear operators mapping continuous hidden RMS spaces to RMS spaces () call for spectral orthogonalization; row-decoupled vocabulary boundaries and 1D gains belong to AdamW.
#5. Odd-Degree Newton-Schulz Iteration and Scalable RMS Alignment
Theory asks for , yet calling exact torch.linalg.svd on hundreds of matrices every training step would stall GPU pipelines: exact SVD relies on sequential bidiagonalization and float32 Givens sweeps that cannot run on half-precision Tensor Cores.
In October 2024, Keller Jordan, Bernstein, and collaborators introduced Muon (MomentUm Orthogonalized by Newton-Schulz)[4], replacing exact SVD with five bfloat16 odd-degree matrix polynomial steps.
#5.1 Why Odd Matrix Polynomials Preserve Left and Right Singular Vectors
Let have reduced SVD . Inspect alternating odd products of and :
(Even powers such as annihilate and change shape to ; only odd products preserve the bilateral basis .)
By linearity, for any odd quintic , setting and iterating pure matrix multiplications
holds and fixed while applying the scalar map independently to every singular value on the diagonal:
Two preprocessing steps precede :
Frobenius pre-normalization into : because diverges rapidly for large , all initial singular values must lie in . Using , setting
guarantees without estimating . Notice also that any positive constant cancels out identically in , which is why Muon's momentum needs neither a factor nor Adam-style cold-start bias correction.
2. Tall-matrix transpose trick (): when rows exceed columns (e.g., with ), forming builds a large Gram matrix costing MACs per step; transposing first into a wide matrix shrinks to , cutting per-step MACs to —from down to at (>90% compute saved). Since , transposing back at the end is bit-exact.
#5.2 Classical Newton-Schulz vs. Muon's Minimax Coefficients
How are chosen? Start with classical Newton-Schulz from numerical linear algebra.
Applying Newton's method directly to gives , which still requires matrix inversion . Applying Newton's tangent update instead to puts in the denominator, flipping negative exponents into pure odd positive powers:
That is the classical cubic . Extending to a quintic with third-order local convergence at the fixed point () solves the linear system:
In neural network training, however, dividing a skewed gradient by pushes many tail singular values down into . Near , and are negligible, so per-step amplification equals the origin slope . Five steps of amplify small singular values by at most —lifting only to .
Jordan et al. observed that under noisy bfloat16 gradients (7 mantissa bits), converging to is pointless; what matters is maximizing the origin slope within a fixed 5-step budget without diverging on . Relaxing so equiripples inside a narrow band around yields Muon's minimax-tuned coefficients[4]:
Checking two numbers confirms the tradeoff:
Small-singular-value amplification: raising the origin slope from to boosts 5-step linear gain to ( stronger than classical), lifting right up to ;
Why : this is not a typo, but the deliberate trough of the equiripple band—every lands inside after 5 compositions (while tiny values in climbing through the peak of reach at most ).
To demystify how pure matrix multiplications can uncover a buried singular direction without ever calling SVD, let us unfold all 5 iterations on a concrete skewed momentum matrix:
At a glance, all four entries sit right around , differing by just between diagonal and anti-diagonal. Taking entrywise signs (the memoryless Adam limit) sees four positive numbers and outputs the rank-1 all-ones matrix (), destroying the anti-diagonal subspace; whereas the exact orthogonal polar factor is the permutation matrix ().
Now run Muon's pre-normalization and quintic recursion () with zero SVD:
Step 0 pre-normalization: , giving with singular values .
Why step 1 separates from : Gram matrix has eigenvalue along the common-mode vector , so the negative cubic term strongly damps the dominant mode down to . Along the differential vector , however, has eigenvalue , so cubic and quintic terms virtually vanish while linear term amplifies the anti-diagonal gap by , yielding ().
Unfolding all five matrix-multiply iterations ():
In five plain matrix multiplications, cancels its diagonal common-mode background down to and extracts the orthogonal swap operator , flattening the singular-value ratio from to .
Unfolded Numeric Walkthrough: Cell-by-Cell Evolution of a 100:1 Skewed Matrix Under SGD, Sign/Adam, and 5-Step Newton-Schulz
1 · SAME 100:1 SKEWED MATRIX UNDER THREE UPDATE RULESInput = [[10,10],[10,10]] (σ₁=20) + [[-0.1,0.1],[0.1,-0.1]] (σ₂=0.2): tiny differential mode buried under +109.910.110.19.9σ = (20.0, 0.2)SGD / Frobenius Norm0.4950.5050.5050.495σ = (1.00, 0.01)Keeps 100:1 skewEntrywise Sign / Adam1.001.001.001.00σ = (2.00, 0.00)Wipes out σ₂ completelyMuon Exact Polar UVᵀ0.001.001.000.00σ = (1.00, 1.00)Both subspaces step = 12 · 5-STEP NEWTON-SCHULZ PURE MATMUL EVOLUTION (ZERO SVD)Watch diagonal common-mode shrink to ~0 while anti-diagonal differential mode amplifies into an orthogonal swap0.4950.5050.5050.495σ:(1.00, 0.01)0.3330.3680.3680.333σ:(0.70, 0.03)0.4980.6160.6160.498σ:(1.11, 0.12)0.1600.5600.5600.160σ:(0.72, 0.40)k=4..5-0.0010.6980.698-0.001σ:(0.70, 0.70)By step 5, diagonal drops to -0.001, anti-diagonal rises to 0.698, flattening singular ratio from 100:1 to 1.003:11 · THREE UPDATE RULES UNFOLDED9.910.110.19.9= 10×ones (dominant)+ 0.1×anti-diag (tail)Entrywise Sign1.001.001.001.00σ = (2.00, 0.00)Erases ±0.1 signalMuon Polar UVᵀ0.001.001.000.00σ = (1.00, 1.00)Restores swap matrix2 · 5-STEP NEWTON-SCHULZ TRACE0.4950.5050.5050.495σ:(1.00, 0.01)0.3330.3680.3680.333σ:(0.70, 0.03)0.1600.5600.5600.160σ:(0.72, 0.40)-0.0010.6980.698-0.001σ:(0.70, 0.70)5 rounds of pure matrix multiplies, zero SVDSingular ratio flattens from 100:1 to 0.699 : 0.697
Input combines dominant with tail . Entrywise sign collapses to a rank-1 all-ones matrix because all 4 entries are positive; 5 Newton-Schulz polynomial steps isolate the hidden orthogonal swap matrix via pure matrix multiplications.
The left panel below plots at ; the right panel measures all 64 singular values of Layer 1's W_q momentum at step 25 of our 2-layer Transformer. Raw momentum spans , and even AdamW's entrywise update still decays by over —whereas 5 Newton-Schulz steps place the top 53 singular values squarely inside .
Newton-Schulz Quintic Composition Curves and Measured Transformer Singular Spectrum
0.00.20.40.60.81.01.2↑ Normalized singular value (log)204060Singular value index i (1 → 64)Top 53 singular values ∈ [0.68, 1.20]Raw momentum decays 13,669×
0.00.20.40.60.81.01.2↑ Normalized singular value (log)204060Singular value index i (1 → 64)Top 53 singular values ∈ [0.68, 1.20]Raw momentum decays 13,669×
Left: composed 1, 3, and 5 times. Right: all 64 singular values of Layer-1 at step 25 of a 2-layer Mini-Transformer (; raw momentum and AdamW updates normalized by to compare spectral shape).
Scaling Muon from small benchmarks to multi-billion-parameter LLM pretraining required solving two hyperparameter-transfer bottlenecks, derived by Moonshot AI (Liu, Su et al., 2025) in Muon is Scalable for LLM Training[5].
First: aligning entrywise update RMS across matrix shapes and with AdamW.
Let have rank with nonzero singular values near . Its squared Frobenius norm equals the sum of squared singular values:
Dividing across all entries gives the per-element root-mean-square update magnitude:
Compare this against earlier aspect-ratio factors: Section 4.3's induced norm gave (entrywise RMS when ), which Keller Jordan clamped to (entrywise RMS ). Under either formula, entrywise update RMS shrinks as whenever model width grows—forcing separate learning-rate sweeps (e.g., lr = 0.02) across widths and across attention, MLP, and MoE layers.
What is the steady-state entrywise update RMS of AdamW? Model coordinate gradients in late training as zero-mean i.i.d. random variables with variance (). For large :
;
Because cross-step terms vanish:
With near concentrating tightly around , the first-order ratio approximation gives the dimensionless AdamW step an entrywise RMS of:
At , (empirically – in real LLM runs with positive local gradient autocorrelation[5]).
Multiplying by cancels the denominator and pins Muon's entrywise update RMS right around across every matrix shape:
With this alignment, Muon and boundary AdamWshare the exact same learning rate schedule and weight decay out of the box.
Without weight decay (), writing , the squared Frobenius norm evolves as:
Under noisy late-stage gradients nearly orthogonal to , the positive quadratic injection accumulates every step without any restoring force, causing to drift upward monotonically until attention logits saturate. Decoupled decay contributes per step; balancing shrinkage against stabilizes weights at the bounded equilibrium [5].
The three controlled ablations below verify each claim: applying Muon to embeddings and the LM head degrades validation loss; omitting weight decay causes to grow linearly; and holds entrywise update RMS steady at – from up to .
2.53.03.54.04.55.0↑ Val Loss200Step →All-Muon rises to 2.91Hybrid 2.62
2.53.03.54.04.55.0↑ Val Loss100200300Step →All-Muon rises to 2.91Hybrid 2.62
Weight Decay · Hidden
2025303540↑ Frobenius norm200Step →No WD grows to 37.6With WD stabilizes at 28.7
2025303540↑ Frobenius norm100200300Step →No WD grows to 37.6With WD stabilizes at 28.7
Cross-Shape Update
0.000.050.100.150.200.25↑ Entrywise RMS642565121k2kLonger matrix side AMoonshot RMS ≈ 0.19
0.000.050.100.150.200.25↑ Entrywise RMS642565121k2kLonger matrix side AMoonshot RMS ≈ 0.19
Left & center: 360 steps on a 2-layer Mini-Transformer. Right: measured entrywise RMS of Gaussian matrices after 5 Newton-Schulz steps across longer dimension ( square, then aspect ratio from to ).
#6. Roofline Arithmetic Intensity and Four-Generation Controlled Benchmark
#6.1 Why Five Extra Matrix Multiplications Barely Move Wall-Clock Step Time
At first glance, running five matrix-multiplication iterations per weight layer sounds far more expensive than AdamW's scalar arithmetic. A quick GPU Roofline calculation—measuring arithmetic intensity in ()—explains why wall-clock overhead is negligible.
For with short side , long side , and float32 master weights/states (4 bytes/entry) in HBM:
Memory-bound fused AdamW: each step reads and writes —roughly bytes of HBM traffic for 12 scalar FLOPs per parameter. Its arithmetic intensity is , hundreds of times below a modern GPU's ridge point ( for H100 bfloat16 Tensor Cores), while holding two full state buffers.
Compute share of Muon's NS5: Muon drops (halving 2D optimizer state memory). After transposing to in bfloat16 (2 bytes/entry), each NS step performs ( FLOPs), ( FLOPs), and ( FLOPs), totaling FLOPs over 5 steps, at high arithmetic intensity (–, or – at ) right in the Tensor Core sweet spot. Meanwhile, on a global token batch , the forward and backward passes execute FLOPs, bounding Muon's relative FLOP overhead by:
In standard LLM pretraining where and , this ratio is just –[4][5]—trading under extra Tensor Core FLOPs for ~48% fewer training tokens to reach the same validation loss in Moonshot AI's scaling-law runs[5].
#6.2 Controlled Benchmark Across Four Optimizer Generations on a 2-Layer Transformer
To observe every mechanism on a transparent task, we construct a synthetic language modeling benchmark combining Zipf-skewed background tokens with in-context associative recall: vocabulary , length , with four random Key → Value pairs planted in the first half of each sequence and one Key queried amidst Zipfian filler in the second half. Answering correctly requires multi-head attention to form an induction circuit aligning query and key subspaces.
We train an identical 2-layer, 4-head Mini-Transformer () for 360 steps under SGD, SGD + Momentum, full-model AdamW, and hybrid Muon + AdamW (with Muon + AdamW and AdamW sharing the exact same and ):
Four Optimizer Generations on a 2-Layer 4-Head Mini-Transformer: Val Loss & Associative Recall
Muon+AdamW hybrid (shared )
Full-model AdamW ()
SGD + Momentum ()
Vanilla SGD ()
Validation Cross-Entropy Loss
2.53.03.54.04.55.0↑ Val Loss0100200300Uniform random ln(128) = 4.85
2.53.03.54.04.55.0↑ Val Loss0100200300Uniform random ln(128) = 4.85
Training step (2-layer 4-head Mini-Transformer, Zipf background + associative recall, mean ±1 SD over 2 seeds)
Vocab , length , , 4 heads, batch ; solid curves show 2-seed means and shaded bands show SD. Uniform random cross-entropy starts at .
The training phases mirror our derivations: within the first 50 steps, all four optimizers fit the unigram frequencies of high-probability Zipfian filler, dropping loss from to ~. Beyond that point, SGD and Momentum remain swamped by dominant filler gradients, leaving the low-singular-value induction-head directions stalled at – recall; AdamW begins aligning subspaces after step 150 to reach by step 360; whereas Muon + AdamW crosses the induction phase transition around step 120 and reaches associative recall (its slight overall validation loss uptick past step 250 reflects mild overfitting on fixed-corpus background tokens while associative recall continues climbing).
#7. Complete Single-File PyTorch Implementation: Mini-Transformer with Muon + AdamW
The self-contained PyTorch script below maps every equation in this post—mixed-precision-safe RMSNorm, multi-head causal self-attention, 5-step Newton-Schulz orthogonalization, Moonshot RMS-aligned Muon, induced-norm parameter routing, and a 1-epoch (50-step) training loop—directly onto runnable code:
importtorchimporttorch.nnasnnimporttorch.nn.functionalasFfromtorch.utils.dataimportTensorDataset,DataLoader# =====================================================================# 1. Quintic Newton-Schulz Iteration & Custom Muon Optimizer# =====================================================================defzeropower_via_newtonschulz5(G:torch.Tensor,steps:int=5,eps:float=1e-7)->torch.Tensor:"""Map G = U * Sigma * V^T to approximate semi-orthogonal U * V^T in 5 matmul steps."""assertG.ndim==2,"Newton-Schulz orthogonalization applies only to 2D matrix parameters"a,b,c=(3.4445,-4.7750,2.0315)X=G.bfloat16()ifG.is_cudaelseG.float()# Pre-normalize by Frobenius norm so all initial singular values lie in [0, 1]X=X/(X.norm()+eps)# Transpose tall matrices (A > B) so A_k = X @ X.T has smaller shape B x Btransposed=FalseifX.size(0)>X.size(1):X=X.Ttransposed=True# Odd matrix polynomial recurrence: X_{k+1} = a * X_k + (b * A_k + c * A_k^2) * X_kfor_inrange(steps):A=X@X.TB=b*A+c*(A@A)X=a*X+B@Xiftransposed:X=X.TreturnX.to(G.dtype)classMuon(torch.optim.Optimizer):"""Muon optimizer for internal 2D Transformer matrices (with decoupled WD & RMS scaling)."""def__init__(self,params,lr=3e-3,momentum=0.95,weight_decay=0.01,scale_mode="moonshot"):defaults=dict(lr=lr,momentum=momentum,weight_decay=weight_decay,scale_mode=scale_mode)super().__init__(params,defaults)@torch.no_grad()defstep(self,closure=None):loss=NoneifclosureisnotNone:withtorch.enable_grad():loss=closure()forgroupinself.param_groups:lr=group["lr"]mu=group["momentum"]wd=group["weight_decay"]scale_mode=group["scale_mode"]forWingroup["params"]:ifW.gradisNone:continueG=W.grad# 2D gradient matrix of shape (d_out, d_in) matching W# Only first-moment momentum M is stored; no second-moment buffer V is neededstate=self.state[W]if"momentum_buffer"notinstate:state["momentum_buffer"]=torch.zeros_like(G)M=state["momentum_buffer"]# 1. Nesterov lookahead momentum: M_t = mu * M_{t-1} + G_t, tilde_M = G_t + mu * M_tM.mul_(mu).add_(G)tilde_M=G+mu*M# 2. 5-step Newton-Schulz orthogonalizationO_t=zeropower_via_newtonschulz5(tilde_M,steps=5)# 3. Decoupled weight decay: W <- (1 - lr * wd) * Wifwd!=0:W.mul_(1.0-lr*wd)# 4. Entrywise update RMS alignment (moonshot mode shares AdamW's lr directly)A,B=W.size(0),W.size(1)scale=0.2*(max(A,B)**0.5)ifscale_mode=="moonshot"elsemax(1.0,A/B)**0.5W.add_(O_t,alpha=-lr*scale)returnloss# =====================================================================# 2. Mini-Transformer Language Model Definition# =====================================================================classRMSNorm(nn.Module):def__init__(self,dim:int,eps:float=1e-6):super().__init__()self.weight=nn.Parameter(torch.ones(dim))# 1D gain (dim,) -> AdamW (wd=0)self.eps=epsdefforward(self,x:torch.Tensor)->torch.Tensor:x_fp32=x.float()rms=torch.rsqrt(x_fp32.pow(2).mean(-1,keepdim=True)+self.eps)return(x_fp32*rms).to(x.dtype)*self.weightclassMiniTransformerLM(nn.Module):def__init__(self,vocab_size=1000,d_model=64,n_heads=4,max_len=32):super().__init__()assertd_model%n_heads==0self.d_model=d_modelself.n_heads=n_headsself.head_dim=d_model//n_heads# Boundary discrete lookup tables -> AdamWself.tok_emb=nn.Embedding(vocab_size,d_model)self.pos_emb=nn.Embedding(max_len,d_model)# Internal 2D attention projections (.weight shape (64, 64)) -> Muonself.norm1=RMSNorm(d_model)self.W_q=nn.Linear(d_model,d_model,bias=False)self.W_k=nn.Linear(d_model,d_model,bias=False)self.W_v=nn.Linear(d_model,d_model,bias=False)self.W_o=nn.Linear(d_model,d_model,bias=False)# Internal 2D FFN layers (W_up: (256, 64), W_down: (64, 256)) -> Muonself.norm2=RMSNorm(d_model)self.W_up=nn.Linear(d_model,4*d_model,bias=False)self.W_down=nn.Linear(4*d_model,d_model,bias=False)# Output vocabulary head (1000, 64) -> AdamWself.norm_final=RMSNorm(d_model)self.lm_head=nn.Linear(d_model,vocab_size,bias=False)defforward(self,idx:torch.Tensor)->torch.Tensor:B,T=idx.shapepos=torch.arange(0,T,device=idx.device)# (B, T, D) + (T, D) [broadcast across batch] -> (B, T, D)x=self.tok_emb(idx)+self.pos_emb(pos)# Sublayer 1: Pre-RMSNorm + Multi-Head Causal Self-Attentionh=self.norm1(x)q=self.W_q(h).view(B,T,self.n_heads,self.head_dim).transpose(1,2)k=self.W_k(h).view(B,T,self.n_heads,self.head_dim).transpose(1,2)v=self.W_v(h).view(B,T,self.n_heads,self.head_dim).transpose(1,2)attn_out=F.scaled_dot_product_attention(q,k,v,is_causal=True)attn_out=attn_out.transpose(1,2).contiguous().view(B,T,self.d_model)x=x+self.W_o(attn_out)# Sublayer 2: Pre-RMSNorm + SiLU Feed-Forward Networkh=self.norm2(x)x=x+self.W_down(F.silu(self.W_up(h)))returnself.lm_head(self.norm_final(x))# =====================================================================# 3. Parameter Routing & 1-Epoch (50 Steps) Training Loop# =====================================================================if__name__=="__main__":torch.manual_seed(42)device="cuda"iftorch.cuda.is_available()else"cpu"model=MiniTransformerLM(vocab_size=1000,d_model=64,n_heads=4,max_len=32).to(device)muon_params,adamw_decay,adamw_nodecay=[],[],[]forname,pinmodel.named_parameters():is_embed_or_head=("emb"inname)or("lm_head"inname)ifp.ndim==2andnotis_embed_or_head:muon_params.append(p)elifp.ndim>=2:adamw_decay.append(p)else:adamw_nodecay.append(p)shared_lr=3e-3opt_muon=Muon(muon_params,lr=shared_lr,momentum=0.95,weight_decay=0.01,scale_mode="moonshot")opt_adamw=torch.optim.AdamW([{"params":adamw_decay,"weight_decay":0.01},{"params":adamw_nodecay,"weight_decay":0.0},],lr=shared_lr,betas=(0.9,0.95))# 1,000 modulo-1000 counting sequences, batch_size=20 -> 1 Epoch = 50 Stepsseq_len=16starts=torch.randint(0,1000,(1000,1))sequences=(starts+torch.arange(seq_len+1))%1000dataloader=DataLoader(TensorDataset(sequences[:,:-1],sequences[:,1:]),batch_size=20,shuffle=True,)model.train()forstep,(x_batch,y_batch)inenumerate(dataloader,start=1):x_batch,y_batch=x_batch.to(device),y_batch.to(device)logits=model(x_batch)# 1. Forward passloss=F.cross_entropy(logits.reshape(-1,1000),y_batch.reshape(-1))# 2. Cross-entropy lossopt_muon.zero_grad();opt_adamw.zero_grad()# 3. Clear stale gradsloss.backward()# 4. Backward contractionopt_muon.step();opt_adamw.step()# 5. Dual-optimizer stepifstep==1orstep%10==0:print(f"Epoch 1 | Step [{step:2d}/50] | Loss: {loss.item():.4f}")
python
Running this script drops cross-entropy smoothly from near the uniform random baseline :
Stepping back across all seven sections, the progression from scalar gradient descent to modern hybrid LLM optimizers revolves around three successive questions: how to smooth gradient noise and curvature oscillation with history, how to decouple weight shrinkage from adaptive preconditioning, and how to match each parameter's update norm to the geometry of its input and output spaces:
Summary of Five Optimizer Generations: Update Signals, Implicit Norms, and Benchmark Recall
Optimizer
Update Signal & Transform
Weight Decay
Implicit Norm Ball
Recall
SGD (+L2)
(scalar step)
Coupled
7.3%
Momentum
(heavy-ball EMA)
Coupled
+ inertia
7.4%
Adam (+L2)
Distorted by
—
AdamW
Decoupled
23.7%
Muon+AdamW
via 5-step NS5
Decoupled
77.0%
Recall comes from the Section 6 2-layer 4-head Mini-Transformer associative recall benchmark at step 360 (Adam+L2 is omitted from that run since its decay distortion is isolated in Section 3.4).
Keeping this single thread in mind—from the four tensor lifetimes in VRAM, to the rank-one outer-product sum that skews singular spectra, to the induced-norm split between Muon and AdamW—turns every matrix transpose, bfloat16 cast, and RMS scaling factor in modded-nanogpt, Moonlight, and modern pretraining frameworks into a direct consequence of linear algebra.
↑123 Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30 (NeurIPS 2017).
↑12345678 Liu, J., Su, J., Yao, X., Jiang, Z., Lai, G., Du, Y., Qin, Y., Xu, W., Lu, E., Yan, J., et al. (2025). Muon is Scalable for LLM Training. arXiv preprint arXiv:2502.16982.