<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://tianshu-michael-yu.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://tianshu-michael-yu.github.io/" rel="alternate" type="text/html" /><updated>2026-06-09T02:21:56+00:00</updated><id>https://tianshu-michael-yu.github.io/feed.xml</id><title type="html">Tianshu’s Homepage</title><subtitle>Thoughts on AI, systems, and life</subtitle><author><name>Tianshu Yu</name></author><entry><title type="html">Muon: Steepest Descent on Matrices, and Does It Kill Neurons?</title><link href="https://tianshu-michael-yu.github.io/machine-learning/optimization/2026/06/01/muon-optimizer.html" rel="alternate" type="text/html" title="Muon: Steepest Descent on Matrices, and Does It Kill Neurons?" /><published>2026-06-01T00:00:00+00:00</published><updated>2026-06-01T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/machine-learning/optimization/2026/06/01/muon-optimizer</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/machine-learning/optimization/2026/06/01/muon-optimizer.html"><![CDATA[<p><em>Muon has quietly climbed to the top of the nanoGPT speedrun leaderboard and is now used in frontier-scale training runs. This post explains the mathematics that makes it tick, surveys the recent claim that it causes neuron death in MLP layers, and then presents my own small-scale encoder experiment that complicates that narrative.</em></p>

<hr />

<h2 id="why-not-adam">Why Not Adam?</h2>

<p>Adam is the default optimizer for almost everything. Its core idea is simple: maintain a per-parameter exponential moving average of squared gradients, and use it to rescale each coordinate before the update. Concretely, for a scalar parameter $w$ with gradient $g$:</p>

\[w \leftarrow w - \eta \frac{g}{\sqrt{v} + \epsilon}, \quad v \leftarrow \beta_2 v + (1 - \beta_2) g^2.\]

<p>This gives each coordinate an <em>adaptive learning rate</em> proportional to the inverse of its historical gradient RMS. The update direction is therefore $-\text{sign}(g)$ in the limit, which is steepest descent under the $L^\infty$ norm per-coordinate.</p>

<p>This works well when parameters are semantically independent scalars — biases, embedding tables, scalar gates. But most of the parameters in a transformer are <em>weight matrices</em>: the attention projections $W_Q, W_K, W_V, W_O$ and the MLP projections $W_\text{gate}, W_\text{up}, W_\text{down}$. A weight matrix $W \in \mathbb{R}^{m \times n}$ acts on <em>vectors</em>, and its natural “size” is not the sum of its entry magnitudes but rather its effect on vector norms. Adam treats each entry of $W$ independently, completely ignoring this matrix structure.</p>

<p>The question Muon answers is: <em>what is the steepest descent direction for a matrix parameter when we use a norm that respects its matrix nature?</em></p>

<hr />

<h2 id="three-characteristics-of-a-well-behaved-model">Three Characteristics of a Well-Behaved Model</h2>

<p>Before asking what the ideal update looks like, it helps to ask what it means for a model to be <em>well-behaved</em> throughout training. Su Jianlin’s framework (<a href="https://www.spaces.ac.cn/archives/11340">苏剑林, 2025</a>) identifies three stability properties for a linear layer $W \in \mathbb{R}^{m \times n}$:</p>

<p><strong>1. Forward stability.</strong> The output scale should match the input scale. For any input $x$:</p>

\[\|Wx\|_2 \leq \|W\|_2 \cdot \|x\|_2,\]

<p>so bounding $|W|_2 = O(1)$ ensures activations don’t blow up through depth. The tightest such bound is exactly the spectral norm, achieved when $x$ is the top right singular vector of $W$.</p>

<p><strong>2. Backward stability.</strong> Gradients $\delta$ propagate backwards through $W^\top$:</p>

\[\|W^\top \delta\|_2 \leq \|W^\top\|_2 \cdot \|\delta\|_2 = \|W\|_2 \cdot \|\delta\|_2.\]

<p>Since $|W^\top|_2 = |W|_2$, forward and backward stability are controlled by the same spectral norm. A model that is forward-stable is automatically backward-stable.</p>

<p><strong>3. Increment stability.</strong> When $W$ is updated to $W + \Delta W$, the change in output for any input $x$ is:</p>

\[\|(W + \Delta W)x - Wx\|_2 = \|\Delta W \, x\|_2 \leq \|\Delta W\|_2 \cdot \|x\|_2.\]

<p>For each training step to make a comparably-sized functional change across all layers — regardless of model width or gradient magnitude — we need $|\Delta W|_2 = O(\eta)$ uniformly.</p>

<p>The <strong>spectral condition</strong> unifies all three: $|W|_2 = O(1)$ at initialization (properties 1 &amp; 2), and $|\Delta W|_2 = O(\eta)$ at each step (property 3). Muon enforces the increment condition exactly — the polar factor $\operatorname{polar}(G)$ satisfies $|\operatorname{polar}(G)|_2 = 1$, so every step produces a worst-case functional shift of exactly $\eta$, independent of layer width or gradient scale. Weight decay handles the parameter condition, keeping $|W|_2 \leq 1/\lambda$ throughout training. Together they maintain all three stability properties.</p>

<hr />

<h2 id="steepest-descent-under-the-spectral-norm">Steepest Descent Under the Spectral Norm</h2>

<h3 id="what-should-we-measure-parameter-change-or-activation-change">What should we measure: parameter change or activation change?</h3>

<p>When we apply an update $\Delta W$ to a weight matrix $W \in \mathbb{R}^{m \times n}$, the downstream effect on an activation $h = Wx$ is:</p>

\[\Delta h = \Delta W \, x.\]

<p>The Frobenius norm $|\Delta W|_F$ measures the total magnitude of parameter change across all entries — a purely parameter-space notion. But from the perspective of what the network <em>does</em>, what matters is how much the activations shift for a given input. The worst-case activation shift over all unit-norm inputs is exactly the <strong>spectral norm</strong>:</p>

\[\max_{\|x\|=1} \|\Delta W \, x\| = \|\Delta W\|_2.\]

<p>This is the fundamental asymmetry between Frobenius and spectral norm: Frobenius counts parameter-space movement, spectral norm bounds functional change. If we want a fair “budget” for how much a single update step is allowed to disturb the network’s function, the spectral norm is the right measure. Constraining $|\Delta W|_2 \leq \eta$ means that <em>no unit-norm input vector can have its activation shifted by more than $\eta$</em>, regardless of which direction you probe.</p>

<p>Frobenius norm by contrast has no such guarantee — a large Frobenius update can spread its mass across many nearly-redundant directions and barely affect any output, while a small but focused Frobenius update can shift activations dramatically.</p>

<h3 id="the-optimization-problem">The Optimization Problem</h3>

<p>This motivates framing one step of optimization as: find the direction $U$ that most decreases the loss while keeping the worst-case activation shift bounded:</p>

\[U^* = \arg\max_{U} \, \text{Tr}(G^\top U) \quad \text{subject to} \quad \|U\|_2 \leq 1,\]

<p>where $G = \nabla_W \mathcal{L}$. This is steepest descent in spectral norm.</p>

<p><strong>Why $\text{Tr}(G^\top U)$?</strong> The gradient $G = \nabla_W \mathcal{L}$ is the matrix of partial derivatives, with $G_{ij} = \partial \mathcal{L}/\partial W_{ij}$. When the weight matrix shifts by a small amount $\delta W$, the first-order change in loss is the sum of each partial derivative times its corresponding weight change:</p>

\[\delta \mathcal{L} = \sum_{i,j} \frac{\partial \mathcal{L}}{\partial W_{ij}} \delta W_{ij} = \sum_{i,j} G_{ij} \, \delta W_{ij}.\]

<p>This entry-wise sum is the <strong>Frobenius inner product</strong> $\langle G, \delta W \rangle_F$. To see why this equals a trace, expand:</p>

\[\text{Tr}(G^\top \delta W) = \sum_i (G^\top \delta W)_{ii} = \sum_i \sum_j G^\top_{ij} \, \delta W_{ji} = \sum_{i,j} G_{ji} \, \delta W_{ji} = \sum_{i,j} G_{ij} \, \delta W_{ij}.\]

<p>So $\delta \mathcal{L} = \text{Tr}(G^\top \delta W)$ — the loss change is just the “dot product” of $G$ and $\delta W$ when both are treated as flat vectors. The first-order Taylor expansion for a step $\delta W = -\eta U$ is therefore:</p>

\[\mathcal{L}(W - \eta U) \approx \mathcal{L}(W) - \eta \, \text{Tr}(G^\top U).\]

<p>So $\text{Tr}(G^\top U)$ measures how much the loss decreases per unit of $U$ in the gradient’s direction. Maximizing it over $|U|_2 \leq 1$ asks: <em>among all matrix updates with spectral norm at most 1, which one points most in the gradient’s direction?</em></p>

<p>Crucially, the <strong>constraint</strong> is spectral ($|U|<em>2 \leq 1$) while the <strong>objective</strong> uses the Frobenius inner product. These are different norms doing different jobs: the Frobenius inner product measures alignment with the gradient; the spectral norm constraint controls functional impact on activations. By norm duality — the dual of the spectral norm is the nuclear norm — the maximum value of $\text{Tr}(G^\top U)$ over the spectral-norm ball is $|G|</em>*$ (the nuclear norm of $G$), and the maximizer is the polar factor $U_G V_G^\top$.</p>

<p><strong>The solution is the polar factor.</strong> Write $G = U_G \Sigma_G V_G^\top$ (thin SVD). Then:</p>

\[\text{Tr}(G^\top U) = \text{Tr}(V_G \Sigma_G U_G^\top U).\]

<p>Since $|U|_2 \leq 1$, every singular value of $U$ is at most 1. The trace inner product is maximized when we set every singular value of $U$ to 1 and align its singular vectors with those of $G$ — giving:</p>

\[U^* = \operatorname{polar}(G) = U_G V_G^\top.\]

<p>This is the semi-orthogonal matrix closest to $G$ in Frobenius norm, with <strong>spectral norm exactly 1</strong>. The unit spectral norm is not just a convenience: it means every step moves the network’s function by the same worst-case amount, making the learning rate $\eta$ a true, interpretable bound on per-step activation shift.</p>

<p>Intuitively, $\operatorname{polar}(G)$ strips the singular values from $G$ — the “how much each direction matters” — and keeps only $U_G V_G^\top$ — the “which directions to move.” All singular directions of the gradient are updated equally, rather than letting the largest singular value dominate (as it would under a plain gradient step).</p>

<p>Su Jianlin’s blog post <a href="https://www.spaces.ac.cn/archives/11647">苏剑林, 2024</a> gives a complementary derivation of this from the perspective of operator norms, showing that polar decomposition is the unique solution and connecting it to why spectral-norm-constrained descent outperforms Frobenius-norm descent (Adam) on matrix parameters.</p>

<hr />

<h2 id="muon-variants-the-schatten-norm-family">Muon Variants: The Schatten Norm Family</h2>

<p>The spectral, Frobenius, and nuclear norms are all special cases of the <strong>Schatten $p$-norm</strong>:</p>

\[\|A\|_p = \left(\sum_i \sigma_i(A)^p\right)^{1/p},\]

<p>with $p=\infty$ giving the spectral norm $\sigma_{\max}$, $p=2$ giving the Frobenius norm $\sqrt{\sum \sigma_i^2}$, and $p=1$ giving the nuclear norm $\sum \sigma_i$. The key duality: the dual norm of $|\cdot|_p$ is $|\cdot|_q$ for $1/p + 1/q = 1$, so spectral and nuclear are duals of each other, and Frobenius is self-dual.</p>

<p>Since steepest descent under $|\cdot|$ maximizes $\text{Tr}(G^\top U)$ over $|U| \leq 1$, and the maximizer is the dual-norm ball’s exposure in direction $G$, we get a distinct optimizer for each norm:</p>

<table>
  <thead>
    <tr>
      <th>Budget constraint</th>
      <th>Update $U^*$</th>
      <th>Frobenius norm of $U^*$</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>$|U|_2 \leq 1$ (spectral)</td>
      <td>$U_G V_G^\top$ — all $\sigma_i = 1$</td>
      <td>$\sqrt{\min(m,n)}$</td>
      <td><strong>Muon</strong></td>
    </tr>
    <tr>
      <td>$|U|_F \leq 1$ (Frobenius)</td>
      <td>$G / |G|_F$ — normalized gradient</td>
      <td>$1$</td>
      <td>Normalized SGD</td>
    </tr>
    <tr>
      <td>$|U|_* \leq 1$ (nuclear)</td>
      <td>$u_1 v_1^\top$ — top singular pair only</td>
      <td>$1$</td>
      <td>Rank-1 power step</td>
    </tr>
  </tbody>
</table>

<p>The differences become sharp when you look at <strong>how each update treats the singular value spectrum of the gradient</strong>:</p>

<ul>
  <li>
    <p><strong>Frobenius</strong> renormalizes the whole gradient to unit length. It keeps the relative sizes of all singular values intact — directions with large $\sigma_i$ get large updates, small-$\sigma_i$ directions get starved. This is just rescaled gradient descent; it does nothing to equalize learning across the weight matrix’s singular directions.</p>
  </li>
  <li>
    <p><strong>Spectral (Muon)</strong> sets <em>every</em> singular value of the update to 1. The polar factor $U_G V_G^\top$ discards the singular values entirely, giving equal update energy to every singular direction of the gradient. This is the equalizing property: no direction is privileged just because it happened to accumulate a large gradient.</p>
  </li>
  <li>
    <p><strong>Nuclear</strong> takes only the top singular pair $u_1 v_1^\top$ — a rank-1 step in the direction of greatest gradient. This concentrates all the update mass on the single most important direction and ignores the rest. It is the most “focused” option but also the most aggressive in ignoring lower-ranked gradient directions.</p>
  </li>
</ul>

<h3 id="the-frobenius-norm-as-the-wrong-penalty-for-matrices">The Frobenius Norm as the Wrong Penalty for Matrices</h3>

<p>The reason Frobenius is the “wrong” choice for matrix parameters connects back to the activation-change argument. Suppose you normalize the gradient to $|G|_F = 1$. The Frobenius norm spreads its mass across all $mn$ entries — but the functional effect on activations is dominated by the large singular values. A gradient with $\sigma_1 \gg \sigma_2, \ldots$ and $|G|_F = 1$ will drive $|Gx|$ almost entirely via $\sigma_1$; the remaining directions receive tiny updates. Over many steps, the weight matrix’s lower singular directions learn much more slowly, effectively wasting capacity.</p>

<p>Spectral-norm budgeting avoids this: by forcing all singular values of the update to 1, every singular direction of the gradient gets equal learning opportunity regardless of the raw gradient magnitude in that direction. This is why the polar factor has Frobenius norm $\sqrt{\min(m,n)}$ rather than 1 — the extra mass comes from the equalization, not from aggressive scaling.</p>

<p>More precisely: if the gradient spectrum is well-distributed (all $\sigma_i \approx \sigma$), then $|G|_F \approx \sigma \sqrt{\min(m,n)}$ and $G/|G|_F \approx U_G V_G^\top / \sqrt{\min(m,n)}$, so Frobenius-normalized SGD approximates a scaled Muon. The gap widens as the gradient becomes rank-deficient or ill-conditioned — exactly the regime common in deep network training.</p>

<h3 id="how-muon-controls-the-spectral-norm">How Muon Controls the Spectral Norm</h3>

<p>The polar factor $O_t = \operatorname{polar}(M_t)$ always has <strong>spectral norm exactly 1</strong>: all its singular values are forced to 1 by construction. Each Muon step therefore adds a unit-spectral-norm matrix to $W$. Without weight decay, this would let $|W|_2$ grow without bound — every step pushes the weight matrix by a fixed-magnitude operator, so the spectral norm grows at rate $\sim \eta$ per step with no ceiling.</p>

<p>Weight decay is what provides the ceiling. The update rule is:</p>

\[W_{t+1} = W_t + \eta(O_t - \lambda W_t) = (1 - \eta\lambda)W_t + \eta O_t.\]

<p>Because $|O_t|<em>2 \leq 1$, whenever $|\lambda W_t|_2 &gt; 1$ (i.e., $|W_t|_2 &gt; 1/\lambda$), the weight decay term $-\eta\lambda W_t$ is larger in operator norm than the update $\eta O_t$, so $|W</em>{t+1}|<em>2 &lt; |W_t|_2$ — the spectral norm shrinks back. More precisely (Chen et al., <a href="https://arxiv.org/abs/2506.15054">2025</a>, Proposition 1): for any update $X</em>{t+1} = X_t + \eta_t(O_t - \lambda X_t)$ with $|O_t|_2 \leq 1$ and $\eta_t \lambda \leq 1$,</p>

\[\|X_t\|_2 - \frac{1}{\lambda} \leq \prod_{s=0}^{t-1}(1 - \eta_s\lambda)\!\left(\|X_0\|_2 - \frac{1}{\lambda}\right).\]

<p>Since $(1-\eta_s\lambda) &lt; 1$, the excess above $1/\lambda$ decays <strong>exponentially</strong> to zero, regardless of the initialization. So $|W|_2$ converges to the constraint ball $|W|_2 \leq 1/\lambda$ at an exponential rate determined by $\eta\lambda$.</p>

<h3 id="why-weight-decay-is-necessary-in-muon">Why Weight Decay is Necessary in Muon</h3>

<p>Setting $\lambda = 0$ collapses the spectral norm constraint: the bound $1/\lambda \to \infty$, so no constraint is enforced and $|W|_2$ can grow unboundedly.</p>

<p>Without weight decay the update is $W_{t+1} = W_t + \eta O_t$ with $|O_t|_2 = 1$, so the spectral norm satisfies $|W_t|_2 \leq |W_0|_2 + \eta t$ — it grows linearly. In practice this leads to training instability: the weight matrices become large operators that amplify activations at every layer, destabilizing the forward pass and making loss spikes likely.</p>

<p>The $\lambda$-dependence also means <strong>weight decay is not just regularization</strong> in Muon — it is a core hyperparameter that sets the scale of the network’s linear maps. Choosing $\lambda$ is equivalent to choosing the maximum allowed spectral norm $1/\lambda$ of each weight matrix, which in turn sets the maximum activation amplification per layer. This is a much more interpretable handle than the ad-hoc weight decay schedules common in AdamW training.</p>

<h3 id="practical-variants">Practical Variants</h3>

<p>Su Jianlin’s optimizer guide <a href="https://www.spaces.ac.cn/archives/11416">苏剑林, 2025</a> covers the practical implications of these norm choices and how to use Muon alongside other optimizers in a real training setup. The key design question for practitioners is: <strong>which parameters get which norm?</strong></p>

<p>In the standard MuonAdam setup, weight matrices get the spectral-norm LMO (polar factor), while vector parameters (biases, LayerNorm scales, embedding tables) get Adam — because Adam’s per-coordinate adaptive scaling is the natural steepest descent under a per-entry $\ell^\infty$ norm, which is appropriate for semantically independent scalar parameters. Crawshaw et al. (<a href="https://arxiv.org/abs/2510.09827">2025</a>) formalize this as constrained steepest descent under the product norm:</p>

\[\|(W_1, \ldots, W_L, \theta)\|_\text{MuonAdam} = \max\!\left(\max_\ell \|W_\ell\|_2,\; \frac{\eta_m}{\eta_b} \|\theta\|_{\text{ada},\infty}\right),\]

<p>where $|\cdot|_{\text{ada},\infty}$ is Adam’s adaptive $\ell^\infty$ norm. The ratio $\eta_m/\eta_b$ allows separate learning rates for matrices and vectors, which in practice is crucial — Muon matrices typically use $10\times$ larger learning rates than the Adam parameters.</p>

<p>Their variant <strong>MuonMax</strong> uses regularized (rather than constrained) steepest descent and scales each layer’s polar factor by the nuclear norm of its momentum buffer, giving each matrix an adaptive step size. This is more expensive (requires the nuclear norm at each layer) but significantly more robust to learning rate tuning.</p>

<h3 id="why-embeddings-and-lm-head-use-normalized-sgd">Why Embeddings and LM Head Use Normalized SGD</h3>

<p>MuonAdam applies Muon to matrix parameters and Adam to scalars/vectors. But there is a third category that needs its own treatment: <strong>embedding tables</strong> and the <strong>LM head</strong>. These are matrices, but applying Muon to them is the wrong choice — and the reason comes down to the structure of their inputs (<a href="https://www.spaces.ac.cn/archives/11647">苏剑林, 2025</a>).</p>

<p>For a regular linear layer $W \in \mathbb{R}^{m \times n}$, the input $x \in \mathbb{R}^n$ is a dense continuous vector. The worst-case output shift from an update $\Delta W$ over all unit-norm inputs is the spectral norm:</p>

\[\max_{\|x\|_2 = 1} \|\Delta W \, x\|_2 = \|\Delta W\|_2.\]

<p>This is exactly why spectral norm is the right budget for linear layers, and why the polar factor (which fixes $|\Delta W|_2 = 1$) gives increment stability.</p>

<p>For an <strong>embedding table</strong> $E \in \mathbb{R}^{V \times d}$, the input is always a one-hot vector $e_i$ for some token $i$. The embedding lookup is a row read:</p>

\[(\Delta E)\, e_i = \Delta E[i, :].\]

<p>The functional effect of any update on a given input touches only a single row. The worst-case shift over all possible inputs is therefore the <strong>max row norm</strong>:</p>

\[\max_i \|\Delta E[i, :]\|_2 = \|\Delta E\|_{2,\infty}.\]

<p>Since inputs are never dense, the spectral norm is the wrong budget — it measures the worst case over all unit-norm directions, most of which never occur. The right increment stability condition is $|\Delta E|_{2,\infty} \leq \eta$: every token embedding moves by at most $\eta$.</p>

<p>Plugging this into the steepest descent problem:</p>

\[U^* = \arg\max_U \, \text{Tr}(G^\top U) \quad \text{s.t.} \quad \max_i \|U[i,:]\|_2 \leq 1.\]

<p>The constraint decouples across rows, so we can maximize each row’s contribution independently. By Cauchy–Schwarz, $G[i,:] \cdot U[i,:] \leq |G[i,:]|_2 |U[i,:]|_2 \leq |G[i,:]|_2$, with equality when $U[i,:] = G[i,:] / |G[i,:]|_2$. The solution is:</p>

\[U^*[i,:] = \frac{G[i,:]}{\|G[i,:]\|_2} \quad \text{for each row } i.\]

<p>This is <strong>normalized SGD</strong>: normalize each row of the gradient to unit norm before the update step. It is the per-row analog of Muon — instead of orthogonalizing across all singular directions (appropriate when the input spans all of $\mathbb{R}^n$), it normalizes independently in each row (appropriate when each input activates exactly one row).</p>

<p>The <strong>LM head</strong> $W_\text{out} \in \mathbb{R}^{V \times d}$ follows the same logic from the output side. Each row $W_\text{out}[i,:]$ controls the logit for token $i$ via $W_\text{out}[i,:] \cdot h$. The per-token logit shift from a row update is $\Delta W_\text{out}[i,:] \cdot h$, bounded by the row norm. With $V \gg d$, the LM head is a tall matrix — exactly the regime where Muon’s polar factor can produce highly non-uniform row norms (the leverage-score failure mode from the Aurora analysis), leaving some tokens’ representations nearly frozen. Row-wise normalization avoids this by giving every token an equal per-step update.</p>

<hr />

