Contents

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.

Five Core Questions and Roadmap

Specifically, we work through five connected questions in order:

  1. 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?
  2. 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?
  3. 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?
  4. 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?
  5. 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 (SGD Momentum Adam AdamW, Section 3) followed by two-dimensional spectral optimizers (Shampoo Muon 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

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.

1.3 The Four Tensor Families in GPU Memory

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

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

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 & SymbolFamilyMini ShapeTypical 7B ShapeInferenceTraining
Inputs & targets Token IDsPrefix onlyShifted by 1 token
Token emb 1. ParameterRead-only lookupAdamW step
Pos emb 1. ParameterParameter-free RoPEBroadcast addAdamW step
Attention 1. ParameterFour Read-only GEMMMuon orthogonal step
FFN 1. ParameterRead-only GEMMMuon orthogonal step
Norm gain 1. Parameter 1D 1DChannel scaleAdamW (wd=0)
LM head 1. ParameterLast-row logitsAdamW step
Residual & norm 2. ActivationFreed per layerCached for backward
Multi-head 2. ActivationFreed per layerCached for backward
Attention 2. ActivationFreed per layerCached or recomputed
Logit tensor 2. ActivationLast row onlyFull-seq CE loss
Cache 3. KV Cache+1 row per stepNot allocated
Weight grad 4. Train StateSame as paramSame as paramNot allocatedWritten in backward
Opt states 4. Train StateSame as paramSame as paramNot allocatedResident (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 .

  1. 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.
  2. 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

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
  • Without KV Cache (recompute full prefix )
  • With KV Cache (new token only )
  • 98.4% redundant compute avoided

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:

  1. 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.
  2. 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.

Full-Flow LLM Training Matrix Shapes: Tracking Cached Activations, Transpose Contraction & Dual Optimizers

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:

  1. 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 .
  2. 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).
  3. 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.
  4. 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:

  1. Left branch (propagating error to earlier layer input ): multiply by (untransposed), contracting out to recover a activation gradient matching :
  1. 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.

Unfolded Numeric Walkthrough: 2-Token Cross-Entropy Gradient and Rank-One Outer-Product Weight Gradient

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

Consider the simplest 2D anisotropic quadratic loss—a narrow canyon whose Hessian eigenvalues differ sharply:

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:

  1. Necessary and sufficient condition: isotropic regularization equals weight decay if and only if is a scalar multiple of the identity (SGD).
  2. 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
  • SGD / Adam+ high-grad
  • Momentum / Adam+ low-grad
  • AdamW (per-axis adaptation & isotropic decay)

Ill-Conditioned Quadratic ·

Decoupled Weight Decay · High-Grad vs Low-Grad

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:

  1. Basis dependence: rotating the hidden representation by an orthogonal basis change () leaves Euclidean/RMS geometry invariant, yet entrywise sign is not rotation-equivariant ().
  2. 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

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]:

  1. 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 :

  1. 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:

  1. Step 0 pre-normalization: , giving with singular values .
  2. 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 ().
  3. 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

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
  • Muon 5-step / spectrum
  • 1-step map / AdamW update spectrum
  • Raw momentum spectrum (13,669× ratio)
  • target band

Quintic Polynomial Map · for

Measured Layer-1 Singular Spectrum (Step 25, 64 dims)

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).

5.3 Moonshot AI's Scaling Improvements: Update RMS Alignment and Decoupled Weight Decay

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 AdamW share the exact same learning rate schedule and weight decay out of the box.

Second: why long-horizon pretraining requires decoupled weight decay.

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 .

Controlled Ablations: Parameter Routing, Decoupled Weight Decay, and Cross-Shape RMS Alignment
  • Hybrid routing / With WD / aligned
  • Ablation: All-Muon / No WD / Unscaled
  • Clamped aspect scale

Routing Ablation · Val Loss

Weight Decay · Hidden

Cross-Shape Update

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:

  1. 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.
  2. 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

Associative Recall Accuracy (%)

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:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader


# =====================================================================
# 1. Quintic Newton-Schulz Iteration & Custom Muon Optimizer
# =====================================================================
def zeropower_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."""
    assert G.ndim == 2, "Newton-Schulz orthogonalization applies only to 2D matrix parameters"
    a, b, c = (3.4445, -4.7750, 2.0315)
    X = G.bfloat16() if G.is_cuda else G.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 B
    transposed = False
    if X.size(0) > X.size(1):
        X = X.T
        transposed = True

    # Odd matrix polynomial recurrence: X_{k+1} = a * X_k + (b * A_k + c * A_k^2) * X_k
    for _ in range(steps):
        A = X @ X.T
        B = b * A + c * (A @ A)
        X = a * X + B @ X

    if transposed:
        X = X.T
    return X.to(G.dtype)


class Muon(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()
    def step(self, closure=None):
        loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()
        for group in self.param_groups:
            lr = group["lr"]
            mu = group["momentum"]
            wd = group["weight_decay"]
            scale_mode = group["scale_mode"]

            for W in group["params"]:
                if W.grad is None:
                    continue
                G = 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 needed
                state = self.state[W]
                if "momentum_buffer" not in state:
                    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_t
                M.mul_(mu).add_(G)
                tilde_M = G + mu * M

                # 2. 5-step Newton-Schulz orthogonalization
                O_t = zeropower_via_newtonschulz5(tilde_M, steps=5)

                # 3. Decoupled weight decay: W <- (1 - lr * wd) * W
                if wd != 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) if scale_mode == "moonshot" else max(1.0, A / B) ** 0.5
                W.add_(O_t, alpha=-lr * scale)
        return loss


# =====================================================================
# 2. Mini-Transformer Language Model Definition
# =====================================================================
class RMSNorm(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 = eps

    def forward(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.weight


class MiniTransformerLM(nn.Module):
    def __init__(self, vocab_size=1000, d_model=64, n_heads=4, max_len=32):
        super().__init__()
        assert d_model % n_heads == 0
        self.d_model = d_model
        self.n_heads = n_heads
        self.head_dim = d_model // n_heads

        # Boundary discrete lookup tables -> AdamW
        self.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)) -> Muon
        self.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)) -> Muon
        self.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) -> AdamW
        self.norm_final = RMSNorm(d_model)
        self.lm_head = nn.Linear(d_model, vocab_size, bias=False)

    def forward(self, idx: torch.Tensor) -> torch.Tensor:
        B, T = idx.shape
        pos = 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-Attention
        h = 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 Network
        h = self.norm2(x)
        x = x + self.W_down(F.silu(self.W_up(h)))

        return self.lm_head(self.norm_final(x))


# =====================================================================
# 3. Parameter Routing & 1-Epoch (50 Steps) Training Loop
# =====================================================================
if __name__ == "__main__":
    torch.manual_seed(42)
    device = "cuda" if torch.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 = [], [], []
    for name, p in model.named_parameters():
        is_embed_or_head = ("emb" in name) or ("lm_head" in name)
        if p.ndim == 2 and not is_embed_or_head:
            muon_params.append(p)
        elif p.ndim >= 2:
            adamw_decay.append(p)
        else:
            adamw_nodecay.append(p)

    shared_lr = 3e-3
    opt_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 Steps
    seq_len = 16
    starts = torch.randint(0, 1000, (1000, 1))
    sequences = (starts + torch.arange(seq_len + 1)) % 1000
    dataloader = DataLoader(
        TensorDataset(sequences[:, :-1], sequences[:, 1:]),
        batch_size=20,
        shuffle=True,
    )

    model.train()
    for step, (x_batch, y_batch) in enumerate(dataloader, start=1):
        x_batch, y_batch = x_batch.to(device), y_batch.to(device)

        logits = model(x_batch)                                                # 1. Forward pass
        loss = F.cross_entropy(logits.reshape(-1, 1000), y_batch.reshape(-1))  # 2. Cross-entropy loss
        opt_muon.zero_grad(); opt_adamw.zero_grad()                            # 3. Clear stale grads
        loss.backward()                                                        # 4. Backward contraction
        opt_muon.step(); opt_adamw.step()                                      # 5. Dual-optimizer step

        if step == 1 or step % 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 :

Epoch 1 | Step [ 1/50] | Loss: 7.1004
Epoch 1 | Step [10/50] | Loss: 6.7182
Epoch 1 | Step [20/50] | Loss: 6.2750
Epoch 1 | Step [30/50] | Loss: 5.7630
Epoch 1 | Step [40/50] | Loss: 5.0782
Epoch 1 | Step [50/50] | Loss: 4.5468

Summary: Modern Optimizer Evolution at a Glance

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
OptimizerUpdate Signal & TransformWeight DecayImplicit Norm BallRecall
SGD (+L2) (scalar step)Coupled 7.3%
Momentum (heavy-ball EMA)Coupled + inertia7.4%
Adam (+L2)Distorted by —
AdamWDecoupled 23.7%
Muon+AdamW via 5-step NS5Decoupled 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.

References

  1. 1 2 3 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).
  2. 1 2 Robbins, H., & Monro, S. (1951). A Stochastic Approximation Method. The Annals of Mathematical Statistics, 22(3), 400–407.
  3. 1 2 Loshchilov, I., & Hutter, F. (2019). Decoupled Weight Decay Regularization. International Conference on Learning Representations (ICLR 2019).
  4. 1 2 3 4 5 6 Jordan, K., Jin, Y., Boza, V., You, J., Cesista, F., Newhouse, L., & Bernstein, J. (2024). Muon: An Optimizer for Hidden Layers in Neural Networks. Keller Jordan blog.
  5. 1 2 3 4 5 6 7 8 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.
  6. 1 2 3 Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization. Advances in Neural Information Processing Systems 32 (NeurIPS 2019).
  7. ↑ Polyak, B. T. (1964). Some Methods of Speeding Up the Convergence of Iteration Methods. USSR Computational Mathematics and Mathematical Physics, 4(5), 1–17.
  8. ↑ Nesterov, Y. (1983). A Method for Solving the Convex Programming Problem with Convergence Rate . Doklady AN SSSR, 269, 543–547.
  9. ↑ Duchi, J., Hazan, E., & Singer, Y. (2011). Adaptive Subgradient Methods for Online Learning and Stochastic Optimization. Journal of Machine Learning Research, 12, 2121–2159.
  10. 1 2 Kingma, D. P., & Ba, J. (2015). Adam: A Method for Stochastic Optimization. International Conference on Learning Representations (ICLR 2015).
  11. ↑ Gupta, V., Koren, T., & Singer, Y. (2018). Shampoo: Preconditioned Stochastic Tensor Optimization. Proceedings of the 35th International Conference on Machine Learning (ICML 2018), 1842–1850.
  12. 1 2 3 4 Bernstein, J., & Newhouse, L. (2024). Old Optimizer, New Norm: An Anthology. arXiv preprint arXiv:2409.20325.