<h2 id="the-algorithm">The Algorithm</h2>

<p>A naive implementation would compute the SVD at every step, which costs $O(\min(m,n) \cdot mn)$ and is slow on modern accelerators. Muon instead uses a <strong>Newton-Schulz iteration</strong> to compute the polar factor using only matrix multiplications.</p>

<p>The quintic iteration from modded-nanoGPT is:</p>

\[X_{k+1} = \frac{1}{8}\left(15 X_k - 10 X_k X_k^\top X_k + 3 X_k (X_k^\top X_k)^2\right),\]

<p>initialized from a rescaled gradient $X_0 = G / |G|_F$. After 5–6 steps this converges to the polar factor with high precision. The only operations are matrix multiplications — no eigendecompositions, no square roots — making it hardware-efficient and easy to fuse.</p>

<p>The full Muon update for a matrix parameter $W$ is:</p>

\[\begin{aligned}
M_t &amp;\leftarrow \beta_1 M_{t-1} + (1 - \beta_1) G_t \\
O_t &amp;\leftarrow \operatorname{polar}(M_t) \\
W_{t+1} &amp;\leftarrow W_t - \eta \lambda W_t - \eta \, O_t
\end{aligned}\]

<p>where $M_t$ is the gradient momentum buffer. The momentum makes the polar factor computation smoother and more stable, since $M_t$ averages over recent gradients before orthogonalization.</p>

<p><strong>Spectral vs. Frobenius.</strong> Note that the update $O_t$ has spectral norm exactly 1 and Frobenius norm $\sqrt{\min(m,n)}$. Each step moves $W$ by the same amount regardless of how large or small the recent gradients were — only their <em>direction</em> matters. This is a strong form of scale invariance.</p>

<hr />

<h2 id="the-neuron-death-claim">The Neuron Death Claim</h2>

<p>Tilde Research’s Aurora paper <a href="https://blog.tilderesearch.com/blog/aurora">(Dewulf et al., 2026)</a> raised a sharp concern: <strong>Muon can cause persistent neuron death in MLP layers</strong>, and the mechanism is geometrically inevitable for tall weight matrices.</p>

<h3 id="leverage-scores">Leverage Scores</h3>

<p>For a matrix $M \in \mathbb{R}^{m \times n}$ with thin SVD $M = U_r \Sigma V^\top$, define the <strong>leverage score</strong> of row $i$ as:</p>

\[\ell_i(M) = \|(U_r)_{i,\cdot}\|_2^2.\]

<p>The $m$ leverage scores sum to $n$ (since $|U_r|_F^2 = n$), and the row norm of the polar factor $\operatorname{polar}(M)$ at row $i$ equals $\sqrt{\ell_i(M)}$. A row with high leverage score gets a large update; a row with low leverage score gets a tiny update.</p>

<p><strong>For tall matrices ($m &gt; n$)</strong>, orthogonality imposes only that $U_r^\top U_r = I_n$, which means the $m$ leverage scores must sum to $n$ but are otherwise unconstrained — they can concentrate arbitrarily. This is in contrast to <strong>square or wide matrices</strong>, where $U_r$ is itself square and orthogonal, forcing $\ell_i = 1$ for all $i$.</p>

<h3 id="the-feedback-loop">The Feedback Loop</h3>

<p>Here is the self-reinforcing failure mode the Aurora authors identify:</p>

<ol>
  <li>Early in training, some MLP neurons receive smaller gradient rows than others — perhaps due to initialization or early data statistics.</li>
  <li>The momentum buffer $M_t$ develops <strong>non-uniform row norms</strong>. Rows with consistently small gradients accumulate small momentum.</li>
  <li>Via the leverage bound $\ell_i(M) \leq |M_{i,\cdot}|^2 / \sigma_n(M)^2$ (Claim 2 in the paper), rows with small momentum get small leverage scores in the polar factor $O_t$.</li>
  <li>These rows receive near-zero weight updates. Their corresponding neurons in the MLP (specifically the up-projection and gate rows in a SwiGLU block) never learn.</li>
  <li>Since they never update, their gradient signal remains small — reinforcing the small momentum — and the cycle continues.</li>
</ol>

<p>The Aurora paper found this empirically at 340M and 1B scale: by step 500, more than one in four neurons in middle MLP layers showed near-zero leverage under Muon, with a sharply bimodal leverage distribution. Under their fix (U-NorMuon or Aurora), leverage remained isotropic throughout training.</p>

<p><strong>Why is this specific to tall matrices?</strong> In the up-projection $W_\text{up} \in \mathbb{R}^{d_\text{ff} \times d_\text{model}}$, we have $d_\text{ff} \gg d_\text{model}$ (e.g., $4 \times$ expansion). This is a tall matrix. Its polar factor $UV^\top$ can have highly non-uniform row norms. By contrast, the down-projection $W_\text{down} \in \mathbb{R}^{d_\text{model} \times d_\text{ff}}$ is wide, and orthogonality forces uniform row norms automatically.</p>

<hr />

<h2 id="my-experiment-no-dead-neurons-at-4m-scale">My Experiment: No Dead Neurons at 4M Scale</h2>

<p>The Aurora paper’s evidence comes from large transformer pretraining (340M–1B parameters, billions of tokens). I ran Muon on a much smaller setting: a <strong>4M-parameter encoder</strong> trained on 4M samples, with SwiGLU MLPs, comparing AdamW vs. Muon.</p>

<h3 id="methodology">Methodology</h3>

<p>A “dead” SwiGLU neuron requires <em>both</em> the gate row <em>and</em> the corresponding up row to show persistently low effective gradient and update norms — across all checkpoints after a reference step.</p>

<p>I tracked the <strong>effective gradient norm ratio</strong> and <strong>effective update norm ratio</strong> (each row’s norm divided by the same-layer mean) across snapshots at steps 100, 150, 200, and 245. A neuron is declared dead if its ratio stays below a threshold for every snapshot after the reference step.</p>

<h3 id="results">Results</h3>

<table>
  <thead>
    <tr>
      <th>Variant</th>
      <th style="text-align: right">Dead pairs @0.05×</th>
      <th style="text-align: right">Dead pairs @0.10×</th>
      <th style="text-align: right">Dead pairs @0.25×</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AdamW</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0 (0.000%)</td>
    </tr>
    <tr>
      <td>Muon</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0 (0.000%)</td>
    </tr>
  </tbody>
</table>

<p>At the 0.25× threshold — already quite generous — neither optimizer produces a single dead neuron pair. At 0.5×, Muon shows 3 dead pairs (0.004%), versus 0 for AdamW, but this is negligible.</p>

<p>The row-level statistics tell a more nuanced story:</p>

<table>
  <thead>
    <tr>
      <th>Variant</th>
      <th style="text-align: right">Threshold</th>
      <th style="text-align: right">Low grad rows</th>
      <th style="text-align: right">Low update rows</th>
      <th style="text-align: right">Low both</th>
      <th style="text-align: right">Dead pairs</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AdamW</td>
      <td style="text-align: right">0.25</td>
      <td style="text-align: right">74 (0.050%)</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0 (0.000%)</td>
      <td style="text-align: right">0</td>
    </tr>
    <tr>
      <td>Muon</td>
      <td style="text-align: right">0.25</td>
      <td style="text-align: right">175 (0.119%)</td>
      <td style="text-align: right">44 (0.030%)</td>
      <td style="text-align: right">39 (0.026%)</td>
      <td style="text-align: right">0</td>
    </tr>
  </tbody>
</table>

<p>Muon does show a heavier persistent low-update tail than AdamW at the row level, which is consistent with the leverage anisotropy mechanism. But the paired gate-up death — the genuine neuron death — does not materialize. The window-max quantiles show that even the weakest rows maintain some update activity:</p>

<table>
  <thead>
    <tr>
      <th>Variant</th>
      <th>Metric</th>
      <th style="text-align: right">q0.1%</th>
      <th style="text-align: right">q1%</th>
      <th style="text-align: right">q5%</th>
      <th style="text-align: right">Median</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Muon</td>
      <td>update window-max</td>
      <td style="text-align: right">0.3432</td>
      <td style="text-align: right">0.5551</td>
      <td style="text-align: right">0.7147</td>
      <td style="text-align: right">1.0470</td>
    </tr>
    <tr>
      <td>AdamW</td>
      <td>update window-max</td>
      <td style="text-align: right">0.6709</td>
      <td style="text-align: right">0.8037</td>
      <td style="text-align: right">0.9167</td>
      <td style="text-align: right">1.2460</td>
    </tr>
  </tbody>
</table>

<p>Even at the 0.1th percentile, the worst Muon row has a window-max update ratio of 0.34× — low, but not zero, and not persistently suppressed in the way the Aurora paper describes for large models.</p>

<h3 id="what-does-this-mean">What Does This Mean?</h3>

<p>The Aurora paper identified a <em>scale-dependent</em> failure mode. Their experiments with 340M and 1B parameter models trained for thousands of steps show the feedback loop crystallizing early and persisting. My 4M experiment, with far fewer parameters and a short 245-step window, likely does not give the feedback loop time or capacity to fully develop.</p>

<p>Several factors may explain the discrepancy:</p>

<p><strong>Training depth.</strong> The self-reinforcing cycle needs time. The Aurora authors observe collapse as early as step 500, but their models trained for 10,000+ steps. With 245 steps I may simply be measuring before the pathology appears.</p>

<p><strong>Model width.</strong> The Aurora paper notes that Aurora’s gains <em>scale with MLP width</em>. A 4M encoder has much narrower MLPs than a 340M transformer; the leverage score distribution has fewer degrees of freedom to develop anisotropy.</p>

<p><strong>Initialization and conditioning.</strong> At small scale, gradient norms may stay better-conditioned throughout training. The bound $\ell_i(M) \leq |M_{i,\cdot}|^2 / \sigma_n(M)^2$ tightens when $\sigma_n(M)$ (the smallest singular value of the momentum buffer) is large — which is more likely for smaller, better-conditioned models.</p>

<p><strong>The Muon leverage signal is there, just not catastrophic.</strong> The 39 rows with persistently low gradient <em>and</em> low update norm (0.026%) hint that the mechanism is present but suppressed. At larger scale, this trace likely amplifies into the 25%+ dead-neuron regime the Aurora authors observe.</p>

<hr />

<h2 id="discussion">Discussion</h2>

<p>Muon’s mathematical foundation is principled and elegant: it is steepest descent in spectral norm, the natural matrix operator norm. By stripping scale from the gradient and using only its directional information (the polar factor), Muon treats all singular directions of the gradient equally — unlike Adam, which privileges high-variance directions.</p>

<p>The neuron death concern from Aurora is real and theoretically grounded. For tall matrices, the polar factor can carry significant row-norm anisotropy, and the Muon momentum loop has no mechanism to correct it. Aurora’s fix — adding a uniform row-norm constraint to the steepest-descent problem — is mathematically principled and yields a cleaner optimization problem on the joint Stiefel/equal-leverage manifold $\mathcal{M} = {U : U^\top U = I,\, \text{diag}(UU^\top) = \frac{n}{m}\mathbf{1}}$.</p>

<p>But my experiment suggests this pathology is not universal across scales. At 4M parameters and a short training window, Muon shows no meaningful neuron death — and in fact trains comparably to AdamW. This matters practically: if you are training small-to-medium models, vanilla Muon appears safe.</p>

<p>The responsible conclusion is scale-dependent: Muon is a theoretically sound improvement over Adam for matrix parameters, and its leverage-score failure mode is real but emerges primarily at scale. For large-scale pretraining — frontier models with wide MLPs and long training runs — Aurora or U-NorMuon are worth the modest overhead. For smaller encoder training, standard Muon holds up fine.</p>

<hr />

<h2 id="references">References</h2>

<ul>
  <li>Kosson et al., “Muon: Momentum Orthogonalized by Newton-Schulz” (2024)</li>
  <li>Dewulf*, Pai*, Yang*, Zhang*, Keigwin, “Aurora: A Leverage-Aware Optimizer for Rectangular Matrices,” Tilde Research (2026). <a href="https://blog.tilderesearch.com/blog/aurora">blog</a></li>
  <li>Su Jianlin, “Muon 优化器的数学原理” (2024). <a href="https://www.spaces.ac.cn/archives/11647">spaces.ac.cn</a></li>
  <li>Su Jianlin, “MuP之上：1. 好模型的三个特征” (2025). <a href="https://www.spaces.ac.cn/archives/11340">spaces.ac.cn</a></li>
  <li>Su Jianlin, “MuP之上：2. 线性层与最速下降” (2025). <a href="https://www.spaces.ac.cn/archives/11605">spaces.ac.cn</a></li>
  <li>Su Jianlin, “MuP之上：3. 特殊情况特殊处理” (2025). <a href="https://www.spaces.ac.cn/archives/11647">spaces.ac.cn</a></li>
  <li>Su Jianlin, “Muon续集：为什么我们选择尝试Muon？” (2025). <a href="https://www.spaces.ac.cn/archives/10739">spaces.ac.cn</a></li>
  <li>Chen et al., “Muon Optimizes Under Spectral Norm Constraints” (2025). <a href="https://arxiv.org/abs/2506.15054">arXiv:2506.15054</a></li>
  <li>Jordan Keller, “modded-nanoGPT” speedrun. <a href="https://github.com/KellerJordan/modded-nanoGPT">GitHub</a></li>
</ul>]]></content><author><name>Tianshu Yu</name></author><category term="machine-learning" /><category term="optimization" /><category term="Other" /><summary type="html"><![CDATA[Muon has quietly climbed to the top of the nanoGPT speedrun leaderboard and is now used in frontier-scale training runs. This post explains the mathematics that makes it tick, surveys the recent claim that it causes neuron death in MLP layers, and then presents my own small-scale encoder experiment that complicates that narrative.]]></summary></entry><entry><title type="html">Distilling Vision Encoders from Multiple Teachers — and How to Tell If It Worked</title><link href="https://tianshu-michael-yu.github.io/machine-learning/vision/distillation/2026/05/04/encoder-distillation-and-eval.html" rel="alternate" type="text/html" title="Distilling Vision Encoders from Multiple Teachers — and How to Tell If It Worked" /><published>2026-05-04T00:00:00+00:00</published><updated>2026-05-04T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/machine-learning/vision/distillation/2026/05/04/encoder-distillation-and-eval</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/machine-learning/vision/distillation/2026/05/04/encoder-distillation-and-eval.html"><![CDATA[<p><em>A practitioner’s view on multi-teacher distillation for general-purpose visual representations, and the evaluation suite that should follow it.</em></p>

<hr />

<h2 id="why-distill-encoders-at-all">Why distill encoders at all</h2>

<p>Modern vision encoders are increasingly <em>general-purpose</em>: a single ViT backbone is asked to do classification, retrieval, dense prediction, robotics control, and conditioning for generative models. The frontier models that produce the best representations — DINOv2, SigLIP/SigLIP 2, CLIP at scale, MAE/MAE-2, AM-RADIO, Theia, SAM’s image encoder — each capture <em>complementary</em> signal. CLIP and SigLIP are strong at semantics and language alignment; DINOv2 produces the cleanest dense features for segmentation, depth, and correspondence; MAE preserves pixel-level reconstructive structure; SAM’s encoder carries the strongest spatial priors for promptable mask quality.</p>

<p>No single pretraining objective dominates. So the natural move is to <em>amalgamate</em> them into one student that inherits the union of capabilities — at a fraction of the cost. That is the bet behind multi-teacher encoder distillation, and it is where AM-RADIO, Theia, UNIC, and a flurry of follow-ups live.</p>

<p>This post walks through the design choices that actually matter when you build such a student, and then — because distillation is uniquely easy to deceive yourself about — the evaluation methodology I’d insist on before believing any number.</p>

<h2 id="what-multi-teacher-encoder-distillation-actually-optimizes">What multi-teacher encoder distillation actually optimizes</h2>

<p>The high-level recipe is simple: feed the same image to N frozen teachers and to a student backbone, then push the student to match each teacher’s output through a teacher-specific projection head.</p>

\[\mathcal{L} = \sum_{t=1}^{N} \lambda_t \, \mathcal{D}_t\!\left( h_t(f_\theta(x)),\; g_t(x) \right)\]

<p>Here $f_\theta$ is the shared student trunk, $h_t$ is a small per-teacher head (usually a 1–3 layer MLP or transformer), $g_t$ is teacher $t$’s frozen output, and $\mathcal{D}_t$ is the matching loss. Almost every interesting design choice is hidden in those four symbols.</p>

<p><strong>What to match.</strong> Logits-style matching is mostly irrelevant here — these are encoders, not classifiers. You’re choosing among (a) the global representation (CLS token / pooled embedding), (b) the full patch-token grid, and (c) intermediate features. Global-only matching is cheap but throws away exactly the signal that makes DINOv2 valuable: spatially coherent dense features. AM-RADIO’s lesson is that <em>dense</em> matching at the patch level is what unlocks segmentation- and detection-grade students. If a teacher’s value proposition is dense (DINOv2, SAM, MAE), match its tokens. If it’s global (CLIP, SigLIP), match the summary embedding plus, optionally, a coarser version of its tokens.</p>

<p><strong>Resolution mismatch.</strong> Teachers were trained at different input sizes and patch sizes (CLIP at 224 with patch 14 or 16, DINOv2 at 224 or 518 with patch 14, SigLIP 2 at 256+, SAM at 1024). The student is one tower with one patch size. You’ll need either (i) per-teacher resize + interpolation of their token grid to the student’s grid, or (ii) variable-resolution training where the student processes multiple crops at the teacher’s native resolution. Option (ii) preserves dense signal better but multiplies compute. AM-RADIO uses partition-by-resolution mini-batches; Theia uses bilinear feature resizing; both work, but the bilinear shortcut tends to blur fine features on small objects.</p>

<p><strong>Distance function.</strong> Cosine similarity in a normalized space is the safe default for global embeddings. For dense features, smooth-L1 or MSE on L2-normalized tokens beats raw MSE because it stops one teacher with large feature norms from dominating the gradient. Some authors add a Pearson/correlation term; in practice the gains are marginal once you normalize.</p>

<p><strong>Teacher weighting.</strong> Hand-tuning $\lambda_t$ is the part nobody likes. Three approaches in use: fixed weights (simple, brittle), uncertainty-weighted losses à la Kendall et al. (one learnable log-variance per teacher), and gradient-norm balancing (GradNorm). The dirty secret is that fixed weights, with a short hyperparameter sweep on a downstream proxy, are usually within noise of the fancier schemes. What <em>does</em> matter is normalizing each teacher’s loss to a comparable scale before you weight it; otherwise your weights are just absorbing scale differences.</p>

<p><strong>Heads vs. shared trunk.</strong> Per-teacher heads are non-negotiable — the teachers live in different feature spaces, and forcing the student trunk to produce all of them at once collapses representation quality. The interesting question is <em>where</em> the heads attach. Attaching all heads to the final block makes the trunk a Swiss-army feature; attaching different heads to different depths (e.g., a SAM head on a mid-block, a CLIP head on the final block) tends to give better dense metrics but is finicky to tune.</p>

<p><strong>Token types and per-token losses.</strong> A modern ViT trunk emits three kinds of tokens, and a careful distillation recipe treats them differently because they carry different signal:</p>

<ul>
  <li>The <strong>CLS token</strong> (or a learned “summary” token) is what gets pooled into a single vector for global tasks. In CLIP/SigLIP it’s the embedding the contrastive loss is applied to; in DINOv2 it’s where most of the image-level semantics live. Its job is to summarize the image into one direction in feature space.</li>
  <li><strong>Patch tokens</strong> are the per-location features on the $h \times w$ grid. They carry locality: object boundaries, stuff/things distinctions, spatial layout. These are the tokens that drive ADE20K dense probe, depth, correspondence, mask quality.</li>
  <li><strong>Register tokens</strong> were introduced in <em>Vision Transformers Need Registers</em> (Darcet et al., 2024) and are now standard in DINOv2/v3 and AM-RADIO. They’re a small set (e.g., 4–16) of extra learned tokens with no positional meaning. They act as a sink: without them, ViTs spontaneously co-opt a handful of <em>patch</em> tokens (often in low-information regions of the image) to store global “scratch” information, which corrupts the patch grid and produces those characteristic high-norm artefacts you see in DINOv2 attention maps. With registers, the artefact tokens move off the patch grid into the registers, and the patch grid stays clean.</li>
</ul>

<p>The reason this matters for distillation is that <strong>a single matching loss across all tokens is the wrong design</strong>. AM-RADIO’s recipe is the canonical example of separating them:</p>

<ul>
  <li><em>Summary loss</em> (CLS-to-CLS): cosine distance between the student’s summary token (after a teacher-specific summary head) and the teacher’s CLS / pooled output. This is the loss that transfers CLIP-style semantics or DINO’s global concept structure. Cosine outperforms L1/MSE/Smooth-L1 here because the summary direction matters more than its magnitude.</li>
  <li><em>Feature loss</em> (patch-to-patch): cosine + Smooth-L1 between the student’s patch tokens (after a teacher-specific feature head) and the teacher’s spatial token grid. This is the loss that transfers locality. Empirically, the AM-RADIO ablation found that <em>spatial</em> matching helped not just dense downstream tasks — it improved global quality too, which is the cleanest evidence that the “global summary” you get out of a contrastive teacher is leaving structure on the table that you only recover by matching the full grid.</li>
  <li><em>Registers are not distilled directly, and — perhaps surprisingly — the RADIO student does not appear to use them at all.</em> The RADIOv2.5 paper describes the student as a plain ViT with cropped position embeddings and per-teacher MLP adaptors, with no register tokens in the student backbone, even though one of its teachers (<code>DINOv2-g-reg</code>) uses them. C-RADIOv4 doesn’t mention student-side registers either; the only occurrence of “register” in the v4 tech report is a bibliographic citation. There is <strong>no published ablation</strong> comparing student-with-registers vs. student-without-registers in any RADIO paper. So treat the architectural choice as defensible-by-inference rather than empirically validated. The likely reasons it works without student registers: the <em>teachers</em> whose patches are matched (DINOv2-g-reg, DINOv3, SAM) have already absorbed their high-norm outliers into their own registers <em>before</em> exposing patch features as targets, so the student is being trained against an already-clean distribution; SigLIP/SigLIP 2 has no registers and no comparable artefact pattern (contrastive training doesn’t push patches into outlier roles the way DINO-style local objectives can); and adding registers to the student would create tokens with no supervision signal at all — neither teacher’s registers correspond to the student’s, and a positional loss between unordered learned tokens is meaningless. C-RADIOv4 instead defends patch-grid cleanliness through a <em>shift-equivariant dense loss</em> (independent random crops for student and teacher, with shift-aligned matching) that prevents the student from baking position-fixed artefacts into specific patch locations. That’s protecting the same property registers protect, but at the loss level rather than the architecture level. If you’re building your own multi-teacher recipe, this is genuinely an open ablation worth running — there’s no public answer for whether student-side registers would help on top of supervised, already-clean patch targets.</li>
</ul>

<p>A subtler point: AM-RADIO ablated using a <em>separate</em> student CLS token vs. average-pooling the student’s patch tokens for the summary loss. Average-pooling looks tempting (one fewer token), and it improves the summary loss in isolation — but it <em>hurts</em> the feature (patch) loss, because you’re now leaning on the patch grid to do double duty. They picked separate CLS tokens for exactly this reason. The general lesson: give each loss its own dedicated tokens, or you get cross-talk where one objective degrades another’s signal.</p>

<p><strong>Adapter / per-teacher head design — and why it matters even with one teacher.</strong> I left this for last in the loss/architecture knobs because it’s the one most people under-engineer. The per-teacher head $h_t$ is the only thing that can absorb the geometric mismatch between the student’s feature space and teacher $t$’s — different dimensionality, different norm scale, different anisotropy. There are three common choices and they are not equivalent:</p>

<ol>
  <li><strong>Bare linear projection.</strong> $h_t(z) = W_t z + b_t$. One matrix per teacher. Cheap, easy to interpret, and the natural starting point. The implicit assumption is that the student’s trunk features and the teacher’s targets are already related by an affine transform — which is almost never true after PHI-S, let alone before.</li>
  <li><strong>Single MLP</strong> (<code>Linear → GELU → Linear</code>, optionally with a LayerNorm). The default in many distillation codebases. Adds one nonlinearity, which is enough to fit <em>some</em> curvature but typically not enough when the teacher’s manifold is highly non-affine relative to the student’s (e.g., distilling DINO patch features from a CLIP-pretrained init, or matching a teacher whose features live on a different effective rank).</li>
  <li>
    <p><strong>The RADIO-style residual adapter (<code>MLP2</code> in <code>radio/adaptor_mlp.py</code>).</strong> This is what NVlabs uses in v2.5/v4 and it is more elaborate than the usual MLP. The actual structure in the released code is:</p>

    <pre><code>(optional pre-norm: LN + GELU)
  ↓
Linear(in → hidden)                       # fc1, bare linear, no activation
  ↓
num_inner × residual block:
    x = x + Linear(GELU(LayerNorm(x)))    # pre-LN, single Linear inside the residual
  ↓
LayerNorm + GELU + Linear(hidden → out)   # "final" projection
</code></pre>

    <p>So it’s: input projection into a hidden width → some small number of pre-LN GELU residual blocks (typically 2, but <code>num_inner</code> is data-driven from the checkpoint) → a pre-norm output projection. RADIO uses two independent instances per teacher — <code>head_mlp</code> for the summary token and <code>feat_mlp</code> for patch features — wired up in <code>GenericAdaptor</code>. The feature head additionally supports an optional spatial upsample.</p>

    <p>What this buys you over a single-MLP head: (i) the residual blocks let depth grow without making early training unstable, so the head can fit nontrivial curvature in the teacher manifold; (ii) the pre-LN inside each block stabilizes gradients flowing back into the trunk, which is what you actually care about — the head’s job is to deliver a <em>clean</em> gradient to the backbone, not to be small; (iii) the final pre-norm + GELU + linear means the output isn’t a raw linear projection from the residual stream, which empirically improves match quality at the tail of the distribution where teacher features have outliers.</p>
  </li>
</ol>

<p><strong>This matters even for single-teacher distillation.</strong> I ran this myself: distilling from one teacher only, the RADIO-style residual adapter beat both a bare linear projection and a single-layer MLP on downstream metrics, by a margin large enough that it wasn’t seed noise. The naive intuition — “with one teacher you don’t need scale balancing, so a linear should be fine” — misses the point. The head isn’t only there to balance teachers; it’s there to absorb the curvature mismatch between <em>any</em> two feature spaces. A linear projection forces the student’s trunk to do all the nonlinear bending itself, which both wastes trunk capacity on plumbing and produces worse downstream features because the trunk is now overfitting to one specific output geometry.</p>

<p>The practical rule I’d give: <strong>use a residual adapter with at least two pre-LN blocks even when N = 1</strong>. Hidden width = teacher feature dim is a fine default. The extra parameter count is negligible compared to the backbone, and the downstream gains hold up across teachers. If you want a single sentence rationale: the head should be expressive enough that the trunk can stay general-purpose; if the head is too weak, the trunk gets specialized as a teacher-shaped projection and you’ve lost the whole point of distillation.</p>

<p><strong>PHI-S: why teacher feature distributions need standardization.</strong> Once you have two losses across N teachers, the next thing that bites you is that <strong>teachers’ activation statistics are wildly incompatible</strong>. CLIP’s CLS token might have feature variance ~1 with light tails; DINOv2’s patch tokens have huge dynamic range with heavy-tailed outliers (the high-norm artefact tokens, even with registers, leave residual heavy tails); SAM’s encoder lives at a different scale entirely. If you naively apply MSE or Smooth-L1, the teacher with the largest variance gets implicitly the largest weight in the gradient, regardless of whatever $\lambda_t$ you set. This is the “scale absorption” problem I flagged earlier under teacher weighting, but it’s worse than it first sounds: variance differs <em>per dimension</em> of the feature vector, not just per teacher, so even per-teacher loss normalization isn’t enough.</p>

<p><strong>PHI-S</strong> (“PHI Standardization”, from Heinrich et al., NVIDIA, 2024) is the cleanest fix and is now the default in the RADIO line. The idea, in three steps:</p>

<ol>
  <li>Estimate each teacher’s per-feature mean and covariance over a sample of activations.</li>
  <li>Whiten each teacher’s distribution to zero mean and identity covariance — but a naïve PCA-style whitening produces dimensions with <em>different</em> scales after rotation back, which still lets some dimensions dominate.</li>
  <li>Apply a <strong>Hadamard matrix</strong> rotation. The Hadamard matrix has the property that all its rows have unit $L_2$ norm and entries $\pm 1/\sqrt{d}$, so when you whiten and then rotate by $H$, every dimension of the resulting distribution has the <em>same</em> scale. This is <em>isotropic</em> standardization — each feature dimension contributes equally to MSE/Smooth-L1.</li>
</ol>

<p>Concretely, for each teacher $t$ you precompute a fixed transform $T_t = H \Sigma_t^{-1/2}$ and a fixed mean $\mu_t$, then apply $\tilde{g}_t(x) = T_t (g_t(x) - \mu_t)$ before the loss. The student head is trained to predict $\tilde{g}_t(x)$, not $g_t(x)$. At inference time you can either invert the transform (if you need teacher-aligned features) or just use the standardized feature space directly.</p>

<p>Why this matters in practice:</p>

<ul>
  <li><em>Teachers become loss-balanced for free.</em> With PHI-S, you can use $\lambda_t = 1/N$ across teachers and get behavior that previously required GradNorm or learned uncertainty weights. The paper shows PHI-S beats MSE, Smooth-L1, and standard whitening across the board.</li>
  <li><em>Per-teacher feature heads can be smaller.</em> When the target distribution is well-conditioned, the head doesn’t have to absorb scale — so head-collapse pressure goes down.</li>
  <li><em>It composes with the per-token-type losses above.</em> You apply PHI-S separately to each teacher’s CLS distribution and each teacher’s patch-token distribution, because their statistics are different.</li>
</ul>

<p>PHI-S is the unsexy load-bearing piece of multi-teacher distillation: not glamorous, but the difference between a clean recipe and one where you spend weeks tuning loss weights and never quite figuring out why one teacher’s signal is dominating.</p>

<p><strong>Data.</strong> Pretraining data matters more than the loss. The teachers themselves were trained on huge image corpora; if you distill on a small or biased dataset, you bake that bias into the student even though the teachers wouldn’t have. A web-scale unlabeled image set (LAION-style, DataComp filtered, or the DINOv2 LVD-142M curation) is the floor. Distillation is <em>extremely</em> sample-efficient compared to from-scratch pretraining — you typically need 10–30% of the original tokens to recover most of teacher quality — but “less data” is not the same as “tiny data.”</p>

<h2 id="the-single-biggest-failure-mode">The single biggest failure mode</h2>

<p>The thing that bites people is <strong>target collapse at the head</strong>. The student looks great on the distillation loss, the heads’ cosine-with-teacher numbers approach 0.95, and downstream metrics are still mediocre. What’s happening: the heads have absorbed all the per-teacher idiosyncrasy and the trunk is producing a generic feature that’s <em>easy to project</em> but doesn’t actually carry teacher-specific structure. You only see this if you evaluate the <strong>trunk</strong> directly, with frozen features and no head — which is exactly what the evaluation section below is built around.</p>

<h2 id="optimizer-geometry-choosing-muon-and-what-it-actually-does">Optimizer geometry: choosing Muon, and what it actually does</h2>

<p>Most distillation recipes default to AdamW out of habit. The optimizer choice meaningfully changes what the trunk learns, though, and once you understand the geometry, Muon turns out to be a clean fit for the two-loss, multi-teacher setting we’ve been describing. The next few subsections are the why; the practical recipe lives at the bottom for skimmers.</p>

<h3 id="optimizers-as-choices-of-norm">Optimizers as choices of norm</h3>

<p>Every gradient-based optimizer can be characterized as steepest descent under some norm constraint. Pick a norm $|\cdot|$, define your update as</p>

\[\Delta W \;=\; \arg\max_{\|\Delta\|\,\le\,1}\;\langle -\nabla L,\;\Delta\rangle,\]

<p>and the optimizer’s behavior falls out. The inner product is the first-order predicted decrease in loss; the constraint sets the “budget” the parameter is allowed to move per step (the learning rate $\eta$ scales the answer back to whatever step size you want). All of an optimizer’s personality lives in the choice of norm, because the norm determines the shape of the unit ball and therefore the shape of the maximizer.</p>

<p>Under a Frobenius ball you get vanilla SGD’s direction. Under an $\ell_\infty$ ball on entries you get sign-SGD. Under a <em>coordinate-wise weighted</em> $\ell_\infty$ ball — entries normalized by a running second-moment estimate $\sqrt{\hat v}$ — you get the (approximate) AdamW step:</p>

\[\Delta W_{ij} \;\approx\; \frac{-\hat m_{ij}}{\sqrt{\hat v_{ij}}}.\]

<p>The Muon paper calls this the “Max-of-Max norm”: you cap each entry independently. The construction treats a weight <em>matrix</em> as a bag of scalars and gives each scalar its own adaptive step size. That’s a perfectly reasonable thing to do for embeddings, biases, and RMSNorm scales — parameters that genuinely are bags of scalars. It is <em>not</em> a reasonable thing to do for weight matrices that act as linear operators on activations, which is what almost all the parameters in a ViT trunk are.</p>

<h3 id="spectral-norm-and-the-operator-view">Spectral norm and the operator view</h3>

<p>The natural norm for a weight matrix isn’t entry-wise; it’s operator-wise. A weight matrix $W \in \mathbb{R}^{m\times n}$ sits inside the network as a linear map $x \mapsto Wx$. What matters for stability is how much $W$’s action on its input changes when you update it — the spectral norm of the change $|\Delta W|_2$, not its entry-wise magnitude. Two updates can have identical Frobenius norms but very different operator behavior: a rank-1 update concentrates its full Frobenius budget along one singular direction and produces a big spectral change there, while a rank-$n$ update spreads the same budget across many directions for a smaller per-direction change. The Frobenius budget doesn’t see this; the spectral budget does.</p>

<p>Concretely, the spectral norm of $A$ is its largest singular value:</p>

\[\|A\|_2 \;=\; \sigma_{\max}(A) \;=\; \max_{\|x\|_2 = 1}\|Ax\|_2 \;=\; \sqrt{\lambda_{\max}(A^\top A)}.\]

<p>In practice nobody computes a full SVD for this; a few iterations of power iteration on $A^\top A$ converge linearly at rate $(\sigma_2/\sigma_1)^2$, and spectral normalization in GANs uses one iteration per training step.</p>

<p>A confusion worth flagging while we’re here: “the L2 norm of a matrix” is ambiguous. Treated as a flattened vector, it’s the Frobenius norm $\sqrt{\sum_{ij} A_{ij}^2}$. Treated as the operator norm induced by the L2 vector norm, it’s the spectral norm. They coincide only for rank-1 matrices; in general $|A|_2 \le |A|_F \le \sqrt{r}\,|A|_2$ where $r$ is the rank. PyTorch’s <code>grad_norm</code> (the number you log to wandb) is the Frobenius variety, applied to the entire flattened parameter vector — not the spectral norm of any individual matrix. Whenever this section says “spectral norm,” it’s the operator one.</p>

<h3 id="muons-update-rule">Muon’s update rule</h3>

<p>Muon’s whole substance is one step: given the EMA of past gradients $M_t$, replace it with its orthogonalized version before applying as an update. If $M_t = U\Sigma V^\top$ is the SVD, the orthogonalized update is</p>

\[O_t \;=\; UV^\top.\]

<p>That throws away $\Sigma$ entirely and keeps only the directions. The result has all singular values equal to 1: a (semi-)orthogonal matrix, an isometry on its row/column space, spectral norm exactly 1. The original paper calls this the “isomorphic” property — used loosely to mean <em>uniform across directions</em> (iso-morph = equal-form), not in the strict algebraic sense of structure-preserving bijection.</p>

<p>Mechanically, you never compute the SVD. Muon runs five iterations of a tuned quintic Newton-Schulz polynomial on the momentum matrix, which approximately pushes all singular values toward 1. The whole thing is matmuls — GPU-friendly, no expensive numerical linear algebra — and it works because the polynomial $p(x) = ax + bx^3 + cx^5$ with the right coefficients has a basin around $x \approx 1$ that’s attractive for any input in $[0, \sigma_{\max}]$.</p>

<p>The reason this is the right thing to do, in the variational-norm framing: $UV^\top$ is exactly the maximizer of $\langle -M_t, \Delta\rangle$ over the spectral-norm unit ball. So Muon is steepest descent under a spectral-norm constraint, by construction.</p>

<h3 id="why-equalizing-singular-values-is-the-right-move-not-the-wrong-one">Why equalizing singular values is the right move (not the wrong one)</h3>

<p>The obvious objection: shouldn’t directions with larger gradient signal get larger updates? Isn’t squashing all singular values to 1 throwing away useful information about which way to learn fastest?</p>

<p>The objection turns on what the singular values of $M_t$ actually mean. They don’t represent “the most important features”; they represent the conditioning of the gradient flow itself. A direction can dominate the momentum spectrum because the parameter happens to sit at a large scale, because the loss surface is steep along it but the variable is already nearly optimal, because earlier layers’ bad conditioning is leaking through, or simply because the gradient has been correlated along that direction for many steps and compounding has amplified it. None of those is “this is the right thing to learn faster.”</p>

<p>This is the same observation that motivates Adam vs. SGD. Adam normalizes per coordinate by the running variance because raw gradient magnitudes are not a reliable signal of update importance. Muon normalizes per singular direction by the singular value for the same reason, but at the matrix level rather than the scalar level. Both are saying: trust the direction more than the magnitude, because the magnitude is contaminated by stuff that has nothing to do with how fast you should be learning that direction.</p>

<p>A useful framing: orthogonalization is <em>whitening</em> applied in the singular-vector basis of the momentum. Whitening doesn’t claim that all features are equally important; it removes the spurious anisotropy introduced by the noise and correlation structure of the signal so that downstream learning sees a clean step. The Moonlight paper’s SVD-entropy ablations confirm this empirically: trained networks under Muon end up with <em>more diverse</em> singular spectra in their weights, not less. The orthogonalization step prevents the optimizer from collapsing onto a few singular directions per step — over many steps, the network still allocates capacity to genuinely useful directions, but it does so through accumulated gradient signal in the right basis, not through a single dominant per-step direction.</p>

<h3 id="consistent-update-rms-and-where-the-spectral-norm-framing-softens">Consistent Update RMS, and where the spectral-norm framing softens</h3>

<p>There’s a complication. The orthogonalized update $UV^\top$ has spectral norm exactly 1, but its per-entry magnitude (its RMS) is shape-dependent. For a full-rank update on an $A \times B$ matrix,</p>

\[\text{RMS}(UV^\top) \;=\; \frac{\|UV^\top\|_F}{\sqrt{AB}} \;=\; \frac{1}{\sqrt{\max(A, B)}}.\]

<p>This is Lemma 1 of the MuonScalable / Moonlight paper. The proof drops out of the singular-value structure: $|UV^\top|_F^2 = \min(A, B)$ (one per nonzero singular value), divide by $AB$ and take the square root.</p>

<p>The consequence at scale: a $4096 \times 4096$ MLP gets per-entry updates ~5.6× smaller than a $128 \times 128$ per-head projection under the same nominal step size. Big matrices under-train; small matrices over-train. Vanilla Muon scales badly to LLM-sized models for this reason, and the same problem shows up in encoder distillation as soon as you mix MHA, GQA, or MLA heads in the trunk.</p>

<p>The “Consistent Update RMS” fix is to multiply by $\sqrt{\max(A, B)}$ and a small global constant tuned to match AdamW’s empirical update RMS:</p>

\[\Delta W \;=\; \eta \cdot 0.2 \cdot O_t \cdot \sqrt{\max(A, B)}.\]

<p>After this rescaling, every matrix in the network — square, rectangular, big, small — gets per-entry updates of RMS ≈ 0.2, which lands inside AdamW’s empirical 0.2–0.4 range. The payoff is hyperparameter transfer: you can use the same <code>lr</code> and <code>weight_decay</code> you tuned for AdamW, and you can mix Muon (for 2D weights) and AdamW (for everything else) without retuning each group.</p>

<p>It’s worth being honest about what this trades away. The pure spectral-norm-budget story says every layer’s update should have $|\Delta W|_2 = \eta$ — one operator-scale step size network-wide. After the $\sqrt{\max(A,B)}$ rescaling, the spectral norm of the applied update is $0.2\eta\sqrt{\max(A,B)}$, which is layer-dependent. You can read this two ways: (i) as a <em>per-layer learning rate</em> $\tilde\eta_l \propto \sqrt{\max(A_l, B_l)}$ inside the spectral-norm framework, which is perfectly legal and doesn’t change how direction is chosen; (ii) as a <em>concession from spectral to entry-wise budgeting</em> — Muon picks step directions with spectral geometry but sizes steps with entry-wise (AdamW-matching) geometry, because empirically networks seem to want roughly constant per-entry update magnitude across layers regardless of shape. Both readings are correct; they’re the same equation viewed from different angles. The Moonlight paper picked entry-wise sizing because it makes hyperparameter sharing tractable, and for a distillation setup that’s juggling teacher selection, loss weights, and head architecture, removing optimizer hyperparameter drift from the search space is worth a lot.</p>

<h3 id="caveats-where-the-per-layer-spectral-view-holds-where-it-doesnt">Caveats: where the per-layer spectral view holds, where it doesn’t</h3>

<p>The “constrain each weight matrix’s spectral change per step” story is rigorous only when the network is a composition of linear maps and pointwise Lipschitz-bounded nonlinearities. Each linear stage has a well-defined spectral norm; ReLU, GELU, tanh, sigmoid, LayerNorm, and RMSNorm are all bounded-Lipschitz; and Lipschitz constants compose multiplicatively, so bounding each $|\Delta W_l|_2$ bounds the network’s global behavior to first order. There’s no “spectral norm of the whole network” object to speak of — the network is nonlinear and has no SVD — but the Jacobian at any input does, and its spectral norm is bounded by the product of the per-layer norms times the activation Lipschitz constants. That’s how a per-matrix step-size constraint translates to global stability.</p>

<p>Attention breaks this cleanly. The softmax over $QK^\top / \sqrt{d}$ involves a <em>quadratic</em> form in the activations, and the resulting map is not globally Lipschitz — its effective Lipschitz constant grows with activation scale (Kim et al. 2021 work this out formally for self-attention). Spectral-norm control on $W_Q$ and $W_K$ controls the projections themselves, but it does not bound the softmax-of-product downstream. This is why production transformers add QK-norm (RMSNorm on $Q$ and $K$ before the dot product), scaled initialization, and pre-LN on residual streams — those are stability mechanisms layered on top of the optimizer to handle the attention-shaped non-Lipschitz region. Muon doesn’t claim to solve attention stability; it provides well-conditioned per-matrix updates, and the architecture handles the rest.</p>

<p>Conv2d is the easier case. A 2D convolution is fully linear; its weight tensor has shape $[C_{\text{out}}, C_{\text{in}}, k_H, k_W]$, but the operation is a linear map and has a well-defined SVD (computable exactly via FFT per Sedghi et al. 2019). The standard Muon convention is to flatten the kernel into the input dimension — $[C_{\text{out}}, C_{\text{in}} \cdot k_H \cdot k_W]$ — and orthogonalize that 2D matrix. This is a useful approximation rather than the exact operator-space SVD, but it captures the dominant amplification mode (channel mixing usually dwarfs spatial mixing in a standard kernel).</p>

<h3 id="the-practical-recipe">The practical recipe</h3>

<p>PyTorch’s official <code>torch.optim.Muon</code> (added in 2.9) handles only 2D parameters and errors on anything else — there’s no automatic conv2d flattening. The implementation includes the consistent-RMS scaling but behind an opt-in flag:</p>

<pre><code class="language-python">muon_params = [
    p for n, p in model.named_parameters()
    if p.ndim == 2
    and "embed" not in n
    and "head" not in n
    and "norm" not in n
]
muon_ids = {id(p) for p in muon_params}
adamw_params = [p for p in model.parameters() if id(p) not in muon_ids]

optimizer_muon = torch.optim.Muon(
    muon_params,
    lr=lr,
    weight_decay=weight_decay,
    adjust_lr_fn="match_rms_adamw",   # opt into the sqrt(max(A,B)) scaling
)
optimizer_adamw = torch.optim.AdamW(
    adamw_params, lr=lr, weight_decay=weight_decay,
)
</code></pre>

<p>The <code>match_rms_adamw</code> flag selects the $0.2\sqrt{\max(A,B)}$ scaling from the paper. The default (<code>"original"</code>) only does Keller Jordan’s aspect-ratio correction $\sqrt{\max(1, A/B)}$ — fine for small models with mostly-square matrices, but it leaves you re-tuning learning rates at ViT-L and above. Always opt in for serious training.</p>

<p>Flash-attention varlen kernels are orthogonal to all of this — they’re a forward-pass implementation and Muon never sees them; the projection matrices they read are 2D and get handled normally. If you have conv layers (a patch-embedding stem, a CNN-style vision tower, anything 4D), put them in the AdamW group; don’t try to coerce a 4D tensor into Muon without thinking through the flattening and scaling explicitly.</p>

<p>For multi-teacher encoder distillation specifically, three points are worth highlighting. First, the per-teacher head MLPs are 2D — they go in the Muon group. The residual adapter design from earlier in this post is exactly the kind of architecture Muon handles cleanly: stacks of 2D linear projections (Muon group) interleaved with LayerNorms whose scalar gain/bias parameters go in the AdamW group. Second, the patch-embedding conv at the front of a ViT goes in AdamW; the cost is marginal because it’s a single small layer. Third, the consistent-RMS scaling matters most when you change architecture variants — MHA vs. GQA vs. MLA produce attention projection matrices of different shapes, and <code>match_rms_adamw</code> lets you swap variants without re-tuning the learning rate.</p>

<p>The honest summary: Muon is not magic, and there is no published encoder-distillation benchmark to quote a precise number against. In the language-model regime where the optimizer <em>has</em> been benchmarked, it reaches a given training loss roughly 1.35× faster than AdamW (Keller Jordan’s FineWeb speedrun) and similar order in the Moonlight ablations. Expect comparable but not identical gains for an encoder student — the more distinctively matrix-shaped your parameters, the better Muon does relative to AdamW. What it really buys you beyond wall-clock is <em>interpretability of the optimizer</em>: every step is the spectral-norm-steepest direction with a known, layer-shape-aware budget. When something goes wrong in distillation — head collapse, dense-probe regression, one teacher’s signal disappearing — you can rule out optimizer pathology cleanly, instead of wondering whether AdamW’s per-coordinate adaptive step sizes have implicitly absorbed one of the loss imbalances you were supposed to be controlling explicitly. That decoupling is the underrated reason to switch.</p>

<h2 id="evaluation-how-to-tell-if-the-student-actually-inherited-capability">Evaluation: how to tell if the student actually inherited capability</h2>

<p>A good encoder eval suite has three properties: it probes the <em>trunk</em> (not the distillation heads), it covers the axes the teachers were chosen for, and it includes at least one head-to-head with each teacher rather than just absolute numbers.</p>

<p>I think of it as four layers.</p>

<h3 id="1-teacher-faithfulness-probes">1. Teacher-faithfulness probes</h3>

<p>For each teacher $t$, fit a <em>fresh</em> linear or 2-layer MLP probe from the student’s trunk features to the teacher’s output, on held-out images. Report the cosine similarity (or feature-prediction R²) and compare it to a sanity baseline — typically the same probe fit on top of a randomly initialized backbone, and on top of the teacher itself (which should saturate). This isolates “did the trunk preserve the structure of teacher $t$” from “did the distillation head memorize a mapping.” If trunk-probe scores are far below the distillation-head scores you saw at train time, you have head collapse.</p>

<h3 id="2-frozen-feature-downstream-evals--the-standard-battery">2. Frozen-feature downstream evals — the standard battery</h3>

<p>Freeze the student trunk. Run the canonical probes:</p>

<ul>
  <li><strong>ImageNet-1k linear probe and kNN</strong> — the long-running sanity check. kNN especially is unforgiving of feature-space distortion.</li>
  <li><strong>VTAB-1k / VTAB-2</strong> — 19 diverse downstream tasks, low-shot. Catches representations that are over-tuned to ImageNet semantics.</li>
  <li><strong>Linear probe on iNaturalist, Places365, ObjectNet</strong> — fine-grained, scene, and distribution-shift respectively.</li>
  <li><strong>Detection:</strong> COCO with a frozen-backbone ViTDet or simple FPN head. Sensitive to spatial localization quality.</li>
  <li><strong>Dense prediction:</strong> the eval that tells you whether the student is <em>actually</em> an encoder rather than a fancy pooled embedding — covered in detail next.</li>
</ul>

<h4 id="dense-probing-in-detail">Dense probing, in detail</h4>

<p>This is the eval most worth understanding mechanically, because it’s where multi-teacher distillation usually wins or quietly fails, and because the word “dense” hides what’s actually happening.</p>

<p>A ViT turns an $H \times W$ image into an $h \times w$ grid of patch tokens (with patch size 14, a 518×518 image becomes a 37×37 grid of tokens — about 1,369 of them). A <em>dense linear probe</em> on ADE20K does this:</p>

<ol>
  <li>Freeze the backbone.</li>
  <li>Pass an image through and grab the per-patch token features $z_{i,j} \in \mathbb{R}^d$ for every patch $(i, j)$ in the grid.</li>
  <li>Apply a single 1×1 convolution (equivalently, a shared linear layer applied to each token independently) that maps $\mathbb{R}^d \rightarrow \mathbb{R}^{150}$ — one logit per ADE20K class, <em>per patch</em>.</li>
  <li>Bilinearly upsample those logits from the $h \times w$ grid back to $H \times W$ to produce a pixel-wise segmentation map.</li>
  <li>Train only the 1×1 conv against the ground-truth segmentation, evaluate mIoU.</li>
</ol>

<p>That is the entire decoder. No DPT, no UperNet, no FPN, no attention. The only learnable parameters are the per-class projection. Anything the predictor “knows” about object boundaries, stuff/things distinctions, or spatial layout has to already live inside the backbone’s per-patch features.</p>

<p>That is what “dense” means here: every patch token must independently carry enough signal to be classified into the right semantic class. Contrast this with ImageNet linear probing, which uses <em>one</em> feature vector per image (the CLS token or pooled output) and asks for <em>one</em> label. ImageNet linear probe rewards a backbone that produces a clean global summary; ADE20K dense linear probe rewards a backbone whose 1,369 individual patch features are each a clean local summary.</p>

<p>ADE20K is the canonical version of this test for three reasons. It has 150 classes covering both <em>things</em> (chair, person, lamp) and <em>stuff</em> (sky, road, sand), so the probe can’t shortcut by relying on object-centric cues. Scenes are cluttered and multi-object, so the per-patch features have to disambiguate locally rather than leaning on a single dominant subject. And the resolution is high enough (typically evaluated at 512+) that patch-grid quality at the boundaries of small objects actually shows up in the metric. Cityscapes and Pascal VOC are the standard companions; depth on NYUv2 / KITTI is the same idea but with a continuous target and a different failure mode (smoothness vs. sharpness at depth edges).</p>

<h4 id="siglip-2-vs-dinov3-under-dense-probing">SigLIP 2 vs. DINOv3 under dense probing</h4>

<p>These two families illustrate the gap perfectly, and the reason it matters for distillation choices.</p>

<p><strong>SigLIP 2</strong> is image-text contrastive (sigmoid loss, multilingual data). The training signal is global: a single image embedding is pulled toward its caption embedding. Patch tokens never receive a <em>local</em> learning signal — they only matter through the pooled embedding the contrastive loss sees. Empirically, SigLIP 2 is excellent on ImageNet linear probe, retrieval, and zero-shot classification, but its per-patch features carry mostly <em>image-level</em> semantics smeared across the grid. Run a dense linear probe on ADE20K and the features hold up only modestly; the gap to a self-supervised dense model is large, and it does not close at higher resolution.</p>

<p><strong>DINOv3</strong> is the opposite design choice. Self-distillation with a Gram-matrix regularizer that explicitly penalizes patch-feature collapse, trained at scale on curated images. Every patch token is forced into a representation that is locally consistent and discriminative against other patches. The published DINOv3 ViT-L hits about <strong>55.9 mIoU on ADE20K with just a linear dense probe</strong> — a number that would have required a full UperNet decoder a couple of years ago, and that comes within striking distance of fully fine-tuned state-of-the-art (~63 mIoU). It also outperforms PEspatial by ~6 points and AM-RADIOv2.5 by ~3 on the same probe.</p>

<p>For SigLIP 2 at comparable scale, the linear ADE20K number lands meaningfully lower — the DINOv3 paper and follow-ups put weakly-supervised contrastive models (SigLIP 2, PEcore) clearly behind on this benchmark, and the gap <em>grows</em> at higher input resolution because contrastive backbones produce patch features that don’t sharpen with more tokens, while DINO-style features do.</p>

<p>The takeaway for multi-teacher distillation is direct: if you only distill from SigLIP 2, no amount of clever loss design will produce strong ADE20K linear-probe numbers, because the teacher itself doesn’t have that signal to give. The whole point of pairing a contrastive teacher with a DINO-family teacher is that the latter supplies dense locality and the former supplies language-alignable semantics. Your dense probe on the resulting student is the cleanest test of whether that pairing actually transferred — if your AM-RADIO–style student lands close to DINOv3’s ADE20K number, the dense pathway worked; if it collapses toward SigLIP 2’s number, your distillation heads ate the locality signal and you have head collapse on the dense side.</p>

<h3 id="3-capability-matched-evals--one-per-teacher">3. Capability-matched evals — one per teacher</h3>

<p>Generic benchmarks miss the point of distilling a <em>specific</em> teacher. Add one targeted eval per teacher:</p>

<ul>
  <li><strong>CLIP / SigLIP teachers</strong> → zero-shot retrieval and classification through the student’s CLIP-aligned head on COCO/Flickr30k retrieval and on ImageNet zero-shot. Compare to the original teacher at matched compute.</li>
  <li><strong>DINOv2 teacher</strong> → unsupervised dense correspondence on SPair-71k or PF-Pascal, and overclustering / k-means purity on ImageNet — both stress the cleanliness of patch features.</li>
  <li><strong>SAM teacher</strong> → mask quality with a fixed mask decoder driven by the student’s encoder, evaluated on SA-1B held-out and COCO panoptic.</li>
  <li><strong>MAE teacher</strong> → hold-one-out reconstruction and linear-probe on low-data regimes (1%, 10% ImageNet).</li>
</ul>

<p>This is also where you check the <em>amalgamation</em> hypothesis: a student that genuinely combined teachers should match each teacher on its home turf. If the CLIP eval drops sharply, you didn’t really distill CLIP — you distilled “things that look CLIP-like in the head.”</p>

<h3 id="4-robustness-calibration-and-efficiency">4. Robustness, calibration, and efficiency</h3>

<p>The final layer is the one papers under-report. Run the student through ImageNet-A, ImageNet-R, ImageNet-Sketch, and ObjectNet to check shift robustness. Measure expected calibration error after the linear probe. And quote real wall-clock numbers: throughput at the deployed resolution, parameter count, and FLOPs at the resolutions you actually serve, not at training resolution. A 10% gain that costs 3× compute is not a win.</p>

<h2 id="reading-the-numbers-honestly">Reading the numbers honestly</h2>

<p>A few habits that prevent self-deception:</p>

<p>Always report teacher numbers at the <em>student’s compute budget</em>. Comparing a ViT-B student against a ViT-L teacher and declaring victory because the student is “close” elides the fact that you should be comparing to a from-scratch ViT-B trained the same way. Run that baseline.</p>

<p>Look at <em>gaps</em>, not levels. Distillation lifts every metric a bit; what matters is whether the student is closer to its teacher on dense tasks than a vanilla ViT-B is to that teacher.</p>

<p>Track <strong>dispersion across seeds and probes</strong>. Encoder evals have surprisingly high variance — linear probes on small VTAB tasks can move 1–2 points across seeds. A 0.5-point improvement on one benchmark is noise.</p>

<p>Do at least one <strong>adversarial eval the student wasn’t selected for</strong> — e.g., depth estimation if you only optimized for segmentation. This is the closest thing we have to a held-out test of generality.</p>

<h2 id="closing">Closing</h2>

<p>Multi-teacher encoder distillation is one of the few places in deep learning where architectural choices, loss design, and evaluation methodology are tightly coupled: a clever loss looks like a win until you probe the trunk and discover the heads ate the gain. The discipline is to pair each teacher you add with a capability-matched eval that measures whether the <em>trunk</em> — not the distillation pipeline — actually inherited the thing you wanted. Do that, and the resulting student is genuinely a single backbone that punches above its weight; skip it, and you’ve trained a very expensive set of projection heads.</p>]]></content><author><name>Tianshu Yu</name></author><category term="machine-learning" /><category term="vision" /><category term="distillation" /><category term="Other" /><summary type="html"><![CDATA[A practitioner’s view on multi-teacher distillation for general-purpose visual representations, and the evaluation suite that should follow it.]]></summary></entry><entry><title type="html">LLaVA-KD: Distilling Multimodal Large Language Models</title><link href="https://tianshu-michael-yu.github.io/2026/03/29/llava-kd-distilling-multimodal-llms.html" rel="alternate" type="text/html" title="LLaVA-KD: Distilling Multimodal Large Language Models" /><published>2026-03-29T00:00:00+00:00</published><updated>2026-03-29T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2026/03/29/llava-kd-distilling-multimodal-llms</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2026/03/29/llava-kd-distilling-multimodal-llms.html"><![CDATA[<p>Multimodal large language models (MLLMs) like LLaVA combine a vision encoder with a language model to handle image-text tasks. The performance scales with the size of the language backbone, but so do the compute and memory requirements. LLaVA-KD (Cai et al., ICCV 2025) asks a natural question: can we transfer the capabilities of a large MLLM into a small one through knowledge distillation, rather than training the small model from scratch?</p>

<p>The answer turns out to be yes, but the distillation requires more care than simply applying KL divergence on output logits. LLaVA-KD introduces a three-stage training pipeline and two distillation objectives that operate on different parts of the model’s representations. This post walks through the framework, examines the loss functions, and highlights some implicit assumptions in the design.</p>

<h2 id="the-architecture">The Architecture</h2>

<p>Both the teacher (large MLLM, or l-MLLM) and the student (small MLLM, or s-MLLM) share the same high-level architecture: a vision encoder, a connector (MLP projector), and a language model. The vision encoder is a SigLIP model (siglip-so400m-patch14-384) shared across all variants. The connector maps visual features from the encoder’s output space into the LLM’s embedding space. The language models differ in size but come from the same family — for example, Qwen2.5-3B as the teacher and Qwen2.5-0.5B as the student.</p>

<p>The image processing pipeline works as follows. An image is passed through the vision encoder to produce a sequence of patch features. These features are projected by the connector into the same dimensionality as the LLM’s token embeddings. The projected visual tokens are then interleaved with the text token embeddings at the position of a special image placeholder token. The LLM processes this combined sequence autoregressively, attending over both visual and textual tokens.</p>

<h2 id="the-three-stage-training-pipeline">The Three-Stage Training Pipeline</h2>

<p>LLaVA-KD organizes training into three stages. Each stage has a specific purpose and uses a different combination of losses.</p>

<h3 id="stage-1-distilled-pre-training-dpt">Stage 1: Distilled Pre-Training (DPT)</h3>

<p>The first stage aligns visual and linguistic representations in the student model. Despite the name “pre-training,” this is not unsupervised next-token prediction over raw text. The data consists of image-caption pairs, where the model receives an image plus a text prompt, and the target is the caption or description. The prompt and visual tokens are masked out (set to the ignore index $-100$), and only the caption tokens receive supervision.</p>

<p>During DPT, the student trains with a combination of the standard cross-entropy loss on ground-truth caption tokens and a distillation loss that aligns the student’s output distribution with the teacher’s. The cross-entropy loss serves as an anchor: it ensures the student learns the correct mapping from visual inputs to textual outputs, not just a smoothed approximation of the teacher’s predictions. The teacher model is imperfect, and its soft distribution may spread probability mass over plausible-but-wrong tokens. Without the hard-label grounding, the student would faithfully replicate these errors.</p>

<h3 id="stage-2-supervised-fine-tuning-sft">Stage 2: Supervised Fine-Tuning (SFT)</h3>

<p>The second stage is standard SFT on instruction-following data — image-question-answer triples. This stage equips the student with the ability to follow instructions and produce structured responses. No distillation loss is applied here; the model trains with cross-entropy on the response tokens alone.</p>

<h3 id="stage-3-distilled-fine-tuning-dft">Stage 3: Distilled Fine-Tuning (DFT)</h3>

<p>The third stage reintroduces distillation after SFT. The student has now learned the task format, so the distillation objective can refine its knowledge without interfering with instruction-following capability. This stage applies the full suite of distillation losses described below.</p>

<h2 id="multimodal-distillation-mdist">Multimodal Distillation (MDist)</h2>

<p>MDist transfers the teacher’s output distribution to the student at the logit level. The implementation uses KL divergence between the teacher’s and student’s softmax distributions, applied in two places.</p>

<h3 id="response-token-distillation">Response-Token Distillation</h3>

<p>For the response portion of the sequence (tokens where the label is not $-100$), the loss is a forward KL divergence:</p>

\[\mathcal{L}_{\text{resp}} = D_{\text{KL}}\!\left( \sigma(\mathbf{z}^T) \;\|\; \sigma(\mathbf{z}^S) \right) = \sum_k \sigma(\mathbf{z}^T)_k \log \frac{\sigma(\mathbf{z}^T)_k}{\sigma(\mathbf{z}^S)_k}\]

<p>where $\sigma(\mathbf{z}^T)$ and $\sigma(\mathbf{z}^S)$ are the softmax distributions of the teacher and student logits respectively, and $k$ ranges over the vocabulary. This loss is computed only over masked response positions, meaning the student is trained to match the teacher’s full predictive distribution — not just the argmax — on the tokens that matter for downstream performance.</p>

<h3 id="visual-position-distillation">Visual-Position Distillation</h3>

<p>A clarification on terminology is useful here. “Visual tokens” are not part of the text vocabulary — they are continuous embeddings produced by the vision encoder and projected into the LLM’s embedding space by the connector. The LLM cannot sample or output a visual token. At every sequence position, including positions occupied by visual embeddings, the LLM produces logits over the standard text vocabulary. During normal training these positions are masked ($-100$) and do not contribute to the cross-entropy loss.</p>

<p>However, the teacher’s text-vocabulary logits at visual positions still encode useful information about how the teacher processes visual inputs internally. MDist exploits this by applying KL divergence on the LLM’s output logits at these positions:</p>

\[\mathcal{L}_{\text{vis}} = D_{\text{KL}}\!\left( \sigma(\mathbf{z}^T_{\text{img}}) \;\|\; \sigma(\mathbf{z}^S_{\text{img}}) \right)\]

<p>where $\mathbf{z}^T_{\text{img}}$ and $\mathbf{z}^S_{\text{img}}$ are the teacher’s and student’s text-vocabulary logits at the 728 sequence positions corresponding to the SigLIP output patches. This encourages the student’s language model to develop similar internal processing patterns for visual information, even at positions where no ground-truth text supervision exists.</p>

<h2 id="relation-distillation-rdist">Relation Distillation (RDist)</h2>

<p>RDist captures a different kind of knowledge: the structural relationships among visual positions. Rather than aligning individual output distributions, it aligns the pairwise interaction pattern across all positions occupied by visual embeddings.</p>

<p>Given the teacher’s text-vocabulary logits at the visual positions $\mathbf{Z}^T_{\text{img}} \in \mathbb{R}^{N_v \times V}$ and the student’s $\mathbf{Z}^S_{\text{img}} \in \mathbb{R}^{N_v \times V}$ (where $N_v = 728$ is the number of visual positions and $V$ is the vocabulary size), the relation matrices are:</p>

\[\mathbf{R}^T = \mathbf{Z}^T_{\text{img}} (\mathbf{Z}^T_{\text{img}})^\top, \qquad \mathbf{R}^S = \mathbf{Z}^S_{\text{img}} (\mathbf{Z}^S_{\text{img}})^\top\]

<p>Each entry $\mathbf{R}_{ij}$ is the dot product between the logit vectors at positions $i$ and $j$, capturing how similarly the model treats two visual patches in output space. The distillation loss is the cosine distance between the flattened relation matrices:</p>

\[\mathcal{L}_{\text{rela}} = 1 - \cos\!\left( \text{vec}(\mathbf{R}^T),\; \text{vec}(\mathbf{R}^S) \right)\]

<p>This loss does not require the absolute magnitudes of the logits to match — only their relative geometry. Two patches that the teacher considers similar (high dot product) should also be considered similar by the student, and vice versa. This is useful because the teacher and student have different capacity, so their raw logit scales may differ, but the relational structure can be preserved.</p>

<h2 id="the-combined-objective">The Combined Objective</h2>

<p>During the distillation stages (DPT and DFT), the total loss for a sample containing one image is:</p>

\[\mathcal{L} = \mathcal{L}_{\text{CE}} + \mathcal{L}_{\text{resp}} + \mathcal{L}_{\text{vis}} + \mathcal{L}_{\text{rela}}\]

<p>where \(\mathcal{L}_{\text{CE}}\) is the standard autoregressive cross-entropy loss. For text-only samples (no image), only \(\mathcal{L}_{\text{CE}} + \mathcal{L}_{\text{resp}}\) is used, since there are no visual tokens to distill.</p>

<h2 id="the-shared-tokenizer-assumption">The Shared Tokenizer Assumption</h2>

<p>An important implicit assumption in LLaVA-KD is that the teacher and student must share the same tokenizer and vocabulary. This is not stated explicitly in the paper, but it is a hard requirement of the implementation.</p>

<p>The logit-level KL divergence computes $D_{\text{KL}}(\sigma(\mathbf{z}^T) | \sigma(\mathbf{z}^S))$ where both $\mathbf{z}^T$ and $\mathbf{z}^S$ have dimension $V$ (the vocabulary size). Each index $k$ in the sum $\sum_k$ must refer to the same token for the comparison to be meaningful. If the teacher used one tokenizer and the student another, index 1042 might mean “the” for one model and “cat” for the other — the KL divergence would be nonsensical.</p>

<p>The code confirms this: both models receive identical <code>input_ids</code> prepared by a single tokenizer (the student’s), and the trainer checks <code>masked_teacher_logits.shape == masked_student_logits.shape</code> before computing the loss. If the shapes mismatch, it falls back to the CE loss alone, effectively skipping distillation.</p>

<p>In practice, this means the teacher and student must come from the same LLM family. The released checkpoints use Qwen2.5-3B $\to$ Qwen2.5-0.5B and Qwen1.5 variants, all of which share the same tokenizer. If you wanted to distill from, say, a LLaMA-based teacher to a Qwen student, you would need to replace the logit-level losses with something tokenizer-agnostic, such as MSE on projected hidden states.</p>

<h2 id="relation-to-standard-knowledge-distillation">Relation to Standard Knowledge Distillation</h2>

<p>It is worth comparing LLaVA-KD’s approach with the original knowledge distillation framework from Hinton et al. (2015). In the classic setup, the loss is:</p>

\[\mathcal{L} = (1 - \alpha) \cdot \mathcal{L}_{\text{CE}}(y, \sigma(\mathbf{z}^S)) + \alpha \cdot T^2 \cdot D_{\text{KL}}\!\left( \sigma(\mathbf{z}^T / T) \;\|\; \sigma(\mathbf{z}^S / T) \right)\]

<p>where $T$ is a temperature parameter that softens both distributions and $\alpha$ balances the two terms. LLaVA-KD simplifies this: there is no temperature scaling (equivalently, $T = 1$) and the losses are summed with equal weight ($\alpha = 0.5$ effectively). The key innovations are the visual-token distillation and the relational loss, neither of which exist in classical KD, since standard distillation assumes a single output per sample rather than a sequence of heterogeneous tokens mixing visual and textual modalities.</p>

<h2 id="results">Results</h2>

<p>LLaVA-KD-1B (using Qwen2.5-0.5B as the student backbone) outperforms several much larger models including BLIP2-13B and InstructBLIP-7B across five multimodal benchmarks. The 1.8B variant further closes the gap with the 3B teacher. The distillation stages contribute complementary gains: DPT improves the base representations, SFT teaches the task format, and DFT refines the student’s knowledge with the teacher’s soft labels.</p>

<p>The relational distillation loss (RDist) provides consistent improvements over MDist alone, suggesting that the pairwise structure among visual tokens carries information that pointwise logit matching misses. This makes sense intuitively — understanding that “the dog’s ear” and “the dog’s tail” are related (both parts of the same object) is different from correctly predicting the next token given either patch.</p>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[Multimodal large language models (MLLMs) like LLaVA combine a vision encoder with a language model to handle image-text tasks. The performance scales with the size of the language backbone, but so do the compute and memory requirements. LLaVA-KD (Cai et al., ICCV 2025) asks a natural question: can we transfer the capabilities of a large MLLM into a small one through knowledge distillation, rather than training the small model from scratch?]]></summary></entry><entry><title type="html">From Entropy to Epiplexity: Why Shannon Information Theory Misleads Us About Learning</title><link href="https://tianshu-michael-yu.github.io/machine-learning/information-theory/deep-learning/2026/03/16/epiplexity.html" rel="alternate" type="text/html" title="From Entropy to Epiplexity: Why Shannon Information Theory Misleads Us About Learning" /><published>2026-03-16T00:00:00+00:00</published><updated>2026-03-16T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/machine-learning/information-theory/deep-learning/2026/03/16/epiplexity</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/machine-learning/information-theory/deep-learning/2026/03/16/epiplexity.html"><![CDATA[<p><em>A deep dive into a new information measure — epiplexity — that separates learnable structure from incompressible noise, and explains paradoxes that classical information theory cannot.</em></p>

<hr />

<p>Shannon information theory has been the backbone of how we think about data, compression, and communication for over 75 years. But a new paper by Marc Finzi, Shikai Qiu, Yiding Jiang, Pavel Izmailov, J. Zico Kolter, and Andrew Gordon Wilson — <a href="https://arxiv.org/abs/2601.03220"><em>“From Entropy to Epiplexity”</em></a> — argues that when it comes to <strong>learning</strong>, Shannon’s framework is fundamentally misleading.</p>

<p>The core problem: Shannon entropy treats all bits equally. A random bit and a structured bit count the same. But for a learner with limited compute — like a neural network, or a human brain — these are wildly different. One carries learnable structure, the other is just noise. The paper introduces <strong>epiplexity</strong> (epistemic complexity) to formalize this distinction.</p>

<hr />

<h2 id="three-paradoxes-that-break-classical-information-theory">Three Paradoxes That Break Classical Information Theory</h2>

<p>The paper builds its case around three observations that seem paradoxical under standard information theory but are perfectly natural once you account for computational constraints.</p>

<h3 id="paradox-1-deterministic-transformations-cant-create-information-but-they-do">Paradox 1: Deterministic Transformations Can’t Create Information… But They Do</h3>

<p>Classical theory says that a deterministic function $f$ can never increase information: $K(f(x)) \leq K(x) + K(f)$. The output is always “simpler” than the input plus the description of the function. This is a theorem — it’s true.</p>

<p>And yet: AlphaZero starts from random play and, through purely deterministic self-play, generates chess strategies that took humanity centuries to discover. Synthetic data pipelines create training examples that improve model performance. How?</p>

<p><strong>The resolution:</strong> Classical information theory assumes unbounded computation. A cryptographically secure pseudorandom number generator (CSPRNG) maps a short seed $k$ to a long string $G(U_k)$ that <em>looks</em> random to any polynomial-time observer. In classical terms, the output has low Kolmogorov complexity (it’s just “run $G$ on seed $k$”). But no efficient algorithm can distinguish it from true randomness — so for any bounded learner, the output carries genuinely new entropy.</p>

<p>The paper formalizes this: for a CSPRNG with advantage $\varepsilon(k)$,</p>

\[H_{\text{Poly}}(G(U_k)) &gt; H_{\text{Poly}}(U_k) + n - n\varepsilon(k) - k - O(1)\]

<p>Deterministic computation <strong>does</strong> create information — time-bounded information. The illusion that it can’t comes from assuming observers have unlimited compute.</p>

<h3 id="paradox-2-data-ordering-shouldnt-matter-but-it-does">Paradox 2: Data Ordering Shouldn’t Matter… But It Does</h3>

<p>Shannon entropy $H(X, Y) = H(Y, X)$. Kolmogorov complexity is symmetric up to a constant: $K(x, y) = K(y, x) + O(\log n)$. Information content doesn’t depend on which direction you read the data.</p>

<p>But anyone who has trained a language model knows: text processed left-to-right yields dramatically better models than text processed right-to-left (or randomly shuffled). Curriculum learning — feeding easy examples before hard ones — consistently helps. If information is order-independent, why?</p>

<p><strong>The resolution:</strong> In the time-bounded setting, computing $G$ forward might be easy (polynomial time), but inverting $G^{-1}$ might be intractable. The symmetry $K(G) = K(G^{-1})$ holds with unbounded compute, but $K_T(G) \neq K_T(G^{-1})$ in general. Data ordering determines which structures become learnable within a fixed compute budget. The directionality is real — it’s just invisible to classical information theory.</p>

<h3 id="paradox-3-likelihood-models-cant-beat-the-data-generator-but-they-can">Paradox 3: Likelihood Models Can’t Beat the Data Generator… But They Can</h3>

<p>If your data comes from distribution $P^<em>$, then $P^</em>$ minimizes expected log-loss: $\mathbb{E}<em>{P^*}[-\log P(X)] \geq \mathbb{E}</em>{P^<em>}[-\log P^</em>(X)]$ for all $P$. No model should do better than the true generator. So likelihood models should, at best, replicate the generator — never discovering anything “new.”</p>

<p>But this is obviously wrong in practice. Conway’s Game of Life is generated by trivial local rules on a grid. Yet trained models discover gliders, oscillators, and complex emergent structures that are nowhere in the generating rule set. Language models discover grammar, semantics, and reasoning from next-token prediction on web text.</p>

<p><strong>The resolution:</strong> The generating process may be simple (constant-time per step), but a polynomial-time observer can discover hierarchical patterns that compress the data more efficiently than the generator itself. The model isn’t beating the generator at its own game — it’s playing a different game, one where bounded computation discovers emergent structure that the simple generator never represented explicitly.</p>

<hr />

<h2 id="what-is-epiplexity">What Is Epiplexity?</h2>

<p>The central definition is elegant. Given a time-bounded model class $\mathcal{P}_T$ (programs that run in time $T$), find the optimal program $P^*$ minimizing:</p>

\[|P| + \mathbb{E}[\log \frac{1}{P(X)}]\]

<p>This is a minimum description length (MDL) decomposition. The first term is the program’s length; the second is how well it compresses the data. The optimal $P^*$ gives us two quantities:</p>

<ul>
  <li>
    <table>
      <tbody>
        <tr>
          <td><strong>Epiplexity</strong> $S_T(X) =</td>
          <td>P^*</td>
          <td>$ — the length of the optimal program. This is the <strong>learnable structural content</strong> of the data.</td>
        </tr>
      </tbody>
    </table>
  </li>
  <li><strong>Time-Bounded Entropy</strong> $H_T(X) = \mathbb{E}[\log \frac{1}{P^*(X)}]$ — the residual loss. This is the <strong>unlearnable random content</strong>.</li>
</ul>

<p>The key insight: classical entropy conflates these two. A dataset of random noise and a dataset of structured text might have the same Shannon entropy, but they have completely different epiplexity. The structured text has high epiplexity (lots of learnable patterns) and moderate time-bounded entropy. The noise has near-zero epiplexity and maximal time-bounded entropy.</p>

<hr />

<h2 id="csprngs-the-perfect-litmus-test">CSPRNGs: The Perfect Litmus Test</h2>

<p>The paper validates epiplexity against a known ground truth: cryptographically secure pseudorandom generators. We <em>know</em> CSPRNG output has structure (it’s generated from a short seed) but that structure is computationally inaccessible to efficient observers. The theory should predict: <strong>high time-bounded entropy, near-zero epiplexity.</strong></p>

<p>And it does. Theorem 9 shows:</p>

\[S_T(G(U_k)) \leq c + n\varepsilon(k) \approx 0\]

\[H_T(G(U_k)) \approx n\]

<p>CSPRNG output has essentially no learnable structure and maximal (time-bounded) randomness. Classical Kolmogorov complexity would say the opposite — the output is highly compressible (just store the seed). Epiplexity gets it right; classical theory gets it wrong.</p>

<hr />

<h2 id="cellular-automata-a-beautiful-illustration">Cellular Automata: A Beautiful Illustration</h2>

<p>The paper uses Wolfram’s elementary cellular automata to demonstrate the three types of data:</p>

<table>
  <thead>
    <tr>
      <th>Rule</th>
      <th>Behavior</th>
      <th>Epiplexity $S_T$</th>
      <th>Time-Bounded Entropy $H_T$</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Rule 15</td>
      <td>Stable/repetitive</td>
      <td>Low</td>
      <td>Low</td>
    </tr>
    <tr>
      <td>Rule 30</td>
      <td>Chaotic</td>
      <td>Low</td>
      <td>High</td>
    </tr>
    <tr>
      <td>Rule 54</td>
      <td>Complex</td>
      <td><strong>High</strong></td>
      <td>Moderate</td>
    </tr>
  </tbody>
</table>

<p><strong>Rule 15</strong> produces repetitive, trivially predictable patterns — low on both dimensions. <strong>Rule 30</strong> produces chaotic output that is essentially pseudorandom — high entropy but nothing to learn. <strong>Rule 54</strong> is the interesting one: it produces complex, structured patterns (like Class IV automata generally do) that contain genuine learnable information.</p>

<p>When you train neural networks on these three rules, the loss curves tell the story: Rule 15 converges instantly, Rule 30 barely improves beyond random guessing, and Rule 54 shows sustained improvement — the model keeps discovering new structure. That sustained improvement <em>is</em> the epiplexity being extracted.</p>

<hr />

<h2 id="measuring-epiplexity-in-practice">Measuring Epiplexity in Practice</h2>

<p>The definition is clean but not directly computable (it requires optimizing over all time-bounded programs). The paper proposes two practical approximations:</p>

<h3 id="prequential-coding">Prequential Coding</h3>

<p>Train a model sequentially on a data stream, accumulating the loss reduction over time. The epiplexity is approximately the <strong>area under the loss curve above the final loss</strong>:</p>

\[|P_{\text{preq}}| \approx \sum_i \left(\log \frac{1}{P_i(Z_i)} - \log \frac{1}{P_M(Z_i)}\right)\]

<p>This is computationally cheap — you just need a training run and its loss curve.</p>

<h3 id="requential-coding">Requential Coding</h3>

<p>Use a trained “teacher” model to generate synthetic data, then train a “student” from scratch on it. The epiplexity is the <strong>area between the teacher and student loss curves</strong>:</p>

\[|P_{\text{req}}| = \sum_i \text{KL}(P_i^t \| P_i^s)\]

<p>This is more rigorous (it gives explicit runtime guarantees) but 2-10x more expensive.</p>

<p>Both methods correlate well in practice, and the paper shows they produce consistent rankings across datasets.</p>

<hr />

<h2 id="why-this-matters-data-selection-over-model-selection">Why This Matters: Data Selection Over Model Selection</h2>

<p>The deepest practical implication of epiplexity is a shift in focus from <strong>model selection</strong> to <strong>data selection</strong>. Classical MDL tells you which model to pick for a given dataset. Epiplexity tells you which <strong>dataset</strong> to pick for a given compute budget.</p>

<p>This is exactly the problem that matters in the era of large-scale pretraining. Everyone is using roughly the same architectures (Transformers). The differentiator is data — its quality, its ordering, its composition. Epiplexity provides a principled, task-agnostic measure of how much learnable structure a dataset contains.</p>

<p>The paper shows that epiplexity rankings across datasets correlate with downstream task performance — even for tasks the model was never trained on. High-epiplexity data produces models that generalize better, not because it teaches specific skills, but because it contains more extractable structure per compute dollar.</p>

<hr />

<h2 id="scaling-behavior">Scaling Behavior</h2>

<p>Under standard neural scaling law assumptions:</p>

<ul>
  <li><strong>Epiplexity grows with compute budget $T$</strong>: more compute lets you discover more structure.</li>
  <li><strong>Time-bounded entropy decreases with $T$</strong>: more compute lets you predict more of the “random” component.</li>
  <li><strong>Per-token entropy decreases with dataset size</strong>: larger datasets have more redundancy to exploit.</li>
</ul>

<p>This aligns with the empirical observation that scaling compute and data simultaneously produces the best models — you’re increasing both the amount of structure available (more data → more epiplexity) and the ability to extract it (more compute → lower time-bounded entropy).</p>

<hr />

<h2 id="key-takeaways">Key Takeaways</h2>

<ol>
  <li>
    <p><strong>Shannon entropy is the wrong measure for learning.</strong> It conflates learnable structure with incompressible noise. Two datasets with the same entropy can have wildly different learning value.</p>
  </li>
  <li>
    <p><strong>Computation creates information.</strong> This sounds impossible under classical theory, but it’s perfectly natural when you account for bounded compute. AlphaZero, synthetic data, and data augmentation all exploit this.</p>
  </li>
  <li>
    <p><strong>Data ordering matters — formally.</strong> Not just as a training heuristic, but as a fundamental property of time-bounded information. Curriculum learning has theoretical backing.</p>
  </li>
  <li>
    <p><strong>Models can discover structure the data generator never represented.</strong> Emergence isn’t just a buzzword — it’s a consequence of polynomial-time observers finding patterns that constant-time generators can’t.</p>
  </li>
  <li>
    <p><strong>Epiplexity is a foundation for data-centric AI.</strong> As the field shifts from “which model” to “which data,” having a principled measure of data quality that doesn’t require downstream evaluation could be transformative.</p>
  </li>
</ol>

<hr />

<h2 id="final-thoughts">Final Thoughts</h2>

<p>This paper does something rare: it identifies fundamental limitations in a framework we’ve been using for decades and proposes a replacement that is both theoretically grounded and practically measurable. The three paradoxes are compelling, the resolution is elegant, and the experimental validation — from cellular automata to chess to natural language — is thorough.</p>

<p>The biggest open question is how epiplexity measurements will scale to frontier model training. The measurement procedures require training runs, which are expensive at scale. But even approximate rankings could be enormously valuable for data curation decisions that currently rely on heuristics and intuition.</p>

<p>If you work on data selection, curriculum learning, or synthetic data generation, this paper is essential reading. It provides the theoretical vocabulary for what practitioners have long felt intuitively: not all bits are created equal.</p>

<hr />

<p><em>Paper: <a href="https://arxiv.org/abs/2601.03220">From Entropy to Epiplexity: Rethinking Information for Computationally Bounded Intelligence</a> by Finzi, Qiu, Jiang, Izmailov, Kolter, and Wilson (2026).</em></p>]]></content><author><name>Tianshu Yu</name></author><category term="machine-learning" /><category term="information-theory" /><category term="deep-learning" /><category term="Other" /><summary type="html"><![CDATA[A deep dive into a new information measure — epiplexity — that separates learnable structure from incompressible noise, and explains paradoxes that classical information theory cannot.]]></summary></entry><entry><title type="html">Why Router-Replay Is a Critical Fix for Training MoE Language Models with RL</title><link href="https://tianshu-michael-yu.github.io/2026/03/02/router-replay.html" rel="alternate" type="text/html" title="Why Router-Replay Is a Critical Fix for Training MoE Language Models with RL" /><published>2026-03-02T00:00:00+00:00</published><updated>2026-03-02T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2026/03/02/router-replay</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2026/03/02/router-replay.html"><![CDATA[<p><em>A look at why the routing mechanism in Mixture-of-Experts models breaks standard reinforcement learning — and how a deceptively simple idea called Router-Replay (R3) fixes it.</em></p>

<hr />

<p>Reinforcement learning has become the secret sauce behind some of the most capable AI models we’ve seen recently. From OpenAI’s o-series to DeepSeek-R1, RL fine-tuning is how raw language models are turned into reasoning powerhouses. But there’s a quiet, underappreciated problem lurking when you try to apply RL to the fastest and most efficient class of modern models: <strong>Mixture-of-Experts (MoE) architectures</strong>.</p>

<p>A paper published in October 2025 by Wenhan Ma and colleagues — <em>“Stabilizing MoE Reinforcement Learning by Aligning Training and Inference Routers”</em> — puts a name to this problem and offers a clean, elegant fix. The fix is called <strong>Rollout Routing Replay</strong>, or <strong>R3</strong>. And once you understand why it’s necessary, you’ll wonder how anyone was training MoE models with RL without it.</p>

<hr />

<h2 id="a-quick-primer-what-makes-moe-models-special-and-tricky">A Quick Primer: What Makes MoE Models Special (and Tricky)</h2>

<p>Most large language models are “dense” — every parameter participates in every computation. Mixture-of-Experts models take a different approach: they have many specialized sub-networks (called “experts”), but only a small subset of them activate for any given token. A lightweight <strong>router</strong> network decides, for each token, which experts should handle it.</p>

<p>This design is brilliant from an efficiency standpoint. Models like DeepSeek V3, Qwen3-MoE, and Mixtral can have hundreds of billions of parameters while only activating a fraction of them per token, making inference much cheaper than equivalently-capable dense models.</p>

<p>But this architectural cleverness introduces a subtle and dangerous complication when you try to apply reinforcement learning.</p>

<hr />

<h2 id="the-problem-two-different-routers-two-different-worlds">The Problem: Two Different Routers, Two Different Worlds</h2>

<p>When you train a language model with RL — say, using GRPO or PPO — the process looks roughly like this:</p>

<ol>
  <li><strong>Rollout phase</strong>: The model generates responses to prompts. This runs on an <em>inference engine</em> (like vLLM or SGLang), optimized for fast text generation.</li>
  <li><strong>Training phase</strong>: The model computes log-probabilities for those same generated responses, and the RL algorithm uses them to update the model’s weights.</li>
</ol>

<p>In a dense model, these two phases are essentially equivalent. If you feed the same tokens through the model twice, you get the same probabilities. The math works out cleanly.</p>

<p>In an MoE model, something goes wrong. When you feed the same token through the model during training, <strong>the router doesn’t necessarily pick the same experts it picked during inference</strong>. And if different experts are activated, you get different hidden states, different output logits, and crucially — <strong>different token probabilities</strong>.</p>

<p>This discrepancy has two sources:</p>

<p><strong>Nondeterminism in Top-K routing.</strong> Most MoE routers select the top-K experts by score for each token. When two experts have very similar scores, which one “wins” can depend on floating-point precision, GPU parallelism implementation details, and the specific order of operations. The training engine and inference engine are typically separate systems with different implementations — so even for identical inputs, they can make different routing decisions.</p>

<p><strong>Architectural separation.</strong> Inference engines are heavily optimized for throughput and latency. They often use different fused kernels, different precision modes, and different batching strategies than the training engine. These differences compound the routing divergence.</p>

<p>The result is that the probabilities the training engine computes for tokens are <em>different</em> from the probabilities that actually generated those tokens during rollout. And this mismatch is not small — the paper shows that it can cause dramatically divergent token probability ratios, with many tokens exhibiting extreme probability discrepancies between the two phases.</p>

<p>We can quantify how much of this KL divergence comes from routing specifically by comparing dense and MoE models on the same FSDP2 + vLLM stack:</p>

<table>
  <thead>
    <tr>
      <th>Model</th>
      <th>Baseline KL</th>
      <th>With R3</th>
      <th>Interpretation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>LFM 1.2B Dense</td>
      <td>~0.003</td>
      <td>—</td>
      <td>Framework noise floor</td>
    </tr>
    <tr>
      <td>LFM MoE 8B</td>
      <td>~0.01–0.02</td>
      <td>~0.004–0.007</td>
      <td>R3 brings MoE down toward dense floor</td>
    </tr>
    <tr>
      <td>Qwen 30B MoE</td>
      <td>~0.003–0.004</td>
      <td>~0.001</td>
      <td>Baseline already near dense floor</td>
    </tr>
  </tbody>
</table>

<p>The dense model establishes a <strong>framework noise floor</strong> (~0.003 nats) — irreducible KL from numerical differences between FSDP2 and vLLM unrelated to routing. LFM MoE 8B sits 3–6x above this floor, confirming the excess KL comes from routing disagreements. Interestingly, Qwen 30B MoE’s baseline KL is already near the dense floor, suggesting its routing is more deterministic across frameworks — R3’s benefit is model-dependent.</p>

<hr />

<h2 id="why-this-breaks-rl-training">Why This Breaks RL Training</h2>

<p>RL algorithms like PPO and GRPO use something called an <strong>importance sampling ratio</strong> — essentially the ratio of the model’s <em>current</em> probability for a token to the <em>old</em> probability from when the rollout was generated. This ratio tells the algorithm how much to trust each training example. If the ratio is close to 1, the distribution hasn’t changed much and the gradient update is reliable. If the ratio is extreme — say, 10x or 0.1x — something has gone very wrong.</p>

<p>In practice, RL algorithms clip this ratio (typically in the range [0.8, 1.2] or similar) to prevent catastrophically large gradient updates. This is the “trust region” concept at the heart of PPO.</p>

<p>Here’s the problem: in MoE models, the routing mismatch can push these importance sampling ratios to extreme values <em>before any learning even happens</em>, just from the discrepancy between the inference and training routers. From the algorithm’s perspective, it looks like the model has already changed dramatically from the rollout policy — so either the gradients get clipped into meaninglessness, or (if clipping isn’t aggressive enough) the training is hit with enormous, destabilizing updates.</p>

<p>This effect is especially dangerous with <strong>multi mini-step training</strong> — where you take multiple gradient steps per rollout batch (<code>ppo_mini_batch_size &lt; train_batch_size</code>). Each mini-step shifts the policy further from the rollout distribution, and routing errors compound on top of that drift. We trained an LFM MoE 8B model on multi-turn GSM8K with 4 mini-steps per rollout, and the KL divergence between rollout and training tells the story clearly:</p>

<p><img src="/img/rollout_corr_kl_lfm_moe_baseline_vs_r3_comparison.png" alt="Rollout KL comparison — baseline vs R3" />
<em>Baseline KL fluctuates at 0.008–0.015 with spikes to 0.02; R3 holds steady at 0.003–0.005.</em></p>

<p>In severe cases, this leads to <strong>catastrophic training collapse</strong>. Running the same configuration to 3,000 steps, the baseline enters a feedback loop — routing errors produce incorrect gradients, which destabilize weights, which cause even worse routing, which produces even larger errors — until the model irreversibly degenerates:</p>

<p><img src="/img/lfm_moe_3k_steps_grad_norm_compr.png" alt="3k steps grad norm — baseline explodes" />
<em>Baseline gradient norms begin spiking around step 2k and explode to 4000+ by step 2.5k. R3 remains flat near zero throughout.</em></p>

<p><img src="/img/lfm_moe_3k_steps_rollout_corr_kl_compr.png" alt="3k steps KL — baseline breakdown" />
<em>Baseline <code>rollout_corr/kl</code> explodes to 30+ nats — a complete breakdown in logprob agreement between rollout and training. R3 stays near zero.</em></p>

<p><img src="/img/lfm_moe_3k_steps_validation_compr.png" alt="3k steps validation — baseline drops to zero" />
<em>Baseline validation accuracy drops from ~0.89 to 0.0 after step 2.5k. R3 holds steady at ~0.90.</em></p>

<p><img src="/img/lfm_moe_3k_steps_score_mean_compr.png" alt="3k steps score mean — baseline collapses" />
<em>The model can no longer produce correct answers. R3 maintains ~1.0 score mean.</em></p>

<p><strong>The key trigger is multi mini-step training</strong>, not multi-turn prompting. Single mini-step runs on the same model and task converge fine without R3 — the importance ratio stays near 1.0 regardless of routing noise, so the small KL perturbation from routing never reaches the clipping boundary.</p>

<hr />

<h2 id="previous-workarounds-and-their-limitations">Previous Workarounds and Their Limitations</h2>

<p>Before R3, researchers tried a few approaches to manage this problem:</p>

<p><strong>Group Sequence Policy Optimization (GSPO)</strong> applies importance sampling corrections at the sequence level rather than the token level, smoothing out some of the noise. It helps, but doesn’t address the root cause.</p>

<p><strong>Truncated Importance Sampling (TIS)</strong> aggressively clips extreme probability ratios. This stabilizes training but at the cost of discarding potentially useful gradient signal — essentially papering over the symptom.</p>

<p><strong>Reducing nondeterminism at the kernel level</strong> is another approach: some teams have introduced specialized GPU compute kernels designed to make routing more deterministic. This works, but it requires deep infrastructure changes and can impose performance overhead.</p>

<p>What none of these approaches do is fix the fundamental issue: the training engine is working with different routing decisions than the inference engine made. They’re all workarounds that manage the consequences, rather than eliminating the cause.</p>

<hr />

<h2 id="r3-the-elegant-fix">R3: The Elegant Fix</h2>

<p>Rollout Routing Replay (R3) takes a different approach that’s almost obvious in hindsight: <strong>just record what the router decided during inference, and replay those same decisions during training</strong>.</p>

<p>Concretely, during the rollout phase, for every token in every generated sequence, R3 logs which experts the router selected. These routing masks — binary indicators of which experts were activated — are stored alongside the generated tokens and rewards.</p>

<p>When the training phase begins, instead of letting the training engine’s router make fresh decisions, R3 feeds those recorded routing masks back in directly. The training engine uses the <em>same expert activations</em> that the inference engine used. This means the log-probabilities computed during training reflect the same computational path that actually produced the tokens — so the importance sampling ratios are accurate, the gradients are meaningful, and training is stable.</p>

<p>The beauty of R3 is that it’s minimal. It doesn’t change the model architecture. It doesn’t require new RL algorithms. It doesn’t impose any restrictive constraints on the training objective. It just adds a thin logging layer during rollout and a replay mechanism during the training forward pass. And it adds minimal overhead — the routing masks are small relative to the token data, and replaying them adds negligible latency to the training forward pass.</p>

<h3 id="how-much-to-replay-indices-vs-indices--weights">How Much to Replay: Indices vs. Indices + Weights</h3>

<p>There’s a practical design question in implementing R3: should you replay just the <strong>routing indices</strong> (which experts were selected) or also the <strong>combination weights</strong> (the softmax scores used to mix expert outputs)?</p>

<p>The original R3 paper describes replaying the full routing distribution. But VeRL’s standard implementation only replays indices, letting the training engine recompute the combination weights. We tested both variants on LFM MoE 8B:</p>

<p><img src="/img/with_rollout_weight_r3_vs_baseline.png" alt="Indices vs indices+weights KL comparison" /></p>

<table>
  <thead>
    <tr>
      <th>Variant</th>
      <th>rollout_corr/kl</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Baseline (no replay)</td>
      <td>~0.01–0.02</td>
    </tr>
    <tr>
      <td>Indices only</td>
      <td>~0.006–0.010</td>
    </tr>
    <tr>
      <td>Indices + weights</td>
      <td>~0.004–0.007</td>
    </tr>
  </tbody>
</table>

<p>Replaying weights provides additional KL reduction — it eliminates one more source of numerical disagreement between the two forward passes. However, there’s a <strong>staleness tradeoff</strong>: indices-only lets the updated model recompute its own combination weights, preserving its current judgment about how to weight experts. Indices + weights forces the model to use stale interpolation coefficients from the rollout policy. The storage overhead is also higher (float tensors vs. integer tensors).</p>

<p>For most practical purposes, <strong>indices-only replay captures the bulk of R3’s benefit</strong> while keeping the implementation simple.</p>

<hr />

<h2 id="why-this-matters-beyond-the-paper">Why This Matters Beyond the Paper</h2>

<p>If R3 were just an academic result, it would still be interesting. But it’s clearly already making its way into production systems.</p>

<p>DeepSeek V3.2 — one of the most capable open-weight models available — explicitly adopted a routing replay technique in its RL training pipeline. Their technical report describes logging which experts were activated during rollout and forcing the same routing pattern during training, so gradient updates are attributed to the experts that actually produced the sampled answers. This is R3 in practice.</p>

<p>This adoption by a leading AI lab is a strong signal that router-replay isn’t just theoretically useful — it’s a necessary ingredient for reliably training MoE models with RL at scale.</p>

<p>As the field continues to push toward larger MoE models (the efficiency advantages are too good to ignore) and more sophisticated RL training (the capability gains are too good to ignore), the problem R3 solves will only become more acute. Any team training a frontier MoE model with RL is going to encounter this issue eventually.</p>

<hr />

<h2 id="the-bigger-picture">The Bigger Picture</h2>

<p>There’s something worth pausing on here. The fact that MoE models create this training-inference discrepancy wasn’t obvious before people started running RL at scale on them. It’s the kind of problem that only surfaces when you combine two relatively new techniques — sparse expert routing and RL fine-tuning — in ways that weren’t anticipated when either was designed.</p>

<p>R3 is a reminder that as AI systems become more complex and composed from more intricate pieces, we should expect more of these subtle interaction effects. The solution, often, isn’t to abandon either technique — it’s to carefully characterize the interaction and build a targeted fix.</p>

<p>In this case, the fix is just a few lines of logging and replay logic. But without it, some of the most capable AI training pipelines in the world would be quietly, invisibly broken.</p>

<hr />

<p><em>The original paper — “Stabilizing MoE Reinforcement Learning by Aligning Training and Inference Routers” by Wenhan Ma, Hailin Zhang, Liang Zhao, Yifan Song, Yudong Wang, Zhifang Sui, and Fuli Luo — is available on arXiv at <a href="https://arxiv.org/abs/2510.11370">2510.11370</a>.</em></p>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[A look at why the routing mechanism in Mixture-of-Experts models breaks standard reinforcement learning — and how a deceptively simple idea called Router-Replay (R3) fixes it.]]></summary></entry><entry><title type="html">Async Rollout in Verl</title><link href="https://tianshu-michael-yu.github.io/2026/02/02/verl-async-rollout.html" rel="alternate" type="text/html" title="Async Rollout in Verl" /><published>2026-02-02T00:00:00+00:00</published><updated>2026-02-02T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2026/02/02/verl-async-rollout</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2026/02/02/verl-async-rollout.html"><![CDATA[<p>In previous posts we discussed how RL training for LLMs works: sample responses from the policy, score them with a reward model, and update the policy to favor higher-reward outputs. The computational pattern is straightforward—generate a batch, compute advantages, run a few gradient steps—but the devil is in the timing. Generation and training compete for the same GPUs, and one slow sample can stall the entire batch.</p>

<p>Verl is an open-source RL training framework (the public implementation of the HybridFlow paper, accepted at EuroSys 2025) that tackles this problem through async rollout. This post examines how Verl decouples generation from training and the algorithmic corrections needed to make off-policy updates work.</p>

<h2 id="the-long-tail-problem">The Long-Tail Problem</h2>

<p>Synchronous RL waits for every sample in a batch to finish generating before training begins. The problem is that generation lengths follow a heavy-tailed distribution: most responses are short, but a few drag on. While those stragglers finish, the GPUs allocated to the other samples sit idle.</p>

<p>The issue compounds with longer contexts and agentic tasks. A model interacting with a code sandbox or web browser might wait seconds for environment feedback, and those waits are unpredictable. Simply adding more GPUs does not help—you cannot parallelize away the tail of a single slow trajectory.</p>

<p><img src="/img/sync_vs_async_rollout.svg" alt="Sync vs Async Rollout" /></p>

<p>The diagram above contrasts the two approaches. In synchronous mode, fast-finishing samples create idle bubbles while waiting for stragglers. A single long-tail sample blocks the entire batch from proceeding to training. In asynchronous mode, samples stream to the trainer as they complete, and training runs continuously without waiting.</p>

<h2 id="colocated-vs-disaggregated">Colocated vs. Disaggregated</h2>

<p>Verl supports two deployment modes that make different trade-offs between latency and utilization.</p>

<p><strong>Colocated (HybridEngine).</strong> Training and generation share the same GPU pool. When generation runs, the optimizer states offload to CPU; when training runs, the inference engine pauses. Weight synchronization is fast—just an in-memory NCCL transfer—but the two workloads cannot overlap. This mode works well when generation is predictable and roughly matches training time.</p>

<p><strong>Disaggregated.</strong> Generation and training run on separate node pools connected by queues. The generator streams samples to the trainer as they complete, so slow trajectories no longer block fast ones. The cost is network transfer for weights and samples, but the benefit is that both pools stay busy. Disaggregation also enables elastic scaling: you can add generator nodes during high-variance workloads without touching the trainer.</p>

<p><img src="/img/colocated_vs_disaggregated.svg" alt="Colocated vs Disaggregated" /></p>

<p>The colocated design time-multiplexes GPUs between generation and training, offloading inactive states to CPU. The disaggregated design runs both workloads in parallel on dedicated pools, communicating through a sample queue with periodic weight synchronization.</p>

<h2 id="staleness-and-off-policy-drift">Staleness and Off-Policy Drift</h2>

<p>Once generation and training decouple, they inevitably drift apart. The generator produces samples under policy version $k$ while the trainer has already updated to version $k+1$ or beyond. PPO assumes on-policy data, so using stale samples without correction biases the gradient.</p>

<p>Verl controls this drift with a <strong>staleness threshold</strong> $\eta$. Setting $\eta = 0$ recovers synchronous training: the trainer blocks until fresh samples arrive. Setting $\eta &gt; 0$ allows a fraction of the batch to come from older policy versions. The generator produces at most</p>

\[N_{\text{rollout}} = (1 + \eta) \cdot B - N_{\text{stale}}\]

<p>samples between weight syncs, where $B$ is the batch size and $N_{\text{stale}}$ counts leftover stale samples from the previous round. When generation is fast relative to training, $\eta = 1$ approximates one-step off-policy updates.</p>

<p><img src="/img/staleness_is_correction.svg" alt="Staleness and IS Correction" /></p>

<p>The diagram shows how samples generated under different policy versions end up in the same training batch. Sample A (generated at version $k$) is stale by 2 versions when used for training at $\pi_{\text{old}}$. Sample C is fresh. The importance sampling ratio $\rho_t$ reweights each sample’s contribution based on how much the policy has drifted since generation.</p>

<h2 id="importance-sampling-corrections">Importance Sampling Corrections</h2>

<p>Stale samples require importance sampling (IS) to reweight their contribution. Let $\pi_{\text{rollout}}$ denote the policy that generated a sample and $\pi_{\text{old}}$ the policy at the start of the current training step. The per-token IS ratio is</p>

\[\rho_t = \frac{\pi_{\text{old}}(a_t \mid s_t)}{\pi_{\text{rollout}}(a_t \mid s_t)}.\]

<p>If $\pi_{\text{rollout}} = \pi_{\text{old}}$, the ratio is 1 and we recover standard PPO. When they differ, we have two correction strategies.</p>

<p><strong>Token-TIS (Token-Level Truncated IS).</strong> Apply a clipped ratio at each token:</p>

\[w_t = \min(\rho_t, C_{\text{IS}}).\]

<p>The REINFORCE gradient becomes</p>

\[\nabla_\theta \mathcal{L}_{\text{Token-TIS}} = -\mathbb{E}_t \bigl[ \text{sg}(w_t) \cdot \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot A_t \bigr],\]

<p>where $\text{sg}$ is stop-gradient. Token-TIS has low variance because each token gets its own weight, but it introduces $O(T^2 \Delta_{\max})$ bias when the policy drifts significantly (here $T$ is sequence length and $\Delta_{\max}$ is the maximum per-token divergence).</p>

<p><strong>Seq-TIS (Sequence-Level Truncated IS).</strong> Compute a single weight for the entire trajectory:</p>

\[w_{\text{seq}} = \min\Bigl( \prod_t \rho_t,\; C_{\text{IS}} \Bigr) = \min\Bigl( \exp\bigl(\textstyle\sum_t \log \rho_t\bigr),\; C_{\text{IS}} \Bigr).\]

<p>This weight broadcasts to all tokens in the sequence. Seq-TIS is unbiased—it correctly reweights the full trajectory—but has higher variance because a single large ratio can dominate.</p>

<p>The choice depends on drift severity:</p>

<table>
  <thead>
    <tr>
      <th>Drift Level</th>
      <th>Recommended Correction</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Negligible (same checkpoint)</td>
      <td>None (bypass mode)</td>
    </tr>
    <tr>
      <td>Moderate (slight staleness)</td>
      <td>Token-TIS</td>
    </tr>
    <tr>
      <td>Severe (replay buffer, old data)</td>
      <td>Seq-TIS or Seq-MIS</td>
    </tr>
  </tbody>
</table>

<p>Seq-MIS is a variant that rejects (masks) sequences exceeding the IS threshold rather than clipping. It acts as a hard trust-region filter when the distribution tail contains garbage samples.</p>

<h2 id="fully-async-training">Fully Async Training</h2>

<p>Verl’s fully async mode pushes decoupling further: the generator and trainer run continuously without explicit synchronization points. Samples flow through a queue, and the trainer consumes whatever is available. Weight updates push to the generator whenever a training step completes.</p>

<p>The key insight is that <code>old_log_prob</code>—the log-probability used for importance sampling—must be computed by the generator at rollout time, not recomputed by the trainer. This ensures the IS ratio correctly reflects the policy that actually produced the sample, even if the trainer has moved on.</p>

<p>In experiments on Qwen2.5-7B with 128 GPUs, fully async training achieved 2.35–2.67× throughput over synchronous baselines. On Qwen3-30B-A3B, the disaggregated async setup delivered 1.7× improvement compared to colocated mode.</p>

<h2 id="takeaways">Takeaways</h2>

<ul>
  <li>Synchronous RL suffers from the long-tail problem: slow samples idle the entire batch.</li>
  <li>Disaggregated deployment separates generation and training onto different node pools, enabling overlap and elastic scaling.</li>
  <li>Staleness thresholds control how much off-policy drift is tolerable.</li>
  <li>Token-TIS and Seq-TIS provide importance sampling corrections with different bias-variance trade-offs.</li>
  <li>Fully async training with proper IS corrections can more than double throughput on large-scale runs.</li>
</ul>

<p>Sources:
- <a href="https://verl.readthedocs.io/en/latest/advance/fully_async.html">Verl Documentation: Fully Async Policy Trainer</a>
- <a href="https://verl.readthedocs.io/en/latest/algo/rollout_corr.html">Verl Documentation: Rollout Correction</a>
- <a href="https://verl.readthedocs.io/en/latest/algo/rollout_corr_math.html">Verl Documentation: Mathematical Formulations</a>
- <a href="https://github.com/volcengine/verl">Verl GitHub Repository</a></p>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[In previous posts we discussed how RL training for LLMs works: sample responses from the policy, score them with a reward model, and update the policy to favor higher-reward outputs. The computational pattern is straightforward—generate a batch, compute advantages, run a few gradient steps—but the devil is in the timing. Generation and training compete for the same GPUs, and one slow sample can stall the entire batch.]]></summary></entry><entry><title type="html">Manifold-Constrained Hyper-Connections</title><link href="https://tianshu-michael-yu.github.io/2026/01/26/manifold-constrained-hyper-connections.html" rel="alternate" type="text/html" title="Manifold-Constrained Hyper-Connections" /><published>2026-01-26T00:00:00+00:00</published><updated>2026-01-26T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2026/01/26/manifold-constrained-hyper-connections</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2026/01/26/manifold-constrained-hyper-connections.html"><![CDATA[<p>The residual connection from ResNet has remained largely unchanged for a decade. The pattern is simple: add the layer output back to the input, $x_{l+1} = x_l + F(x_l, W_l)$. This identity mapping lets gradients flow unimpeded through deep networks and has become a fundamental building block of transformers and LLMs.</p>

<p>Hyper-Connections (HC) extended this paradigm by widening the residual stream and diversifying connection patterns. Instead of a single residual path, HC maintains $n$ parallel streams and uses learnable matrices to route information among them. The performance gains are substantial, but the approach has a hidden cost: it breaks the identity mapping property that made residual connections stable in the first place.</p>

<p>This post looks at Manifold-Constrained Hyper-Connections (mHC), which restores stability by projecting the learnable mappings onto doubly stochastic matrices.</p>

<h2 id="the-problem-with-hyper-connections">The Problem with Hyper-Connections</h2>

<p>In standard residual networks, recursively unrolling the connection across layers gives:</p>

\[x_L = x_l + \sum_{i=l}^{L-1} F(x_i, W_i).\]

<p>The term $x_l$ passes through unchanged—this is the identity mapping. Signal magnitude stays bounded because we are just summing residuals onto a stable baseline.</p>

<p>HC replaces the scalar identity with a learnable matrix $\mathcal{H}_l^{\text{res}} \in \mathbb{R}^{n \times n}$:</p>

\[x_{l+1} = \mathcal{H}_l^{\text{res}} x_l + \mathcal{H}_l^{\text{post} \top} F(\mathcal{H}_l^{\text{pre}} x_l, W_l),\]

<p>where $x_l \in \mathbb{R}^{n \times C}$ is the widened residual stream. Unrolling this across layers produces a composite mapping $\prod_{i=1}^{L-l} \mathcal{H}_{L-i}^{\text{res}}$ in front of the initial features. Nothing constrains this product to behave like an identity, so signals can explode or vanish as they propagate through the network.</p>

<p>The DeepSeek team measured this instability directly. They define the <em>Amax Gain Magnitude</em> as the maximum absolute row sum (forward signal gain) or column sum (backward gradient gain) of the composite mapping. For a well-behaved identity mapping this value should stay near 1. In their 27B model trained with HC, the Amax Gain Magnitude spiked to nearly 3000—a clear sign of exploding residual streams.</p>

<h2 id="doubly-stochastic-matrices">Doubly Stochastic Matrices</h2>

<p>The fix is to constrain $\mathcal{H}_l^{\text{res}}$ to be a doubly stochastic matrix: a non-negative matrix whose rows and columns each sum to 1. Formally, mHC projects the residual mapping onto the Birkhoff polytope:</p>

\[\mathcal{P}_{\mathcal{M}^{\text{res}}}(\mathcal{H}_l^{\text{res}}) = \left\{ \mathcal{H}_l^{\text{res}} \in \mathbb{R}^{n \times n} \mid \mathcal{H}_l^{\text{res}} \mathbf{1}_n = \mathbf{1}_n,\; \mathbf{1}_n^\top \mathcal{H}_l^{\text{res}} = \mathbf{1}_n^\top,\; \mathcal{H}_l^{\text{res}} \geq 0 \right\}.\]

<p>Why does this help? Doubly stochastic matrices have several nice properties for training stability:</p>

<ol>
  <li><strong>Norm preservation.</strong> The spectral norm of a doubly stochastic matrix is bounded by 1, so the mapping is non-expansive and cannot blow up gradients.</li>
  <li><strong>Closure under multiplication.</strong> The product of doubly stochastic matrices is itself doubly stochastic. This means the composite mapping across many layers inherits the same stability guarantee.</li>
  <li><strong>Convex combination of permutations.</strong> Geometrically, every doubly stochastic matrix is a weighted average of permutation matrices (Birkhoff–von Neumann theorem). The residual mapping therefore acts as a soft permutation that mixes features across streams without amplifying or attenuating them.</li>
</ol>

<p>When $n = 1$, the only doubly stochastic “matrix” is the scalar 1, recovering the original identity mapping.</p>

<h2 id="the-sinkhorn-knopp-algorithm">The Sinkhorn-Knopp Algorithm</h2>

<p>mHC computes the learnable coefficients similarly to HC. Given the flattened hidden state $\vec{x}_l \in \mathbb{R}^{1 \times nC}$, we apply a linear projection and add a static bias:</p>

\[\tilde{\mathcal{H}}_l^{\text{res}} = \alpha_l^{\text{res}} \cdot \text{mat}(\vec{x}'_l \varphi_l^{\text{res}}) + \mathbf{b}_l^{\text{res}},\]

<p>where $\vec{x}’_l = \text{RMSNorm}(\vec{x}_l)$. The resulting matrix $\tilde{\mathcal{H}}_l^{\text{res}}$ is unconstrained, so we project it onto the Birkhoff polytope using the Sinkhorn-Knopp algorithm.</p>

<p>The algorithm is straightforward. Starting from $\mathbf{M}^{(0)} = \exp(\tilde{\mathcal{H}}_l^{\text{res}})$ (element-wise exponentiation ensures positivity), we alternate row and column normalization:</p>

\[\mathbf{M}^{(t)} = \mathcal{T}_r\left( \mathcal{T}_c(\mathbf{M}^{(t-1)}) \right),\]

<p>where $\mathcal{T}_r$ divides each row by its sum and $\mathcal{T}_c$ divides each column by its sum. As $t \to \infty$ the matrix converges to a doubly stochastic one. In practice, 20 iterations suffice.</p>

<p>For the pre and post mappings, mHC simply applies a sigmoid to enforce non-negativity:</p>

\[\mathcal{H}_l^{\text{pre}} = \sigma(\tilde{\mathcal{H}}_l^{\text{pre}}), \qquad \mathcal{H}_l^{\text{post}} = 2\sigma(\tilde{\mathcal{H}}_l^{\text{post}}).\]

<h2 id="system-level-optimizations">System-Level Optimizations</h2>

<p>Widening the residual stream by a factor of $n$ increases memory access costs proportionally. The original HC paper did not address this overhead, which limited practical scalability.</p>

<p>mHC introduces several infrastructure optimizations:</p>

<p><strong>Kernel fusion.</strong> Computing the coefficients involves RMSNorm, linear projections, Sinkhorn-Knopp iterations, and the application of the mappings. mHC fuses these operations into a small number of custom CUDA kernels using TileLang. The RMSNorm division is reordered to follow the matrix multiplication, maintaining mathematical equivalence while reducing memory traffic.</p>

<p><strong>Recomputation.</strong> Instead of storing all intermediate activations for the backward pass, mHC discards the mHC-specific activations after the forward pass and recomputes them on-the-fly during backpropagation. For a block of $L_r$ consecutive layers, only the input to the first layer needs to be stored. The optimal block size that minimizes total memory footprint is approximately:</p>

\[L_r^* \approx \sqrt{\frac{nL}{n+2}}.\]

<p><strong>DualPipe overlap.</strong> In pipeline-parallel training, the $n$-stream residual incurs extra communication at stage boundaries. mHC extends the DualPipe schedule to overlap this communication with computation. The post-residual kernels for MLP layers run on a dedicated high-priority compute stream, and attention kernels avoid persistent mode so they can be preempted for communication.</p>

<p>With these optimizations, mHC adds only 6.7% training overhead at expansion rate $n = 4$.</p>

<h2 id="results">Results</h2>

<p>On a 27B MoE model trained for 50k steps, mHC achieves a final loss reduction of 0.021 compared to the baseline. More importantly, the training is stable: gradient norms stay well-behaved throughout, whereas HC shows a loss spike around step 12k that correlates with unstable gradients.</p>

<table>
  <thead>
    <tr>
      <th>Benchmark</th>
      <th>Baseline</th>
      <th>HC</th>
      <th>mHC</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>BBH (EM)</td>
      <td>43.8</td>
      <td>48.9</td>
      <td><strong>51.0</strong></td>
    </tr>
    <tr>
      <td>DROP (F1)</td>
      <td>47.0</td>
      <td>51.6</td>
      <td><strong>53.9</strong></td>
    </tr>
    <tr>
      <td>GSM8K (EM)</td>
      <td>46.7</td>
      <td>53.2</td>
      <td><strong>53.8</strong></td>
    </tr>
    <tr>
      <td>MMLU (Acc)</td>
      <td>59.0</td>
      <td>63.0</td>
      <td><strong>63.4</strong></td>
    </tr>
  </tbody>
</table>

<p>mHC consistently outperforms both the baseline and HC across reasoning and knowledge benchmarks. The stability analysis confirms the mechanism: the Amax Gain Magnitude of the composite mapping in mHC stays below 2, three orders of magnitude smaller than HC’s spikes.</p>

<h2 id="takeaways">Takeaways</h2>

<ul>
  <li>HC’s performance gains come at the cost of breaking the identity mapping property, which leads to exploding/vanishing signals in deep networks.</li>
  <li>Constraining the residual mapping to be doubly stochastic restores stability while preserving the benefits of multi-stream residuals.</li>
  <li>The Sinkhorn-Knopp algorithm provides a differentiable projection onto the Birkhoff polytope.</li>
  <li>Careful infrastructure work (kernel fusion, recomputation, pipeline overlap) makes the approach practical at scale with minimal overhead.</li>
</ul>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[The residual connection from ResNet has remained largely unchanged for a decade. The pattern is simple: add the layer output back to the input, $x_{l+1} = x_l + F(x_l, W_l)$. This identity mapping lets gradients flow unimpeded through deep networks and has become a fundamental building block of transformers and LLMs.]]></summary></entry><entry><title type="html">Tiny Recursive Models</title><link href="https://tianshu-michael-yu.github.io/machine-learning/reasoning/deep-learning/2026/01/10/tiny-recursive-model.html" rel="alternate" type="text/html" title="Tiny Recursive Models" /><published>2026-01-10T00:00:00+00:00</published><updated>2026-01-10T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/machine-learning/reasoning/deep-learning/2026/01/10/tiny-recursive-model</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/machine-learning/reasoning/deep-learning/2026/01/10/tiny-recursive-model.html"><![CDATA[<p><strong>Tiny Recursive Models (TRM)</strong> show that <em>recursive reasoning</em> plus <em>deep supervision</em> can outperform much larger models on hard reasoning tasks (Sudoku-Extreme, Maze-Hard, ARC-AGI) using <strong>only ~5–7M parameters</strong>.<br />
Instead of scaling depth or width, TRM <strong>reuses a tiny network many times</strong>, progressively improving its own solution.</p>

<p><img src="/img/trm.png" alt="TRM" /></p>

<hr />

<h2 id="motivation-why-recursion-instead-of-bigger-models">Motivation: Why Recursion Instead of Bigger Models?</h2>

<p>Large language models struggle on tasks where:
- A single error invalidates the solution (Sudoku, ARC)
- Step-by-step correctness matters more than fluency
- Data is scarce (≈1k training examples)</p>

<p>Scaling parameters increases capacity but also <strong>overfitting</strong>.<br />
TRM takes a different route:</p>

<blockquote>
  <p><strong>Fix the capacity, scale the reasoning.</strong></p>
</blockquote>

<hr />

<h2 id="core-idea-iterative-self-correction">Core Idea: Iterative Self-Correction</h2>

<p>TRM maintains <strong>two states</strong>:</p>

<ul>
  <li><strong>$y$</strong> – the current <em>proposed solution</em> (embedded)</li>
  <li><strong>$z$</strong> – a <em>latent reasoning state</em> (analogous to an internal chain-of-thought)</li>
</ul>

<p>Given an input problem $x$, TRM repeatedly:
1. Refines its latent reasoning $z$
2. Uses $z$ to refine the solution $y$</p>

<p>This allows the model to <strong>correct earlier mistakes</strong> instead of committing to a single forward pass.</p>

<hr />

<h2 id="architecture-overview">Architecture Overview</h2>

<p>TRM uses <strong>a single tiny network</strong> $f_\theta$ (typically a 2-layer Transformer).</p>

<hr />

<h2 id="algorithm-pseudocode">Algorithm (Pseudocode)</h2>

<p>The following pseudocode makes the structure of <strong>Tiny Recursive Models (TRM)</strong> explicit: a <em>latent recursion</em> phase that updates the reasoning state, followed by an <em>answer refinement</em> step, wrapped inside a deep-recursion training loop.</p>

<h3 id="1-latent-recursion--answer-refinement">1) Latent recursion + answer refinement</h3>

<pre><code class="language-python"># x : embedded input
# y : current embedded solution
# z : latent reasoning state
# f_theta : the same tiny network used everywhere

def latent_recursion(x, y, z, n=6):
    # Reasoning phase: update latent state z
    for _ in range(n):
        z = f_theta(x, y, z)

    # Decision phase: update solution y once
    y = f_theta(y, z)
    return y, z
</code></pre>

<h3 id="2-deep-recursion-wrapper-t-rounds">2) Deep recursion wrapper (T rounds)</h3>

<pre><code class="language-python">def deep_recursion(x, y, z, n=6, T=3):
    # T-1 rounds without gradients (cheap iterative reasoning)
    with torch.no_grad():
        for _ in range(T - 1):
            y, z = latent_recursion(x, y, z, n)

    # Final round with gradients (used for learning)
    y, z = latent_recursion(x, y, z, n)
    return y, z
</code></pre>

<h3 id="3-deep-supervision-training-loop">3) Deep supervision training loop</h3>

<pre><code class="language-python"># N_sup : maximum supervision steps (e.g., 16)
# g     : output head mapping y -&gt; logits
# h     : halting head mapping y -&gt; halting logit

for (x_input, y_true) in dataloader:
    x = embed(x_input)
    y, z = init_y(), init_z()

    for step in range(N_sup):
        y, z = deep_recursion(x, y, z, n=6, T=3)

        logits = g(y)
        q      = h(y)

        # prediction + halting losses
        loss = CE(logits, y_true) + BCE(sigmoid(q), is_correct(logits, y_true))
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        # early stopping if the model believes it is correct
        if sigmoid(q) &gt; 0.5:
            break
</code></pre>

<p><strong>Notes</strong>
- The <em>same</em> network $f_\theta$ is reused everywhere; passing $(x, y, z)$ versus $(y, z)$ determines whether the model updates reasoning or refines the answer.
- Using $T−1$ rounds without gradients plus one round with gradients keeps memory usage low while still training multi-step improvement.</p>

<hr />

<h2 id="inference-structure">Inference Structure</h2>

<p>At inference time, TRM runs the same recursive update logic <strong>without any losses or backpropagation</strong>. The model repeatedly refines its solution using fixed inner recursion and adaptive outer stopping.</p>

<pre><code class="language-python"># x : embedded input
# y : current embedded solution
# z : latent reasoning state
# f_theta : shared tiny network
# K_max : maximum number of improvement steps

def trm_inference(x, y, z, n=6, T=3, K_max=16):
    for k in range(K_max):                     # outer improvement loop
        for t in range(T):                     # deep recursion
            for _ in range(n):                 # latent reasoning
                z = f_theta(x, y, z)
            y = f_theta(y, z)                  # answer refinement

        # optional halting (same criterion as training)
        q = h(y)                               # halting logit
        if q &gt; 0:                              # equivalent to sigmoid(q) &gt; 0.5
            break

    return y
</code></pre>

<p><strong>Key points</strong>
- The model performs <code>n × T</code> latent-reasoning updates per outer improvement step.
- The solution <code>y</code> is refined <strong>T times per improvement step</strong>, and up to <code>K_max</code> improvement steps overall.
- Deep supervision is a <strong>training-only</strong> mechanism; inference simply reuses the learned iterative solver.
- Halting is checked only at the outer loop, even though <code>y</code> is updated inside the inner loops.</p>

<hr />

<h2 id="mathematical-formulation">Mathematical Formulation</h2>

<h3 id="state-variables">State Variables</h3>

<p>Let:
- $x ∈ ℝ^{L×D}$ : embedded input
- $y_t ∈ ℝ^{L×D}$ : solution embedding at step $t$
- $z_t ∈ ℝ^{L×D}$ : latent reasoning state</p>

<hr />

<h3 id="latent-recursion-reasoning-phase">Latent Recursion (Reasoning Phase)</h3>

<p>For $n$ reasoning steps:</p>

\[z_{t,k+1} = f_θ(x, y_t, z_{t,k}), \quad k = 0 \dots n-1\]

<p>We denote the final latent state as:</p>

\[z_{t+1} = z_{t,n}\]

<p>This phase updates <em>how</em> the model reasons without yet changing the answer.</p>

<hr />

<h3 id="answer-update-decision-phase">Answer Update (Decision Phase)</h3>

<p>Using the refined latent state:</p>

\[y_{t+1} = f_θ(y_t, z_{t+1})\]

<p>The same network $f_θ$ is reused; the input structure defines the role.</p>

<hr />

<h3 id="deep-recursion">Deep Recursion</h3>

<p>To control memory cost, TRM performs:</p>

<ul>
  <li>$T−1$ recursion rounds <strong>without gradients</strong></li>
  <li>1 recursion round <strong>with gradients</strong></li>
</ul>

\[(y_{t+1}, z_{t+1}) =
\mathcal{R}^{(T)}(x, y_t, z_t)\]

<p>Only the final recursion participates in backpropagation.</p>

<hr />

<h2 id="training-objective">Training Objective</h2>

<h3 id="prediction-loss">Prediction Loss</h3>

<p>The solution embedding is decoded via an output head:</p>

\[\hat{y}_t = \arg\max (W y_t)\]

\[\mathcal{L}_{pred} = \mathrm{CE}(\hat{y}_t, y^*)\]

<hr />

<h3 id="halting-loss-adaptive-computation">Halting Loss (Adaptive Computation)</h3>

<p>TRM learns when to stop iterating.</p>

<p>Let $q_t$ be a halting logit:</p>

\[\mathcal{L}_{halt} =
\mathrm{BCE}(\sigma(q_t), \mathbf{1}[\hat{y}_t = y^*])\]

<p>Training halts early when the model predicts correctness.</p>

<hr />

<h3 id="total-loss">Total Loss</h3>

\[\mathcal{L} = \mathcal{L}_{pred} + \mathcal{L}_{halt}\]

<hr />

<h2 id="why-two-states-y-and-z">Why Two States ($y$ and $z$)?</h2>

<ul>
  <li>$y$ stores <em>what</em> the current solution is</li>
  <li>$z$ stores <em>how</em> the model reasoned to reach it</li>
</ul>

<p>Empirically:
- One state → worse performance
- More than two states → worse generalization
- Exactly two states → best results</p>

<hr />

<h2 id="why-tiny-networks-work-better">Why Tiny Networks Work Better</h2>

<p>Counterintuitively, <strong>2-layer models outperform deeper ones</strong>.</p>

<p>Reason:
- Data is scarce
- Larger models overfit
- Recursion provides effective depth</p>

<p>Effective depth is approximately:</p>

\[\text{Depth} ≈ T × (n+1) × \text{layers}\]

<p>Example:
- 2 layers × 42 recursions ≈ 84-layer behavior</p>

<hr />

<h2 id="observation-reasoning-capacity-vs-knowledge-capacity">Observation: Reasoning Capacity vs Knowledge Capacity</h2>

<p>The empirical result that <em>smaller</em> TRMs generalize better on ARC-AGI, Sudoku, and Maze should not be interpreted as evidence that reasoning capacity is inherently small or that larger models are fundamentally worse at reasoning.</p>

<p>Rather, it reflects two properties of the experimental setting:</p>

<ol>
  <li>
    <p><strong>The tasks require almost no world knowledge.</strong><br />
ARC-AGI and related puzzles are algorithmic and symbolic. They do not require linguistic understanding, factual recall, or common-sense priors about the real world. As a result, increasing parameter count mainly adds unused or overfittable capacity.</p>
  </li>
  <li>
    <p><strong>The training regime is extremely data-limited.</strong><br />
With only on the order of (10^3) training tasks, larger models are prone to shortcut learning and memorization rather than learning a robust iterative procedure.</p>
  </li>
</ol>

<p>From this perspective, TRM’s key contribution is architectural rather than parametric: it <strong>decouples reasoning capacity from parameter count</strong>. Reasoning depth is provided by <em>iteration over latent state</em>, while parameters primarily encode inductive biases and task-specific representations.</p>

<p>This suggests a more general interpretation:</p>

<ul>
  <li><strong>Parameters control knowledge breadth</strong> (what the model knows).</li>
  <li><strong>Recursion controls reasoning depth</strong> (how long and how carefully the model can think).</li>
</ul>

<p>Under this view, the observation that “smaller models work better” is specific to low-knowledge puzzle domains. In settings that require substantial world knowledge, variable-length outputs, or open-ended semantics, larger TRMs may benefit from increased parameterization while retaining efficient recursive reasoning.</p>

<hr />

<h2 id="comparison-with-chain-of-thought-cot">Comparison with Chain-of-Thought (CoT)</h2>

<p>It is instructive to contrast TRM’s recursive reasoning with <strong>Chain-of-Thought (CoT)</strong> reasoning in large language models. Both aim to improve reasoning by “thinking longer,” but they scale computation and memory in fundamentally different ways.</p>

<h3 id="how-cot-scales-reasoning">How CoT scales reasoning</h3>

<p>In CoT-based models, reasoning depth is increased by generating longer token sequences. This has several consequences:</p>

<ul>
  <li><strong>Compute scales quadratically</strong> with reasoning length due to self-attention over longer sequences.</li>
  <li><strong>Memory scales linearly</strong> with the number of generated tokens, since all intermediate tokens must be stored.</li>
  <li>Reasoning is <strong>entangled with generation</strong>: each reasoning step is a committed token and cannot be revised.</li>
  <li>Errors early in the chain can irreversibly corrupt the final answer.</li>
</ul>

<p>In practice, increasing reasoning via CoT incurs rapidly increasing compute and memory costs.</p>

<h3 id="how-trm-scales-reasoning">How TRM scales reasoning</h3>

<p>TRM increases reasoning depth through <strong>iteration over a fixed-size latent state</strong>:</p>

<ul>
  <li><strong>Compute scales linearly</strong> with the number of recursion steps.</li>
  <li><strong>Memory remains constant</strong>, since the latent state has fixed dimensionality and is repeatedly updated.</li>
  <li>Reasoning is <strong>non-committal</strong>: intermediate latent states can be revised and corrected.</li>
  <li>The final answer is produced only after sufficient refinement.</li>
</ul>

<p>This makes TRM closer to an <strong>iterative solver</strong> than a generative process.</p>

<h3 id="key-contrast">Key contrast</h3>

<table>
  <thead>
    <tr>
      <th>Aspect</th>
      <th>Chain-of-Thought</th>
      <th>TRM</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Reasoning medium</td>
      <td>Token sequence</td>
      <td>Fixed-size latent state</td>
    </tr>
    <tr>
      <td>Compute vs reasoning</td>
      <td>Quadratic</td>
      <td>Linear</td>
    </tr>
    <tr>
      <td>Memory vs reasoning</td>
      <td>Linear</td>
      <td>Constant</td>
    </tr>
    <tr>
      <td>Error correction</td>
      <td>Difficult</td>
      <td>Natural</td>
    </tr>
    <tr>
      <td>Reasoning vs knowledge</td>
      <td>Entangled</td>
      <td>Decoupled</td>
    </tr>
  </tbody>
</table>

<p>From this perspective, TRM can be viewed as an <strong>architectural alternative to CoT</strong>: instead of scaling reasoning by growing sequences, it scales reasoning by reusing computation over a persistent internal state.</p>

<p>This distinction helps explain why TRM is particularly effective in low-data, algorithmic domains, and why its recursive structure may remain advantageous even as models are scaled to handle broader, knowledge-intensive tasks.</p>

<hr />

<h2 id="training-details">Training Details</h2>

<ul>
  <li>Optimizer: AdamW (β₁=0.9, β₂=0.95)</li>
  <li>Learning rate: 1e−4 (embeddings: 1e−2)</li>
  <li>Hidden size: 512</li>
  <li>Layers: 2</li>
  <li>Recursions: $n=6$, $T=3$</li>
  <li>Max supervision steps: $N_{sup}=16$</li>
  <li>Exponential Moving Average (EMA): 0.999</li>
</ul>

<hr />

<h2 id="results-snapshot">Results Snapshot</h2>

<p>TRM achieves strong generalization with orders-of-magnitude fewer parameters than LLMs:</p>

<p><img src="/img/arc-agi-1.png" alt="ARC-AGI-1" />
<img src="/img/arc-agi-2-trm.png" alt="ARC-AGI-2" /></p>

<ul>
  <li><strong>87%</strong> on Sudoku-Extreme</li>
  <li><strong>85%</strong> on Maze-Hard</li>
  <li><strong>44.6%</strong> on ARC-AGI-1</li>
  <li><strong>7.8%</strong> on ARC-AGI-2</li>
</ul>

<p>Using only <strong>~7M parameters</strong>.</p>

<hr />

<h2 id="key-takeaways">Key Takeaways</h2>

<ol>
  <li>Reasoning depth can replace parameter count</li>
  <li>Recursion is a powerful regularizer</li>
  <li>Deep supervision enables stable iterative improvement</li>
  <li>Simplicity beats biologically motivated complexity</li>
</ol>

<hr />

<h2 id="open-questions">Open Questions</h2>

<ul>
  <li>Why does recursion generalize better than depth?</li>
  <li>Can TRM be extended to generative modeling?</li>
  <li>What are the scaling laws for recursion vs parameters?</li>
</ul>

<hr />

<h2 id="autoregressive-trm-with-per-token-refinement">Autoregressive TRM with Per-Token Refinement</h2>

<p>I want to propose a possible extension of TRM that is <strong>not explored in the original paper</strong>: turning the three-time-scale TRM into an <strong>autoregressive model</strong> by wrapping it inside an outer token-generation loop.</p>

<p>In this proposal, TRM would no longer be a one-shot predictor, but instead act as an <strong>adaptive compute engine per token</strong>.</p>

<h3 id="high-level-idea">High-level idea</h3>

<ul>
  <li>The inner TRM performs <strong>iterative refinement</strong> to produce a <em>single next-token distribution</em>.</li>
  <li>An outer autoregressive loop emits one token at a time, appends it to the input context, and repeats until a stopping token is generated.</li>
</ul>

<p>This allows variable-length outputs while preserving TRM’s recursive reasoning structure.</p>

<h3 id="per-token-refinement-with-adaptive-compute">Per-token refinement with adaptive compute</h3>

<p>For each decoding step:</p>

<ul>
  <li>The prefix tokens are fixed, and their key–value (K,V) cache is reused.</li>
  <li>TRM refines the latent solution state corresponding to the <strong>current token</strong> over multiple recursion steps.</li>
  <li>Each refinement step updates the token’s representation, and therefore its K,V, while attending to the cached prefix.</li>
  <li>Once the halting condition is met, the final refined state is used to emit the token, and its K,V are committed to the cache.</li>
</ul>

<p>Intermediate refinement steps are <strong>not serialized into tokens</strong> and remain fully revisable.</p>

<h3 id="compute-and-memory-characteristics">Compute and memory characteristics</h3>

<p>Under this design:</p>

<ul>
  <li><strong>Compute per refinement step scales linearly</strong> with prefix length, since attention reuses cached K,V from previous tokens.</li>
  <li><strong>Total compute per token scales linearly</strong> with the number of refinement steps.</li>
  <li><strong>Memory usage remains bounded</strong> by the KV cache for emitted tokens plus the (small) model weights.</li>
  <li>Model capacity can be shifted from parameters to <strong>recursion depth</strong>, improving the balance between memory and compute.</li>
</ul>

<p>This contrasts with Chain-of-Thought reasoning, where increasing reasoning length directly increases sequence length, attention cost, and memory usage.</p>

<h3 id="why-this-is-appealing">Why this is appealing</h3>

<p>This autoregressive TRM formulation combines several desirable properties:</p>

<ul>
  <li><strong>Adaptive compute</strong>: easy tokens halt early, hard tokens receive more refinement.</li>
  <li><strong>Decoupling of knowledge and reasoning</strong>: parameters store knowledge, recursion provides reasoning depth.</li>
  <li><strong>Inference efficiency</strong>: reduced weight memory pressure and better utilization of available compute.</li>
  <li><strong>Edge deployment</strong>: smaller models with dynamic compute are well suited to memory-constrained devices.</li>
</ul>

<p>Conceptually, this shifts reasoning from <em>sequence expansion</em> to <em>latent refinement</em>, suggesting a path toward language models that are more efficient, more controllable at inference time, and less dominated by static parameter count.</p>

<hr />

<p><em>Based on “Less is More: Recursive Reasoning with Tiny Networks” (Jolicoeur‑Martineau, 2025).</em></p>]]></content><author><name>Tianshu Yu</name></author><category term="machine-learning" /><category term="reasoning" /><category term="deep-learning" /><category term="Other" /><summary type="html"><![CDATA[Tiny Recursive Models (TRM) show that recursive reasoning plus deep supervision can outperform much larger models on hard reasoning tasks (Sudoku-Extreme, Maze-Hard, ARC-AGI) using only ~5–7M parameters. Instead of scaling depth or width, TRM reuses a tiny network many times, progressively improving its own solution.]]></summary></entry><entry><title type="html">LFM2-VL Performance: Two Hidden Host↔Device Syncs in Metadata Building</title><link href="https://tianshu-michael-yu.github.io/2025/12/22/lfm2-vl-performance-issues.html" rel="alternate" type="text/html" title="LFM2-VL Performance: Two Hidden Host↔Device Syncs in Metadata Building" /><published>2025-12-22T00:00:00+00:00</published><updated>2025-12-22T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2025/12/22/lfm2-vl-performance-issues</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2025/12/22/lfm2-vl-performance-issues.html"><![CDATA[<p>When profiling <code>lfm2-vl</code>, most of the “why is my GPU idle?” time showed up <em>outside</em> the model kernels—in the attention <strong>metadata builder</strong>. This post documents two concrete bottlenecks I hit, how to spot them in a trace, and the fixes that restored async scheduling.</p>

<p>The hot path looked like this (simplified):</p>

<pre><code class="language-python">class ShortConvAttentionMetadataBuilder(
    BaseMambaAttentionMetadataBuilder[ShortConvAttentionMetadata]
):
    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: CommonAttentionMetadata,
        fast_build: bool = False,
    ) -&gt; ShortConvAttentionMetadata:
        num_reqs = common_attn_metadata.num_reqs
        query_start_loc = common_attn_metadata.query_start_loc
        state_indices_tensor = common_attn_metadata.block_table_tensor[:, 0]

        # for causal_conv1d
        nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None

        num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
            split_decodes_and_prefills(
                common_attn_metadata, decode_threshold=self.reorder_batch_threshold
            )
        )

        has_initial_states_p = None
        if num_prefills &gt; 0:
            has_initial_states_cpu = (
                common_attn_metadata.num_computed_tokens_cpu[
                    num_reqs - num_prefills : num_reqs
                ]
                &gt; 0
            )
            has_initial_states_p = has_initial_states_cpu.to(query_start_loc.device)  # Problem 1

            query_start_loc_p = (
                common_attn_metadata.query_start_loc[-num_prefills - 1 :]
                - num_decode_tokens
            )

            nums_dict, batch_ptr, token_chunk_offset_ptr = (
                compute_causal_conv1d_metadata(query_start_loc_p)  # Problem 2
            )

        elif (
            num_decodes &gt; 0
            and num_decodes &lt;= self.decode_cudagraph_max_bs
            and self.compilation_config.cudagraph_mode.has_full_cudagraphs()
        ):
            self.state_indices_tensor[:num_decodes].copy_(
                state_indices_tensor, non_blocking=True
            )
            state_indices_tensor = self.state_indices_tensor[:num_decode_tokens]
            state_indices_tensor[num_decodes:] = PAD_SLOT_ID

        return ShortConvAttentionMetadata(
            query_start_loc=query_start_loc,
            state_indices_tensor=state_indices_tensor,
            has_initial_states_p=has_initial_states_p,
            num_prefills=num_prefills,
            num_prefill_tokens=num_prefill_tokens,
            num_decodes=num_decodes,
            num_decode_tokens=num_decode_tokens,
            nums_dict=nums_dict,
            batch_ptr=batch_ptr,
            token_chunk_offset_ptr=token_chunk_offset_ptr,
        )
</code></pre>

<p>Both issues come from the same general rule:</p>

<blockquote>
  <p>If you want <strong>full async scheduling</strong>, be paranoid about <strong>implicit CPU↔GPU sync</strong> and about using <strong>pageable host memory</strong> for copies.</p>
</blockquote>

<hr />

<h2 id="background-what-is-has_initial_states_p-actually-checking">Background: what is <code>has_initial_states_p</code> actually checking?</h2>

<p>During serving, a “sequence at iteration (N)” can be viewed like:</p>

<pre><code>|---------- N-1 iteration --------|
|---------------- N iteration ---------------------|
|- tokenA -|......................|-- newTokens ---|
|---------- context_len ----------|
|-------------------- seq_len ---------------------|
                                  |-- query_len ---|
</code></pre>

<p><code>has_initial_states_p</code> is trying to determine whether we already have an <em>initial state</em> for short-conv attention, which is essentially checking:</p>

<ul>
  <li><strong>context_len &gt; 0</strong>  (i.e., this request is not “pure prompt from scratch”)</li>
</ul>

<p>In other words, it wants a per-request boolean derived from <code>query_start_loc</code> and <code>seq_lens</code>.</p>

<hr />

<h2 id="problem-1-tiny-cpugpu-copy-that-still-breaks-async">Problem 1: “tiny” CPU→GPU copy that still breaks async</h2>

<p>Here is what I originally had:</p>

<pre><code class="language-python">if num_prefills &gt; 0:
    has_initial_states_cpu = (
        common_attn_metadata.num_computed_tokens_cpu[
            num_reqs - num_prefills : num_reqs
        ]
        &gt; 0
    )
    has_initial_states_p = has_initial_states_cpu.to(query_start_loc.device)
</code></pre>

<p>On the trace, this showed up as a noticeable sync/copy point:</p>

<p><img src="/img/has_inital_states_cpu_to.png" alt="has_initial_states_cpu_to" /></p>

<h3 id="fix-a-if-you-must-hd-use-pinned-memory--non-blocking">Fix A: if you must H→D, use pinned memory + non-blocking</h3>

<p>If the value truly must originate on CPU, at minimum make the transfer async-friendly:</p>

<pre><code class="language-python">has_initial_states_cpu = (...).pin_memory()
has_initial_states_p = has_initial_states_cpu.to(
    query_start_loc.device, non_blocking=True
)
</code></pre>

<p>This dropped <code>short_conv_attn: build: has_initial_states_cpu.to</code> down to <strong>~28.367 μs</strong> in my run.</p>

<h3 id="fix-b-better-dont-go-to-cpu-in-the-first-place">Fix B (better): don’t go to CPU in the first place</h3>

<p>The bigger “aha” was that <code>num_computed_tokens_cpu</code> is itself suspicious. In fact, in the codebase it is explicitly deprecated because it risks implicit sync:</p>

<pre><code class="language-python">@property
@deprecated(
    """
Prefer using device seq_lens directly to avoid implicit H&lt;&gt;D sync which breaks full
async scheduling. If a CPU copy is needed, it can be derived from
query_start_loc_cpu and seq_lens.
Will be removed in a future release (v0.14.0)
"""
)
def num_computed_tokens_cpu(self) -&gt; torch.Tensor:
    if self._num_computed_tokens_cpu is None:
        query_seq_lens = self.query_start_loc_cpu[1:] - self.query_start_loc_cpu[:-1]
        self._num_computed_tokens_cpu = self.seq_lens_cpu - query_seq_lens
    return self._num_computed_tokens_cpu
</code></pre>

<p>But we don’t need any CPU tensor here. <code>query_start_loc</code> and <code>seq_lens</code> already exist on device, so compute the boolean on GPU:</p>

<pre><code class="language-python">query_seq_lens = (
    common_attn_metadata.query_start_loc[1:]
    - common_attn_metadata.query_start_loc[:-1]
)
context_lens = common_attn_metadata.seq_lens - query_seq_lens

has_initial_states_p = context_lens[num_reqs - num_prefills : num_reqs] &gt; 0
</code></pre>

<p>This completely removes the host dependency for Problem 1.</p>

<hr />

<h2 id="problem-2-a-30-ms-cudamemcpyasync-that-shouldnt-exist">Problem 2: a 30 ms <code>cudaMemcpyAsync</code> that shouldn’t exist</h2>

<p>The next spike was much worse: a single <code>cudaMemcpyAsync</code> taking <strong>~30.796 ms</strong>.</p>

<p><img src="/img/compute_causal_conv1d_metadata.png" alt="compute_causal_conv1d_metadata" /></p>

<p>When a CUDA API call is in <strong>milliseconds</strong> (not microseconds), it usually means you accidentally introduced a synchronization point or forced a slow path.</p>

<p>Zooming in, the GPU-side copy was:</p>

<ul>
  <li><code>Memcpy DtoH (Pageable)</code> on the <strong>main compute stream</strong></li>
</ul>

<p><img src="/img/compute_causal_conv1d_metadata_relationship.png" alt="compute_causal_conv1d_metadata_relationship" /></p>

<p>Two red flags:</p>

<ul>
  <li><strong>DtoH on the main stream</strong>: it blocks the CPU from enqueuing later kernels until the copy completes (because the runtime must ensure the source is ready).</li>
  <li><strong>Pageable host memory</strong>: true async DMA requires pinned memory. With pageable memory, CUDA often has to:
    <ul>
      <li>allocate/reuse an internal pinned staging buffer</li>
      <li>synchronize to ensure the device source is ready</li>
      <li>DMA into pinned memory</li>
      <li>memcpy pinned → pageable on CPU</li>
    </ul>
  </li>
</ul>

<h3 id="root-cause">Root cause</h3>

<p>The culprit was inside <code>compute_causal_conv1d_metadata</code>:</p>

<pre><code class="language-python">def compute_causal_conv1d_metadata(query_start_loc_p: torch.Tensor):
    # Needed for causal_conv1d
    seqlens = query_start_loc_p.diff().to("cpu")  # DtoH copy to pageable memory
    nums_dict = {}
    batch_ptr = None
    token_chunk_offset_ptr = None
    device = query_start_loc_p.device
    for BLOCK_M in [8]:
        nums = -(-seqlens // BLOCK_M)
        nums_dict[BLOCK_M] = {}
        nums_dict[BLOCK_M]["nums"] = nums
        nums_dict[BLOCK_M]["tot"] = nums.sum().item()
        mlist = torch.from_numpy(np.repeat(np.arange(len(nums)), nums))
        nums_dict[BLOCK_M]["mlist"] = mlist
        mlist_len = len(nums_dict[BLOCK_M]["mlist"])
        nums_dict[BLOCK_M]["mlist_len"] = mlist_len
        MAX_NUM_PROGRAMS = max(1024, mlist_len) * 2
        offsetlist = []
        for idx, num in enumerate(nums):
            offsetlist.extend(range(num))
        offsetlist = torch.tensor(offsetlist, dtype=torch.int32)
        nums_dict[BLOCK_M]["offsetlist"] = offsetlist

        if batch_ptr is None:
            batch_ptr = torch.full(
                (MAX_NUM_PROGRAMS,), PAD_SLOT_ID, dtype=torch.int32, device=device
            )
            token_chunk_offset_ptr = torch.full(
                (MAX_NUM_PROGRAMS,), PAD_SLOT_ID, dtype=torch.int32, device=device
            )
        else:
            if batch_ptr.nelement() &lt; MAX_NUM_PROGRAMS:
                batch_ptr.resize_(MAX_NUM_PROGRAMS).fill_(PAD_SLOT_ID)
                token_chunk_offset_ptr.resize_(MAX_NUM_PROGRAMS).fill_(PAD_SLOT_ID)

        batch_ptr[0:mlist_len].copy_(mlist)                 # HtoD from pageable
        token_chunk_offset_ptr[0:mlist_len].copy_(offsetlist)  # HtoD from pageable
        nums_dict[BLOCK_M]["batch_ptr"] = batch_ptr
        nums_dict[BLOCK_M]["token_chunk_offset_ptr"] = token_chunk_offset_ptr

    return nums_dict, batch_ptr, token_chunk_offset_ptr
</code></pre>

<p>There are <em>three</em> expensive transfers here:</p>

<ul>
  <li><strong>DtoH</strong>: <code>query_start_loc_p.diff().to("cpu")</code></li>
  <li><strong>HtoD</strong>: <code>batch_ptr.copy_(mlist)</code></li>
  <li><strong>HtoD</strong>: <code>token_chunk_offset_ptr.copy_(offsetlist)</code></li>
</ul>

<h3 id="fix-keep-the-input-cpu-side-and-make-htod-transfers-pinned--non-blocking">Fix: keep the input CPU-side, and make HtoD transfers pinned + non-blocking</h3>

<p>First principle: ask if the movement is necessary.</p>

<p>In this case, <code>compute_causal_conv1d_metadata</code> is building <strong>CPU-side lists</strong> anyway; it can just take CPU input and avoid the DtoH entirely:</p>

<pre><code class="language-python">def compute_causal_conv1d_metadata(query_start_loc_cpu: torch.Tensor, device: torch.device):
    ...
</code></pre>

<p>Then for the remaining HtoD copies:</p>

<ul>
  <li>allocate the CPU tensors in <strong>pinned memory</strong> (<code>pin_memory()</code>)</li>
  <li>use <strong>non-blocking</strong> copies (<code>copy_(..., non_blocking=True)</code>)</li>
</ul>

<p>After these changes, the trace looked like this:</p>

<p><img src="/img/fixed_compute_causal_conv1d_metadata.png" alt="fixed_compute_causal_conv1d_metadata.png" /></p>

<p>And <code>compute_causal_conv1d_metadata</code> dropped to <strong>~292.806 μs</strong>, with the async memcpy (red arrow) becoming negligible.</p>

<hr />

<h2 id="takeaways">Takeaways</h2>

<ul>
  <li><strong>Prefer device-side derivations</strong> when you already have device tensors (<code>seq_lens</code>, <code>query_start_loc</code>). Avoid “convenience” CPU properties that hide sync.</li>
  <li>If you must transfer CPU↔GPU in the hot path:
    <ul>
      <li>use <strong>pinned memory</strong> (<code>pin_memory()</code>)</li>
      <li>use <strong>non-blocking</strong> transfers (<code>to(..., non_blocking=True)</code> / <code>copy_(..., non_blocking=True)</code>)</li>
    </ul>
  </li>
  <li>A <code>cudaMemcpyAsync</code> taking <strong>milliseconds</strong> is often a sign you triggered a sync or a pageable-memory slow path. Always check whether it’s <code>DtoH (Pageable)</code> / <code>HtoD (Pageable)</code> and on which stream it runs.</li>
</ul>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[When profiling lfm2-vl, most of the “why is my GPU idle?” time showed up outside the model kernels—in the attention metadata builder. This post documents two concrete bottlenecks I hit, how to spot them in a trace, and the fixes that restored async scheduling.]]></summary></entry><entry><title type="html">Continuous Autoregressive Language Models</title><link href="https://tianshu-michael-yu.github.io/2025/12/14/continuous-autoregressive-language-models.html" rel="alternate" type="text/html" title="Continuous Autoregressive Language Models" /><published>2025-12-14T00:00:00+00:00</published><updated>2025-12-14T00:00:00+00:00</updated><id>https://tianshu-michael-yu.github.io/2025/12/14/continuous-autoregressive-language-models</id><content type="html" xml:base="https://tianshu-michael-yu.github.io/2025/12/14/continuous-autoregressive-language-models.html"><![CDATA[<p>In our previous post, <a href="/2025/11/07/sequence-parallelism.html">Sequence Parallelism</a>, we treated <em>sequence length</em> as a fixed property of the training batch, and asked how to shard computation when a single sequence becomes too long to process efficiently. That discussion focused on parallelizing attention under strict dependency constraints.</p>

<p>This post explores a complementary axis: <strong>reducing the number of autoregressive steps themselves</strong>. Continuous Autoregressive Language Models (CALM) do this by increasing the <em>semantic bandwidth</em> of each step, replacing next-token prediction with <strong>next-vector prediction</strong>, where a single continuous vector represents a chunk of $K$ discrete tokens.</p>

<hr />

<h2 id="from-next-token-to-next-vector">From next-token to next-vector</h2>

<p>Let a token sequence be</p>

\[X = (x_1, x_2, \dots, x_T), \quad x_t \in \mathcal{V}.\]

<p>We choose a chunk size $K$ and group the sequence into</p>

\[S = T / K\]

<p>non-overlapping chunks (assume divisibility for simplicity). CALM introduces an encoder that maps each chunk of $K$ tokens into a vector in $\mathbb{R}^\ell$, yielding a shorter sequence</p>

\[Z = (z_1, z_2, \dots, z_S), \qquad
z_i = f_{\text{enc}}(x_{(i-1)K+1}, \dots, x_{iK}).\]

<p>The autoregressive factorization becomes</p>

\[p(Z) = \prod_{i=1}^{S} p(z_i \mid z_{&lt;i}).\]

<p>Structurally this looks identical to a standard language model, but the output space is now continuous and uncountable. As a result, the usual “linear layer + softmax over vocabulary” construction no longer applies, and the conditional density $p(z_i \mid z_{&lt;i})$ is intractable. CALM therefore treats the model as <strong>implicit</strong>: it is trained and evaluated through sampling rather than likelihoods.</p>

<hr />

<h2 id="the-chunk-autoencoder">The chunk autoencoder</h2>

<p>At the heart of CALM is a lightweight autoencoder that learns an almost-bijective mapping between</p>

<ul>
  <li>a chunk of $K$ discrete tokens $x_{1:K} \in \mathcal{V}^K$, and</li>
  <li>a continuous latent vector $z \in \mathbb{R}^\ell$.</li>
</ul>

<p>Formally,</p>

\[f_{\text{enc}} : \mathcal{V}^K \rightarrow \mathbb{R}^\ell, \qquad
g_{\text{dec}} : \mathbb{R}^\ell \rightarrow \mathcal{V}^K,\]

<p>with reconstruction $g_{\text{dec}}(f_{\text{enc}}(x_{1:K})) \approx x_{1:K}$.</p>

<p>For simplicity and efficiency, the autoencoder is <strong>context-free</strong>: each chunk is encoded independently of surrounding chunks.</p>

<h3 id="architecture">Architecture</h3>

<p>A common (and CALM-compatible) way to implement the autoencoder is:</p>

<p><strong>Encoder</strong>
1. Embed each token in the chunk: $e_j = E[x_j] \in \mathbb{R}^d$ for $j=1,\dots,K$.
2. Apply a position-wise MLP to each: $\tilde{e}_j = \text{MLP}(e_j)$.
3. Flatten and compress: $\tilde{e} = [\tilde{e}_1;\dots;\tilde{e}_K] \in \mathbb{R}^{Kd}$, then $u = W_c \tilde{e} \in \mathbb{R}^{d}$.
4. Project to latent: $z = W_z \, \phi(u)$ for some nonlinearity $\phi$.</p>

<p><strong>Decoder</strong>
1. Lift: $u’ = W’_z z$.
2. Expand back to $K$ slots: $\hat{e} = W_e \, \phi(u’) \in \mathbb{R}^{Kd}$ and reshape into $(\hat{e}_1,\dots,\hat{e}_K)$.
3. Token logits: $\ell_j = E^\top \hat{e}_j$ (tying input/output embeddings).
4. Tokens: $\hat{x}_j = \arg\max \text{softmax}(\ell_j)$ (or sample).</p>

<h3 id="reconstruction-loss">Reconstruction loss</h3>

<p>The basic objective is standard cross-entropy over the $K$ positions:</p>

\[\mathcal{L}_{\text{ae}}(x_{1:K})
=
- \sum_{i=1}^{K}
\log p_{\text{dec}}\!\left(x_i \mid z = f_{\text{enc}}(x_{1:K})\right).\]

<p>With small $K$ (e.g. $K=4$), very high reconstruction accuracy can be achieved with surprisingly small $\ell$.</p>

<hr />

<h2 id="making-the-latent-space-robust">Making the latent space robust</h2>

<p>A reconstruction-only autoencoder learns a brittle latent space: infinitesimal perturbations in $z$ can decode to unrelated token chunks. This is catastrophic for autoregressive modeling, where prediction errors are unavoidable. CALM therefore explicitly regularizes the latent space.</p>

<h3 id="variational-regularization">Variational regularization</h3>

<p>Instead of outputting a single point, the encoder produces parameters of a diagonal Gaussian:</p>

\[(\mu, \sigma) = f_{\text{enc}}(x_{1:K}), \qquad
z \sim \mathcal{N}(\mu, \sigma^2 I).\]

<p>The training objective becomes</p>

\[\mathcal{L}_{\text{total}}
=
\mathcal{L}_{\text{ae}}
+
\beta \, \mathcal{L}_{\text{KL}},\]

<p>where</p>

\[\mathcal{L}_{\text{KL}}
=
- \frac{1}{2}
\sum_{i=1}^{\ell}
\left(1 + \log \sigma_i^2 - \sigma_i^2 - \mu_i^2 \right).\]

<p>This discourages arbitrarily precise encodings and encourages a smooth latent manifold.</p>

<h3 id="kl-clipping">KL clipping</h3>

<p>To prevent posterior collapse (unused latent dimensions reverting to pure noise), apply per-dimension KL clipping:</p>

\[\mathcal{L}^{\text{clip}}_{\text{KL}}
=
\sum_{i=1}^{\ell}
\max\!\left(\lambda_{\text{KL}}, \mathcal{L}_{\text{KL},i}\right).\]

<p>This ensures every latent dimension carries useful signal.</p>

<h3 id="dropout-induced-redundancy">Dropout-induced redundancy</h3>

<p>Two practical regularizers during autoencoder training:</p>

<ul>
  <li>dropout on the latent vector $z$ before decoding,</li>
  <li>random masking of input tokens within a chunk.</li>
</ul>

<p>Together, these force the representation to be redundant and tolerant to perturbations—exactly what the downstream continuous language model needs.</p>

<hr />

<h2 id="the-calm-autoregressive-loop">The CALM autoregressive loop</h2>

<p>CALM combines three components:</p>

<ol>
  <li>a Transformer backbone,</li>
  <li>a lightweight generative head that samples $z_i$,</li>
  <li>the frozen autoencoder decoder that maps $z_i$ back to $K$ tokens.</li>
</ol>

<p>At step $i$:</p>

<ol>
  <li>The previous $K$ tokens are embedded and compressed into a single vector.</li>
  <li>The Transformer produces a hidden state $h_{i-1}$.</li>
  <li>A stochastic generative head samples $z_i \in \mathbb{R}^\ell$.</li>
  <li>The decoder reconstructs the next $K$ discrete tokens.</li>
</ol>

<p>Although the model predicts vectors, the <strong>input remains discrete tokens</strong>, which empirically stabilizes training.</p>

<hr />

<h2 id="the-energy-based-generative-head">The energy-based generative head</h2>

<p>The generative head is designed for <strong>single-step continuous sampling</strong>. It takes</p>

<ul>
  <li>the Transformer hidden state $h_{i-1} \in \mathbb{R}^d$,</li>
  <li>a noise vector $\varepsilon \sim U[-0.5, 0.5]^{d_{\text{noise}}}$,</li>
</ul>

<p>and outputs $z_i$.</p>

<p>A convenient formulation is:</p>

\[e_0 = W_\varepsilon \varepsilon, \qquad
c = W_h h_{i-1},\]

<p>followed by $B$ residual refinement blocks</p>

\[e_{b+1} = e_b + \text{MLP}_b([e_b, c]),\]

<p>and a final projection</p>

\[z_i = W_{\text{out}} e_B.\]

<hr />

<h2 id="training-without-likelihoods-the-energy-loss">Training without likelihoods: the energy loss</h2>

<p>Because $p(z_i \mid z_{&lt;i})$ is intractable, CALM trains the generative head using a <strong>strictly proper scoring rule</strong>, specifically the <em>energy score</em>.</p>

<p>For a predictive distribution $P$ and observation $y$, the energy score is</p>

\[S(P, y)
=
\mathbb{E}_{x', x'' \sim P}\!\left[\|x' - x''\|^\alpha\right]
-
2 \, \mathbb{E}_{x \sim P}\!\left[\|x - y\|^\alpha\right],
\qquad \alpha \in (0, 2).\]

<p>In practice, expectations are approximated by Monte Carlo sampling. Let</p>

<ul>
  <li>$\tilde{z}<em>{i,1}, \dots, \tilde{z}</em>{i,N}$ be samples from the model,</li>
  <li>$z_{i,1}, \dots, z_{i,M}$ be samples from the encoder’s Gaussian posterior.</li>
</ul>

<p>A common estimator (using $\alpha=1$) is:</p>

\[\mathcal{L}_{\text{energy}}
=
\sum_{i=1}^{S}
\left(
\frac{2}{NM}
\sum_{n=1}^{N}
\sum_{m=1}^{M}
\|\tilde{z}_{i,n} - z_{i,m}\|
-
\frac{1}{N(N-1)}
\sum_{n \neq k}
\|\tilde{z}_{i,n} - \tilde{z}_{i,k}\|
\right).\]

<p>The first term pulls model samples toward the target distribution; the second enforces diversity and prevents collapse.</p>

<hr />

<h2 id="why-this-can-speed-things-up">Why this can speed things up</h2>

<p>Standard autoregressive models generate <strong>one token per step</strong>. CALM generates <strong>$K$ tokens per step</strong>.</p>

<p>Conceptually:</p>

<ul>
  <li>effective sequence length drops from $T$ to $T/K$,</li>
  <li>attention and other sequence-length-dependent costs shrink accordingly.</li>
</ul>

<p>Sequence parallelism helps when $T$ is fixed and large; CALM attacks the problem earlier by changing what a “step” represents.</p>

<hr />

<h2 id="summary">Summary</h2>

<p>CALM reframes language modeling around three ideas:</p>

<ol>
  <li><strong>High-bandwidth steps</strong>: predict continuous vectors instead of low-information tokens.</li>
  <li><strong>Robust latent spaces</strong>: use variational regularization, KL clipping, and dropout so small errors remain decodable.</li>
  <li><strong>Likelihood-free training</strong>: replace cross-entropy with strictly proper scoring rules that only require sampling.</li>
</ol>

<p>The result is a model that remains autoregressive in structure, but changes the unit of generation from <em>token</em> to <em>vector</em>.</p>]]></content><author><name>Tianshu Yu</name></author><category term="Other" /><summary type="html"><![CDATA[In our previous post, Sequence Parallelism, we treated sequence length as a fixed property of the training batch, and asked how to shard computation when a single sequence becomes too long to process efficiently. That discussion focused on parallelizing attention under strict dependency constraints.]]></summary></entry></feed>