Module contents
Lesson 22 of 22Research 110 min

Feature learning at scale: μP and the spectral condition

Study how initialization, layer multipliers and learning rates should scale with width to preserve feature learning. Cover abc parameterizations, maximal update parameterization (μP), hyperparameter transfer between widths and the equivalent spectral condition. Examine Muon and finish with depth scaling and open questions.

After this lesson you can

  • Classify standard, NTK and μP parameterizations by width scaling of initialization, multipliers and learning rates.
  • Reproduce on a GPU the shift in the optimal learning rate with width under standard parameterization and its stability under μP.
  • State the spectral condition for feature learning and verify that μP meets it.
  • Measure layerwise spectral norms of AdamW and Muon updates and relate them to the spectral condition.
  • Evaluate evidence for μP, its extension across depths and its limitations.

Before you start

A tuning step we do not want to repeat

You have found a learning rate for a small model. What happens when you increase its width and keep the other details fixed? The answer depends on how weights, the output readout and each group’s learning rates scale. A rate that works for a narrow model can produce an excessive update in a wider one, or be so small that some features barely change.

InteractiveLearning rate and width

Mean final validation loss over 2 Fashion-MNIST seeds, with 100 steps and widths 64 and 256. Points are measured rates; vertical bars show the minimum and maximum across seeds, not a confidence interval. The rate axis is logarithmic.

Preparing chart…
Measured points: mean and range across seeds
Raten=64n=256
0.00030.7048 (0.6824 to 0.7272)0.5879 (0.5805 to 0.5953)
0.0010.5985 (0.5933 to 0.6038)0.5475 (0.5231 to 0.5720)
0.0030.6242 (0.6135 to 0.6348)0.5729 (0.5658 to 0.5801)
0.010.5824 (0.5574 to 0.6073)0.6657 (0.6240 to 0.7073)
0.030.7077 (0.6739 to 0.7414)0.8337 (0.8108 to 0.8566)

Short run: 2048 training examples and 512 validation examples, batch 64, Adam without weight decay. The smallest mean in this grid is selected, not a continuous optimum; two widths and two seeds do not prove universal transfer. The full lab expands the sweep.

Parameterization
Best measured rate, n=640.01
Best measured rate, n=2560.001
CE at n=256 with base rate0.6657
Minimum CE at n=2560.5475
Compare measured sweeps, the rate selected at base width and its result in the wider network.

The figure shows a bounded experiment, not a guaranteed law. The “optimum” is the best value in a finite grid under a specific budget and split. To measure hyperparameter transfer, select on the proxy and evaluate the same base rate on the larger model; do not select the best large-model value and call it transferred. If both losses are close, also report variation across seeds and any non-finite run.

From a fixed kernel to changing features

In certain width limits and parameterizations, training approaches a model linearized around initialization: the effective kernel barely changes. This kernel regime can learn a function, but does not imply the same representation evolution as a finite network. Yang and Hu compare parameterization families in width limits and identify others where feature learning persists. The order of limits and optimizer scaling are part of that claim; it does not follow that a finite standard network never learns representations.

For a fixed probe XX, compare activations of the same network before and after the step, for example

RMS(ΔHℓ)=1∣Hℓ∣∑i(Hℓ,idespueˊs−Hℓ,iantes)2.\mathrm{RMS}(\Delta H_\ell)=\sqrt{\frac{1}{|H_\ell|}\sum_i(H_{\ell,i}^{\mathrm{después}}-H_{\ell,i}^{\mathrm{antes}})^2}.

It can also be divided by the initial RMS if positive; an initially zero layer leaves that ratio undefined. Do not compare neuron 17 of two independently trained networks as if it were the same feature. The bars below use a common probe within each run and show calculated changes, not a directly observed asymptotic limit.

InteractiveHow much features change

RMS(Hₜ − H₀) / RMS(H₀) on the same validation probe: mean of 2 seeds. Adjacent bars compare widths in the same layer; step 1 is one update and later steps measure accumulated changes.

Preparing chart…

Fashion-MNIST, short Adam run with widths 64 and 256. A ratio with zero denominator is undefined. NTK was not measured in these data. Two widths and two seeds do not establish an asymptotic law.

View
Parameterization
Layer 1, n=643.0661
Layer 1, n=2561.5023
Layer 2, n=643.6046
Layer 2, n=2561.5530
Observe activation changes on the same probe by layer and width.

The second view of the figure is a linear model constructed so each step can be calculated, not an additional Fashion-MNIST measurement. With f(x)=V⊤Uxf(x)=V^\top Ux, x=1x=1, target y=1y=1 and loss (f−y)2/2(f-y)^2/2, take Ui=1U_i=1 and alternating signs in VV, so f(1)=0f(1)=0. In standard and NTK, Vi=±1/nV_i=\pm1/\sqrt n; in μP, Vi=±1/nV_i=\pm1/n. With reference rate η\eta, the effective rates (ηU,ηV)(\eta_U,\eta_V) are (η,η)(\eta,\eta), (η,η/n)(\eta,\eta/n) and (nη,η/n)(n\eta,\eta/n), respectively. The initial gradient is −V-V for UU and −U-U for VV. The μP output rate η/n\eta/n applies to the effective weight: if V=Vbruto/nV=V_{\rm bruto}/n and the raw weight uses rate nηn\eta, the factor 1/n1/n appears once in backward and once when returning to the effective weight.

Therefore the relative RMS of ΔU\Delta U is exactly η/n\eta/\sqrt n in standard and NTK, and η\eta in μP. After the step, the output is η(n+1)\eta(n+1) in standard and 2η2\eta in NTK and μP. This example simultaneously illustrates standard output growth and the hidden change that vanishes in NTK. Deterministic initializations and the chosen alignment make the calculation verifiable; a conclusion for general networks and data requires the sources’ assumptions and does not follow from this example alone. The measured view uses Adam and is not an optimizer comparison with the SGD model.

What parameterizing a family means

An abc parameterization specifies how three pieces change with width nn: a parameter’s multiplier, initialization scale and learning rate. A common representation is W=n−aW~W=n^{-a}\widetilde W, with std⁡(W~)∝n−b\operatorname{std}(\widetilde W)\propto n^{-b} and η∝n−c\eta\propto n^{-c}, using exponents per tensor. Depending on the convention, powers can move between WW and W~\widetilde W. Comparing two tables also requires transforming gradients and learning rate, not just copying the variance.

The example’s standard parameterization uses He initialization in ReLU layers, output standard deviation proportional to 1/n1/\sqrt n, multiplier one and a common rate. A typical NTK parameterization places explicit factors such as 1/fan_in1/\sqrt{\mathrm{fan\_in}} and uses a rate on the unscaled variables. In effective variables, the multiplier also scales their gradient. A description in powers is a rule for a family of widths, not a mandatory choice of constant for a single width.

With a global rate in standard parameterization, input, hidden-layer and output changes can scale differently; as nn grows, the best compromise rate can shift. This explains why measuring each layer is useful. It does not prove that every standard problem shifts its optimum in the same direction or that the alternative is better for every architecture or budget.

The mechanism can be seen explicitly. Consider the scalar linear model f(x)=V⊤Uxf(x)=V^\top Ux, with independent Ui∼N(0,1)U_i\sim\mathcal N(0,1) and Vi∼N(0,1/n)V_i\sim\mathcal N(0,1/n). The initial output remains order one in probability. For a differentiable loss, a fixed-rate SGD step has the form V′=V+θUV'=V+\theta U and U′=U+θVU'=U+\theta V, where θ\theta incorporates rate, error and input. Expanding,

V′⊤U′=V⊤U+θU⊤U+θV⊤V+θ2V⊤U.V'^\top U'=V^\top U+\theta U^\top U+\theta V^\top V+\theta^2V^\top U.

Since U⊤U/n→1U^\top U/n\to 1, the second term grows as θn\theta n if θ\theta does not decrease with width. Keeping that term bounded requires reducing the rate in this example, but a single rate also reduces updates to other layers. This is a calculation for a particular architecture and step, not a universal formula for Adam’s optimum. Section 5 of Tensor Programs V develops this contrast and shows the same conflict between scales in a Transformer.

In NTK parameterization with gradient descent, the effective matrix is written W~/fan_in\widetilde W/\sqrt{\mathrm{fan\_in}}. The same factor appears when differentiating with respect to W~\widetilde W: a step of size η\eta in that variable is equivalent to rate η/fan_in\eta/\mathrm{fan\_in} on the effective weight. For a square hidden layer, that rate decreases as 1/n1/n. In the limit and under the analysis assumptions, hidden spectral updates become small and the kernel stays approximately fixed: the function can change, but the limiting regime does not capture order-one feature evolution. This calculation concerns SGD; Adam normalizes gradients and requires its own scales.

μP in a reproducible convention

Maximal update parameterization seeks a regime in which relevant feature updates neither vanish with width nor explode, under the analysis assumptions. We use the equivalent formulation in table 8 of Tensor Programs V, normalized to base width n0n_0. Consider an MLP din→n→n→doutd_{\rm in}\to n\to n\to d_{\rm out}, with fixed input and output dimensions and r=n/n0r=n/n_0:

Tensor or layerWeight initializationMultiplierAdam rateSGD scale relative to base
Inputvariance 2/din2/d_{\rm in} for ReLU1η\etarr
Hidden matrix n×nn\times nvariance 2/n2/n1η/r\eta/r1
Raw output weightsvariance 1/n01/n_01/r1/rη\etarr
Biases of width nnzero in this example1η\etarr
Output bias, fixed dimensionzero1η\eta1

Constants 22 and 1/n01/n_0 specify our base choice; the source table establishes scaling orders and allows other constants. The output multiplier applies to the matrix product, not the bias. For SGD, input weight and hidden bias rates scale with their output dimension, and output weight rates with their input dimension; output bias does not grow with nn. The lab uses Adam without decay. Do not copy the Adam rate into SGD without changing the rule.

In the Adam implementation, the functional readout is (n0/n)Wouth+bout(n_0/n)W_{\rm out}h+b_{\rm out}; raw output weights are not on the same scale as that effective operator. A multiplier is not decoration: it appears in backward too. The formulations in tables 3 and 8 can describe equivalent functions if initialization, multipliers and rates are transformed together. With Adam, ε\varepsilon and additional terms can break a naive algebraic equivalence: record their values and verify the step, especially with small gradients.

The official mup library marks dimensions that grow and assigns rates accordingly. If installed, the lab compares a manual model against it: it checks forward, gradients, groups and one step. That parity does not automatically turn a generic implementation of any architecture into μP; embeddings, shared weights and layers with fixed dimensions require declaring their base shapes.

Transfer is a measurable hypothesis

Yang and colleagues tuned a proxy of about 40 million parameters for a 6.7 billion parameter GPT; they estimated tuning cost at 7% of target pretraining. Their table 7 reports validation loss of 1.98 for the transferred configuration and 2.03 for their reference retraining. The authors note that the transferred model used FP32 after numerical problems, while the reference used FP16 and a different attention variant. These are results of that protocol, not an isolated causal comparison of parameterization.

For your own trial, fix architecture, preprocessing, seeds, steps and criterion; sweep the same base rates for each parameterization. Select on validation at small width, apply that choice at large width and compare against the best point in the large-width grid under the same budget. A small difference would support transfer in that domain; failure is also a result. Hold out an independent test set until the end if selecting a configuration.

The base rate and certain multipliers are candidates for transfer, not every hyperparameter. Regularization also depends on data and overfitting; batch size and duration define other experimental axes. Tensor Programs V observes approximate transfer in specific ranges and models, with exceptions. Everett and colleagues study other alignment and optimizer assumptions, also find transfer with other parameterizations and highlight the role of Adam’s ε\varepsilon. There is no guarantee that keeping a decay, batch size or schedule value is optimal when changing scale.

Tables 1 and 2 of Tensor Programs V distinguish three roles. Learning rate, momentum, Adam coefficients, schedule, initialization variance and parameter multipliers are candidates for transfer. Regularization hyperparameters such as dropout and weight decay are not included in that general rule. Width, depth, batch size, duration and sequence length are dimensions across which one can try to transfer the former: for several of them the evidence is empirical and depends on the model and range. A rate remaining stable as batch size changes does not claim that the optimal batch size transfers.

In the data included here, the standard network selects rate 0.010.01 at width 64 and 0.0010.001 at 256. Applying 0.010.01 to the wide network gives mean loss 0.66570.6657, versus 0.54750.5475 for the best wide point: a difference of 0.11820.1182. In μP the corresponding difference is 0.03010.0301; at rate 0.0030.003 the two wide seeds give 0.53030.5303 and 0.62590.6259, a separation of 0.09560.0956. These figures describe two seeds and a grid of five rates: they are indications of behavior in this trial, not a guarantee of transfer outside it.

An earlier run of the same protocol and seeds obtained, at width 256 and rate 0.010.01, mean losses of 0.71110.7111 for standard and 0.58900.5890 for μP, versus 0.66570.6657 and 0.60820.6082 in the run feeding the figure. Both sets of results are retained in the interactive’s folder. The observed discrepancy makes repeatability part of the result; by itself it does not identify the cause.

In AdamW, if a layer uses constant rate ηℓ\eta_\ell and decoupled decay λ\lambda, the multiplicative part of one step is 1−ηℓλ1-\eta_\ell\lambda. After TT steps, the isolated contribution of the initial weight is multiplied by (1−ηℓλ)T(1-\eta_\ell\lambda)^T; gradient updates also affect the final weight. Changing the group rate or number of steps changes that retention even if λ\lambda stays the same. With a variable schedule, replace the power with the product of each step’s factors. Thus “keeping the same decay” does not automatically settle what regularization is being compared.

The spectral condition and alignment

Let W∈Rm×nW\in\mathbb R^{m\times n}, with n=fan_inn=\mathrm{fan\_in} and m=fan_outm=\mathrm{fan\_out}. The spectral condition of Yang, Simon and Bernstein compares operator norms of effective weights and updates with the scale

∥W∥2=Θ ⁣(m/n),∥ΔW∥2=Θ ⁣(m/n),\|W\|_2=\Theta\!\left(\sqrt{m/n}\right),\qquad \|\Delta W\|_2=\Theta\!\left(\sqrt{m/n}\right),

within their family and asymptotic regime. A constant learning rate can appear as an update factor. Θ\Theta indicates upper and lower bounds with constants independent of width: it does not mean the norm must be exactly ηm/n\eta\sqrt{m/n} at each step.

To check the scale of weights in the μP table, take fixed input dimension dd and output dimension kk, hidden width nn and fixed base width n0n_0. With approximate Gaussian edge σ(fan_in+fan_out)\sigma(\sqrt{\mathrm{fan\_in}}+\sqrt{\mathrm{fan\_out}}), the input matrix has norm of order n/d\sqrt{n/d} and the hidden matrix order one. At the output, the effective weight multiplies a matrix of standard deviation 1/n01/\sqrt{n_0} by n0/nn_0/n: its standard deviation is n0/n\sqrt{n_0}/n and its edge is of order 1/n1/\sqrt n. Since kk and n0n_0 remain fixed, this has the same order as k/n\sqrt{k/n}. Standard He output initialization, in contrast, has an order-one edge and its ratio to k/n\sqrt{k/n} grows as n\sqrt n.

The μP rate rules complete the comparison for updates, but the rate table alone does not establish their norms: an assumption on gradient structure is required. Yang, Simon and Bernstein derive the scaling equivalence through outer products and, for adaptive optimizers, an additional argument about coordinatewise processing. The panel measures two finite widths and one seed: it lets us look for a trend, not prove an Θ\Theta bound.

If ∥x∥2=Θ(n)\|x\|_2=\Theta(\sqrt n), inequality ∥ΔWx∥2≤∥ΔW∥2∥x∥2\|\Delta W x\|_2\le\|\Delta W\|_2\|x\|_2 gives an upper bound of order m\sqrt m. A lower bound requires the update to align nondegenerately with xx: the same operator norm can act in an orthogonal direction and produce zero. In the aligned example, output norm Θ(m)\Theta(\sqrt m) means order-one RMS, not that all coordinates change by an order-one amount. One-hot inputs and other normalizations require redoing the calculation for their actual norm.

InteractiveSpectral norms by layer

Bars use a logarithmic scale so both measurement and reference are visible. Blue: effective spectral norm. Orange: η√(fan_out/fan_in). The reference expresses a scale, not a required equality.

Input
Measured: 0.40970
Reference: 0.00086
Measured / reference: 477.98; relative power residual: 7.78e-8
Hidden
Measured: 0.10342
Reference: 0.00300
Measured / reference: 34.47; relative power residual: 8.62e-8
Output
Measured: 0.04162
Reference: 0.00119
Measured / reference: 35.09; relative power residual: 8.09e-8

Measured / reference ratio against width, by layer. The vertical scale is logarithmic: an approximately horizontal line suggests ratio stability in these two measurements.

Preparing chart…

Fashion-MNIST, short run of 80 steps, one seed and widths 64 and 256. The norm includes the multiplier in the effective output matrix. Muon acts on the hidden matrix and AdamW on the rest; it is not pure Muon. A small residual does not certify that the largest singular value was found. Weight decay is zero.

Method
Quantity
Nominal rate η0.003
StatusComplete
Compare effective weights and measured updates with the scale reference for each shape.

To interpret the panel, distinguish spectral and Frobenius norms: the same Frobenius norm can be distributed across many singular values. In μP measure (n0/n)Wout(n_0/n)W_{\rm out} and its effective change, not just the raw weight. A power estimator can underestimate the extreme if it has not converged; the cell records a residual so you can detect the problem. A small residual indicates only proximity to some eigenvector; by itself it does not certify that the largest was found. The scale reference is a guide, not by itself proof of alignment or better loss.

For example, in the first step of the short run the ratio of hidden update norm to reference goes from 34.4734.47 to 147.91147.91 for standard AdamW when width changes from 64 to 256; in μP it goes from 34.4734.47 to 32.8732.87, and with Muon from 1.20231.2023 to 1.20151.2015. Constant factors, including input size and base width, can make a ratio very different from one without invalidating an Θ\Theta scale. At the output of the Muon hybrid, which uses standard AdamW in that layer, the ratio goes from 35.0935.09 to 131.72131.72: this measurement describes a scale difference but does not itself prove the cause of the loss transfer observed below.

Muon as a matrix update

The Muon optimizer takes a momentum direction for hidden matrices and applies a polynomial Newton-Schulz iteration approximating its orthogonalization. If G=UΣV⊤G=U\Sigma V^\top has full rank in its smaller dimension, the exact polar factor UV⊤UV^\top replaces its singular values with ones; a few polynomial iterations need not yield exactly that matrix. With deficient rank, the partial polar factor must be distinguished from non-unique semiorthogonal extensions. The browser cell uses a seeded full-rank matrix.

In the practical implementation used here, the shape scale is max⁡(1,m/n)\sqrt{\max(1,m/n)}, with mm rows and nn columns. This can be checked in the update function of the Muon repository. For wide matrices it does not match m/n\sqrt{m/n}; therefore do not claim exact equality with the spectral condition for every shape. The experiment uses Muon on the hidden matrix and AdamW for input, output and biases, following the division described by Jordan. The four compared configurations use declared nominal rate and decay: this is not a fairly tuned optimizer competition.

The lab uses mt=0,95mt−1+0,05gtm_t=0,95m_{t-1}+0,05g_t and orthogonalizes 0,05gt+0,95mt0,05g_t+0,95m_t. The formulation in the spectral descent lesson accumulates Bt=0,95Bt−1+gtB_t=0,95B_{t-1}+g_t and orthogonalizes gt+0,95Btg_t+0,95B_t: with zero initial states both inputs are proportional by 0,050,05. Normalization with epsilon means that proportionality does not imply exact numerical identity. In addition, our lab calculates the polynomial in float32, while Jordan’s original example uses bfloat16; record these choices when comparing.

Changing depth is a different problem

Scaling width at fixed depth does not determine how a residual branch should scale when adding blocks. Tensor Programs VI studies width and then depth limits in residual networks: for one-layer blocks it identifies Depth-μP, but also points out limitations for deeper blocks such as Transformers. In another residual-network family, Bordelon and colleagues analyze a branch scaled by 1/L1/\sqrt L and report transfer across widths and depths in their experiments. Do not transfer that exponent to another architecture without checking its parameterization, normalization and order of limits.

Labs

The browser cell checks the need for alignment and compares an exact polar factor with the Muon polynomial on an explicit matrix. The two local labs train real models, save their configurations and allow a short test. Their charts use those runs; the reader can run the full budget on their own GPU.

[ ]One exact step in standard, NTK and μPBrowser
import numpy as np

eta = 0.1
for n in (16, 64, 256, 1024):
    u = np.ones(n)
    signs = np.tile([1., -1.], n // 2)
    for method in ('estandar', 'ntk', 'mup'):
        v = signs / (n if method == 'mup' else np.sqrt(n))
        lr_u = eta * n if method == 'mup' else eta
        lr_v = eta if method == 'estandar' else eta / n
        assert np.isclose(v @ u, 0.)
        # Para x=1 e y=1, el gradiente de la pérdida es -v y -u.
        u_after = u + lr_u * v
        v_after = v + lr_v * u
        relative_change = np.sqrt(np.mean((u_after - u) ** 2))
        prediction = v_after @ u_after
        expected_change = eta if method == 'mup' else eta / np.sqrt(n)
        expected_prediction = eta * (n + 1) if method == 'estandar' else 2 * eta
        assert np.isclose(relative_change, expected_change)
        assert np.isclose(prediction, expected_prediction)
        print(method, n, 'cambio RMS:', round(relative_change, 6),
              'salida:', round(prediction, 4))
[ ]Alignment and approximate polar factorBrowser
import numpy as np

# Una misma norma espectral puede actuar o no sobre la entrada.
n,m=4,6
x=np.ones(n)
u=np.ones(m)/np.sqrt(m)
v=x/np.linalg.norm(x)
w=np.array([1.,-1.,0.,0.])/np.sqrt(2)
scale=np.sqrt(m/n)
aligned=scale*np.outer(u,v)
orthogonal=scale*np.outer(u,w)
assert np.isclose(np.linalg.norm(aligned,2),scale)
assert np.isclose(np.linalg.norm(orthogonal,2),scale)
assert np.isclose(np.linalg.norm(aligned@x),np.sqrt(m))
assert np.linalg.norm(orthogonal@x)<1e-12
print('Normas de operador:',np.linalg.norm(aligned,2),np.linalg.norm(orthogonal,2))
print('Respuestas alineada y ortogonal:',np.linalg.norm(aligned@x),np.linalg.norm(orthogonal@x))

# El polinomio es el de Muon; no confundas sus cinco pasos con una SVD.
rng=np.random.default_rng(22)
matrix=rng.normal(size=(7,4))
left,_,right=np.linalg.svd(matrix,full_matrices=False)
polar=left@right
approx=matrix/(np.linalg.norm(matrix)+1e-7)
for _ in range(5):
    [email protected]
    approx=3.4445*approx+(-4.775*gram+2.0315*gram@gram)@approx
exact_values=np.linalg.svd(polar,compute_uv=False)
approx_values=np.linalg.svd(approx,compute_uv=False)
print('Valores singulares polar exacta:',np.round(exact_values,5))
print('Valores singulares del polinomio:',np.round(approx_values,5))
assert np.allclose(exact_values,1)
assert not np.allclose(approx_values,1,atol=1e-4)
[ ]Tune a proxy and transferLocal GPU
"""Barrido de μTransfer con Fashion-MNIST; no consulta el test oficial.

Instala torch, torchvision y, opcionalmente, mup. ORYON_VERIFY_SHORT=1 usa
una prueba breve. ORYON_MUTRANSFER_OUTPUT cambia el destino JSON.
"""
import json
import math
import os
import statistics
from pathlib import Path

import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import FashionMNIST

torch.set_num_threads(1)
SHORT = os.getenv('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
BASE = 64 if SHORT else 128
# La anchura 4096 implica mucha más memoria y trabajo que el modo corto.
WIDTHS = [BASE, 4 * BASE] if SHORT else [BASE, 4 * BASE, 8 * BASE, 32 * BASE]
RATES = [0.0003, 0.001, 0.003, 0.01, 0.03] if SHORT else [0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1]
SEEDS = [22, 23] if SHORT else [22, 23, 24]
STEPS, EVERY, BATCH = (100, 20, 64) if SHORT else (500, 50, 128)
NTRAIN, NVALID = (2048, 512) if SHORT else (50000, 10000)
EPS = 1e-8
OUTPUT = Path(os.getenv('ORYON_MUTRANSFER_OUTPUT', 'fashion-mutransfer.json'))


class Network(nn.Module):
    def __init__(self, width, parametrization):
        super().__init__()
        self.width, self.parametrization = width, parametrization
        self.input = nn.Linear(784, width)
        self.hidden = nn.Linear(width, width)
        self.output = nn.Linear(width, 10)
        for layer in (self.input, self.hidden):
            nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')
            nn.init.zeros_(layer.bias)
        # En μP, varianza de salida cruda constante al aumentar anchura.
        nn.init.normal_(self.output.weight, std=1 / math.sqrt(BASE if parametrization == 'mup' else width))
        nn.init.zeros_(self.output.bias)

    def forward(self, x, return_features=False):
        h1 = F.relu(self.input(x))
        h2 = F.relu(self.hidden(h1))
        scale = BASE / self.width if self.parametrization == 'mup' else 1.0
        logits = F.linear(scale * h2, self.output.weight, self.output.bias)
        return (logits, (h1, h2)) if return_features else logits


def optimizer(model, rate):
    # Adam sin weight decay: evita una discrepancia de convenciones en AdamW.
    groups = []
    for name, parameter in model.named_parameters():
        lr = rate * BASE / model.width if model.parametrization == 'mup' and name == 'hidden.weight' else rate
        groups.append({'params': [parameter], 'lr': lr, 'name': name})
    return torch.optim.Adam(groups, eps=EPS)


def library_parity():
    """Compara función, grupos y un paso idéntico con microsoft/mup si está instalado."""
    try:
        import mup
    except ImportError:
        return {'available': False, 'reason': 'Instala mup para ejecutar la comparación opcional.'}

    class LibraryNetwork(nn.Module):
        def __init__(self, width):
            super().__init__()
            self.input = nn.Linear(784, width)
            self.hidden = nn.Linear(width, width)
            self.output = mup.MuReadout(width, 10)

        def forward(self, x):
            return self.output(F.relu(self.hidden(F.relu(self.input(x)))))

    torch.manual_seed(111)
    width = 2 * BASE
    own = Network(width, 'mup')
    lib = LibraryNetwork(width)
    # delta identifica las dimensiones que crecen, incluso cuando width=base.
    base, delta = LibraryNetwork(BASE), LibraryNetwork(2 * BASE)
    mup.set_base_shapes(lib, base, delta=delta, rescale_params=False)
    with torch.no_grad():
        for (_, p), (_, q) in zip(own.named_parameters(), lib.named_parameters()):
            q.copy_(p)
    opt_own = optimizer(own, 0.003)
    opt_lib = mup.MuAdam(lib.parameters(), lr=0.003, eps=EPS, weight_decay=0.)
    rates_own = {name: group['lr'] for (name, _), group in zip(own.named_parameters(), opt_own.param_groups)}
    lr_by_id = {id(p): g['lr'] for g in opt_lib.param_groups for p in g['params']}
    rates_lib = {name: lr_by_id[id(p)] for name, p in lib.named_parameters()}
    x = torch.randn(5, 784)
    target = torch.tensor([0, 1, 2, 3, 4])
    a, b = own(x), lib(x)
    forward_diff = (a - b).abs().max().item()
    F.cross_entropy(a, target).backward()
    F.cross_entropy(b, target).backward()
    grad_diff = max((p.grad - q.grad).abs().max().item() for p, q in zip(own.parameters(), lib.parameters()))
    opt_own.step()
    opt_lib.step()
    step_diff = max((p - q).abs().max().item() for p, q in zip(own.parameters(), lib.parameters()))
    assert rates_own == rates_lib and forward_diff < 1e-6 and grad_diff < 1e-6 and step_diff < 1e-6
    return {'available': True, 'width': width, 'max_forward_difference': forward_diff,
            'max_gradient_difference': grad_diff, 'max_parameter_difference_after_step': step_diff,
            'own_learning_rates': rates_own, 'library_learning_rates': rates_lib}


def metrics(model, x, y):
    with torch.no_grad():
        logits = model(x)
        loss = F.cross_entropy(logits, y)
        if not torch.isfinite(logits).all() or not torch.isfinite(loss):
            return None
        return {'loss': float(loss), 'accuracy': float((logits.argmax(1) == y).float().mean())}


def safe_rms(tensor):
    """Recurre a float64 si el cuadrado desborda o subdesborda a cero."""
    value = tensor.square().mean().sqrt()
    if not torch.isfinite(value) or (value == 0 and torch.count_nonzero(tensor) > 0):
        value = tensor.double().square().mean().sqrt()
    return float(value) if torch.isfinite(value) else None


def safe_difference_rms(a, b):
    """La resta se recalcula en float64 si solo float32 desborda."""
    difference = a - b
    if not torch.isfinite(difference).all() and torch.isfinite(a).all() and torch.isfinite(b).all():
        difference = a.double() - b.double()
    return safe_rms(difference)


def run(train_x, train_y, valid_x, valid_y, width, rate, seed, parametrization):
    torch.manual_seed(seed)
    model = Network(width, parametrization).to(DEVICE)
    opt = optimizer(model, rate)
    batches = torch.randint(len(train_x), (STEPS, BATCH), generator=torch.Generator().manual_seed(seed + 7000))
    probe = valid_x[:min(128, len(valid_x))]
    with torch.no_grad():
        initial_features = [v.clone() for v in model(probe, True)[1]]
        initial_rms = [safe_rms(v) for v in initial_features]
    if any(v is None for v in initial_rms):
        return {'parametrization': parametrization, 'width': width, 'rate': rate,
                'seed': seed, 'status': 'nonfinite_initial_features', 'history': []}
    history, status = [], 'complete'
    for step in range(STEPS + 1):
        if step % EVERY == 0 or step == 1:
            train = metrics(model, train_x[:min(512, len(train_x))], train_y[:min(512, len(train_y))])
            valid = metrics(model, valid_x, valid_y)
            if train is None or valid is None:
                status = 'nonfinite_evaluation'
                break
            with torch.no_grad():
                features = model(probe, True)[1]
                delta = [safe_difference_rms(a, b) for a, b in zip(features, initial_features)]
                if any(d is None for d in delta):
                    status = 'nonfinite_features'
                    break
                relative = [d / initial if initial > 0 else None for d, initial in zip(delta, initial_rms)]
            history.append({'step': step, 'train': train, 'validation': valid,
                            'feature_initial_rms': initial_rms,
                            'feature_change_rms': delta, 'feature_change_relative': relative})
        if step == STEPS:
            break
        ix = batches[step].to(DEVICE)
        loss = F.cross_entropy(model(train_x[ix]), train_y[ix])
        if not torch.isfinite(loss):
            status = 'nonfinite_training'
            break
        opt.zero_grad(set_to_none=True)
        loss.backward()
        if not torch.stack([torch.isfinite(p.grad).all() for p in model.parameters() if p.grad is not None]).all():
            status = 'nonfinite_gradient'
            break
        opt.step()
        if not torch.stack([torch.isfinite(p).all() for p in model.parameters()]).all():
            status = 'nonfinite_parameters'
            break
    return {'parametrization': parametrization, 'width': width, 'rate': rate,
            'seed': seed, 'status': status, 'history': history}


def plot_curves(records):
    import matplotlib.pyplot as plt
    fig, axes = plt.subplots(1, 2, figsize=(12, 4), sharey=True, constrained_layout=True)
    for ax, parametrization in zip(axes, ('standard', 'mup')):
        for width in WIDTHS:
            means = []
            for rate in RATES:
                group = [r for r in records if r['parametrization'] == parametrization
                         and r['width'] == width and r['rate'] == rate]
                vals = [r['history'][-1]['validation']['loss'] for r in group
                        if r['status'] == 'complete' and r['history'][-1]['step'] == STEPS]
                means.append(statistics.mean(vals) if len(vals) == len(SEEDS) else float('nan'))
            ax.plot(RATES, means, marker='o', label=f'anchura {width}')
        ax.set(xscale='log', title=parametrization, xlabel='Tasa base de Adam', ylabel='CE media de validación')
        ax.grid(alpha=0.25)
        ax.legend()
    target = OUTPUT.with_suffix('.png')
    fig.savefig(target, dpi=150)
    plt.close(fig)
    print('Gráfico:', target, flush=True)


def main():
    FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
    dataset = FashionMNIST(Path.home() / '.cache' / 'atlas-data', train=True, download=True)
    order = torch.randperm(len(dataset), generator=torch.Generator().manual_seed(22000))
    train_ids, valid_ids = order[:NTRAIN], order[NTRAIN:NTRAIN + NVALID]
    assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
    xtrain = dataset.data[train_ids].reshape(NTRAIN, -1).float() / 255
    xvalid = dataset.data[valid_ids].reshape(NVALID, -1).float() / 255
    mean, std = xtrain.mean(), xtrain.std(unbiased=False)
    xtrain = ((xtrain - mean) / (std + 1e-6)).to(DEVICE)
    xvalid = ((xvalid - mean) / (std + 1e-6)).to(DEVICE)
    ytrain = dataset.targets[train_ids].to(DEVICE)
    yvalid = dataset.targets[valid_ids].to(DEVICE)
    parity = library_parity()
    records = []
    for parametrization in ('standard', 'mup'):
        for width in WIDTHS:
            for rate in RATES:
                for seed in SEEDS:
                    record = run(xtrain, ytrain, xvalid, yvalid, width, rate, seed, parametrization)
                    records.append(record)
                    last = record['history'][-1] if record['history'] else None
                    print(parametrization, width, rate, seed, record['status'],
                          None if last is None else round(last['validation']['loss'], 5), flush=True)
    result = {'protocol': {'dataset': 'Fashion-MNIST train', 'official_test_used': False,
              'short': SHORT, 'train_size': NTRAIN, 'validation_size': NVALID,
              'partition_seed': 22000, 'training_steps': STEPS, 'batch_size': BATCH,
              'widths': WIDTHS, 'base_width': BASE, 'rates': RATES, 'seeds': SEEDS,
              'optimizer': 'Adam', 'epsilon': EPS, 'weight_decay': 0,
              'device': str(DEVICE), 'torch_version': torch.__version__,
              'feature_probe': 'primeros 128 ejemplos de validación; RMS y razón frente al inicio; denominador cero no definido',
              'selection': 'menor pérdida final media de validación en la rejilla, solo corridas completas'},
              'library_parity': parity, 'records': records}
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT.write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False), encoding='utf-8')
    plot_curves(records)
    print('JSON:', OUTPUT, flush=True)
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second lab includes a separate sweep of the Muon hybrid. In the short run, with two seeds and 80 steps, the rate selected at width 64 was 0.001. At width 256 it produced mean cross-entropy of 0.798387; the best grid point was 0.0003, with 0.760271. The selected rate does not match that discrete optimum: one grid and two seeds do not establish a transfer law. Norms are measured in another comparison at a common nominal rate that does not aim to optimize each method.

[ ]Measure spectral updatesLocal GPU
"""Normas de operador durante actualizaciones reales en Fashion-MNIST.

Muón solo actúa en la matriz oculta; entrada, salida y sesgos usan AdamW.
Las configuraciones usan decay cero y la misma tasa nominal por claridad,
lo que no es un ajuste competitivo de hiperparámetros. ORYON_VERIFY_SHORT=1
ejecuta una prueba corta. ORYON_SPECTRAL_OUTPUT cambia el destino JSON.
"""
import json
import math
import os
import statistics
from pathlib import Path

import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import FashionMNIST

torch.set_num_threads(1)
SHORT = os.getenv('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
BASE = 64 if SHORT else 128
# En la ejecución completa, la matriz oculta 4096×4096 es costosa.
WIDTHS = [BASE, 4 * BASE] if SHORT else [BASE, 4 * BASE, 8 * BASE, 32 * BASE]
STEPS, TRAIN_N, VALID_N, BATCH = (80, 1024, 256, 64) if SHORT else (400, 10000, 2000, 128)
SNAPSHOTS = [1, 10, 40, 80] if SHORT else [1, 10, 100, 200, 400]
RATE, SEED, POWER_STEPS = 0.003, 22023, 64
TRANSFER_RATES = [0.0003, 0.001, 0.003, 0.01, 0.03] if SHORT else [0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1]
TRANSFER_SEEDS = [22023, 22024] if SHORT else [22023, 22024, 22025]
OUTPUT = Path(os.getenv('ORYON_SPECTRAL_OUTPUT', 'fashion-spectral.json'))


class Network(nn.Module):
    def __init__(self, width, mup):
        super().__init__()
        self.width, self.mup = width, mup
        self.input = nn.Linear(784, width)
        self.hidden = nn.Linear(width, width)
        self.output = nn.Linear(width, 10)
        for layer in (self.input, self.hidden):
            nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')
            nn.init.zeros_(layer.bias)
        nn.init.normal_(self.output.weight, std=1 / math.sqrt(BASE if mup else width))
        nn.init.zeros_(self.output.bias)

    def forward(self, x):
        x = F.relu(self.input(x))
        x = F.relu(self.hidden(x))
        scale = BASE / self.width if self.mup else 1.
        return F.linear(x * scale, self.output.weight, self.output.bias)


def orthogonalize_newton_schulz(matrix, iterations=5):
    """Polinomio quíntico Muon, no descomposición polar exacta."""
    a, b, c = 3.4445, -4.7750, 2.0315
    x = matrix.float()
    if x.shape[0] > x.shape[1]:
        x = x.T
        transpose = True
    else:
        transpose = False
    x = x / (x.norm() + 1e-7)
    for _ in range(iterations):
        gram = x @ x.T
        x = a * x + (b * gram + c * (gram @ gram)) @ x
    return x.T if transpose else x


def spectral_norm(matrix):
    """Potencia sobre WᵀW; devuelve None si los cálculos no son finitos."""
    w = matrix.detach().float()
    generator = torch.Generator().manual_seed(22024)
    v = torch.randn(w.shape[1], generator=generator).to(w.device)
    v = v / v.norm()
    for _ in range(POWER_STEPS):
        z = w.T @ (w @ v)
        n = z.norm()
        v = z / n.clamp_min(1e-30)
    z = w.T @ (w @ v)
    eigenvalue = torch.dot(v, z)
    residual = (z - eigenvalue * v).norm() / eigenvalue.clamp_min(1e-30)
    norm = eigenvalue.clamp_min(0).sqrt()
    if not torch.isfinite(norm) or not torch.isfinite(residual):
        return None
    return {'norm': float(norm), 'relative_residual': float(residual)}


def parameters_finite(model):
    return bool(torch.stack([torch.isfinite(p).all() for p in model.parameters()]).all())


def actual_matrices(model):
    scale = BASE / model.width if model.mup else 1.
    return {'input': model.input.weight.detach().clone(),
            'hidden': model.hidden.weight.detach().clone(),
            'output': scale * model.output.weight.detach().clone()}


def make_optimizer(model, method, rate=RATE):
    groups = []
    for name, p in model.named_parameters():
        if method == 'muon' and name == 'hidden.weight':
            continue
        lr = rate * BASE / model.width if method == 'mup' and name == 'hidden.weight' else rate
        groups.append({'params': [p], 'lr': lr})
    if method == 'sgd':
        return torch.optim.SGD(groups, momentum=0.9, weight_decay=0.)
    return torch.optim.AdamW(groups, eps=1e-8, weight_decay=0.)


def muon_step(model, momentum, rate):
    with torch.no_grad():
        grad = model.hidden.weight.grad
        momentum.lerp_(grad, 1 - 0.95)
        direction = grad.lerp(momentum, 0.95)
        direction = orthogonalize_newton_schulz(direction)
        out_dim, in_dim = direction.shape
        model.hidden.weight.add_(direction, alpha=-rate * math.sqrt(max(1., out_dim / in_dim)))


def run(train_x, train_y, valid_x, valid_y, width, method, batches):
    torch.manual_seed(SEED)
    model = Network(width, method == 'mup').to(DEVICE)
    adam = make_optimizer(model, method)
    momentum = torch.zeros_like(model.hidden.weight)
    readings, status = [], 'complete'
    for step in range(1, STEPS + 1):
        before = actual_matrices(model) if step in SNAPSHOTS else None
        adam.zero_grad(set_to_none=True)
        model.hidden.weight.grad = None
        ix = batches[step - 1].to(DEVICE)
        loss = F.cross_entropy(model(train_x[ix]), train_y[ix])
        if not torch.isfinite(loss):
            status = 'nonfinite_training'
            break
        loss.backward()
        if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
            status = 'nonfinite_gradient'
            break
        if method == 'muon':
            muon_step(model, momentum, RATE)
        adam.step()
        if not parameters_finite(model):
            status = 'nonfinite_parameters'
            break
        if before is not None:
            after = actual_matrices(model)
            layers = {}
            for name in ('input', 'hidden', 'output'):
                w, dw = after[name], after[name] - before[name]
                fan_out, fan_in = w.shape
                reference = math.sqrt(fan_out / fan_in)
                wspec, dspec = spectral_norm(w), spectral_norm(dw)
                if wspec is None or dspec is None:
                    status = 'nonfinite_spectral_estimate'
                    break
                layers[name] = {'shape': [fan_out, fan_in], 'weight': wspec, 'update': dspec,
                                'shape_reference': reference, 'weight_over_reference': wspec['norm'] / reference,
                                'update_over_rate_reference': dspec['norm'] / (RATE * reference)}
            if status != 'complete':
                break
            with torch.no_grad():
                logits = model(valid_x)
                valid = F.cross_entropy(logits, valid_y)
                if not torch.isfinite(logits).all() or not torch.isfinite(valid):
                    status = 'nonfinite_validation'
                    break
                readings.append({'step': step, 'train_batch_loss_before_update': float(loss),
                                 'validation_loss_after_update': float(valid), 'layers': layers})
    return {'method': method, 'width': width, 'status': status, 'readings': readings}


def transfer_run(train_x, train_y, valid_x, valid_y, width, rate, seed):
    """Barrido emparejado del híbrido, sin registrar espectros adicionales."""
    torch.manual_seed(seed)
    model = Network(width, False).to(DEVICE)
    adam = make_optimizer(model, 'muon', rate)
    momentum = torch.zeros_like(model.hidden.weight)
    batches = torch.randint(len(train_x), (STEPS, BATCH), generator=torch.Generator().manual_seed(seed + 7000))
    history, status = [], 'complete'
    for step in range(STEPS + 1):
        if step == 0 or step in SNAPSHOTS:
            with torch.no_grad():
                logits = model(valid_x)
                validation_loss = F.cross_entropy(logits, valid_y)
                if not torch.isfinite(logits).all() or not torch.isfinite(validation_loss):
                    status = 'nonfinite_validation'
                    break
                history.append({'step': step, 'validation_loss': float(validation_loss)})
        if step == STEPS:
            break
        adam.zero_grad(set_to_none=True)
        model.hidden.weight.grad = None
        ix = batches[step].to(DEVICE)
        loss = F.cross_entropy(model(train_x[ix]), train_y[ix])
        if not torch.isfinite(loss):
            status = 'nonfinite_training'
            break
        loss.backward()
        if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
            status = 'nonfinite_gradient'
            break
        muon_step(model, momentum, rate)
        adam.step()
        if not parameters_finite(model):
            status = 'nonfinite_parameters'
            break
    return {'width': width, 'rate': rate, 'seed': seed, 'status': status, 'history': history}


def summarize_transfer(records):
    means = {}
    for width in WIDTHS:
        means[str(width)] = {}
        for rate in TRANSFER_RATES:
            group = [r for r in records if r['width'] == width and r['rate'] == rate]
            vals = [r['history'][-1]['validation_loss'] for r in group
                    if r['status'] == 'complete' and r['history'][-1]['step'] == STEPS]
            means[str(width)][str(rate)] = statistics.mean(vals) if len(vals) == len(TRANSFER_SEEDS) else None
    proxy = means[str(WIDTHS[0])]
    candidates = [(v, rate) for rate in TRANSFER_RATES if (v := proxy[str(rate)]) is not None]
    selected = min(candidates)[1] if candidates else None
    targets = []
    for width in WIDTHS:
        losses = means[str(width)]
        candidates = [(v, rate) for rate in TRANSFER_RATES if (v := losses[str(rate)]) is not None]
        best = min(candidates) if candidates else None
        targets.append({'width': width, 'selected_rate': selected,
                        'transferred_loss': None if selected is None else losses[str(selected)],
                        'best_rate': None if best is None else best[1],
                        'best_loss': None if best is None else best[0]})
    return {'means': means, 'selected_on_proxy': selected, 'targets': targets}


def plot_transfer(records):
    import matplotlib.pyplot as plt
    summary = summarize_transfer(records)
    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)
    for width in WIDTHS:
        ys = [summary['means'][str(width)][str(rate)] for rate in TRANSFER_RATES]
        ax.plot(TRANSFER_RATES, [float('nan') if v is None else v for v in ys], marker='o', label=f'anchura {width}')
    ax.set(xscale='log', xlabel='Tasa nominal del híbrido', ylabel='CE media de validación',
           title='Muon oculto y AdamW en el resto')
    ax.grid(alpha=0.25)
    ax.legend()
    target = OUTPUT.with_name(OUTPUT.stem + '-transfer.png')
    fig.savefig(target, dpi=150)
    plt.close(fig)
    print('Gráfico de transferencia:', target, flush=True)


def plot_updates(records):
    import matplotlib.pyplot as plt
    fig, axes = plt.subplots(1, 3, figsize=(14, 4), constrained_layout=True)
    width = max(WIDTHS)
    for ax, layer in zip(axes, ('input', 'hidden', 'output')):
        for rec in records:
            if rec['width'] != width:
                continue
            steps = [r['step'] for r in rec['readings']]
            ratios = [r['layers'][layer]['update_over_rate_reference'] for r in rec['readings']]
            ax.plot(steps, ratios, marker='o', label=rec['method'])
        ax.axhline(1., color='gray', linestyle=':', linewidth=1)
        ax.set(title=layer, xlabel='Paso', yscale='log', ylabel='Norma de cambio / (tasa × escala por forma)')
        ax.grid(alpha=0.25)
        ax.legend()
    fig.suptitle(f'Anchura {width}: referencia comparativa, no una igualdad teórica')
    target = OUTPUT.with_suffix('.png')
    fig.savefig(target, dpi=150)
    plt.close(fig)
    print('Gráfico:', target, flush=True)


def main():
    FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
    data = FashionMNIST(Path.home() / '.cache' / 'atlas-data', train=True, download=True)
    order = torch.randperm(len(data), generator=torch.Generator().manual_seed(22000))
    train_ids, valid_ids = order[:TRAIN_N], order[TRAIN_N:TRAIN_N + VALID_N]
    assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
    x = data.data[train_ids].reshape(TRAIN_N, -1).float() / 255
    xv = data.data[valid_ids].reshape(VALID_N, -1).float() / 255
    mean, std = x.mean(), x.std(unbiased=False)
    x, xv = ((x - mean) / (std + 1e-6)).to(DEVICE), ((xv - mean) / (std + 1e-6)).to(DEVICE)
    y, yv = data.targets[train_ids].to(DEVICE), data.targets[valid_ids].to(DEVICE)
    batches = torch.randint(TRAIN_N, (STEPS, BATCH), generator=torch.Generator().manual_seed(SEED + 7000))
    records = []
    for method in ('sgd', 'adamw', 'mup', 'muon'):
        for width in WIDTHS:
            record = run(x, y, xv, yv, width, method, batches)
            records.append(record)
            print(method, width, record['status'], 'lecturas:', len(record['readings']), flush=True)
    transfer_records = []
    for width in WIDTHS:
        for rate in TRANSFER_RATES:
            for seed in TRANSFER_SEEDS:
                record = transfer_run(x, y, xv, yv, width, rate, seed)
                transfer_records.append(record)
                last = record['history'][-1] if record['history'] else None
                print('transferencia Muon', width, rate, seed, record['status'],
                      None if last is None else round(last['validation_loss'], 5), flush=True)
    transfer_summary = summarize_transfer(transfer_records)
    result = {'protocol': {'dataset': 'Fashion-MNIST train', 'official_test_used': False, 'short': SHORT,
              'train_size': TRAIN_N, 'validation_size': VALID_N, 'partition_seed': 22000,
              'seed': SEED, 'base_width': BASE, 'widths': WIDTHS, 'steps': STEPS, 'batch_size': BATCH,
              'snapshots': SNAPSHOTS, 'nominal_rate': RATE, 'weight_decay': 0.,
              'sgd_momentum': 0.9,
              'muon_scope': 'hidden.weight; AdamW para el resto', 'muon_momentum': 0.95,
              'muon_iterations': 5, 'norm_method': 'potencia sobre WᵀW', 'power_steps': POWER_STEPS,
              'output_matrix': 'peso efectivo: multiplicador de readout aplicado',
              'reference': 'sqrt(fan_out/fan_in), escala comparativa, no igualdad',
              'device': str(DEVICE), 'torch_version': torch.__version__}, 'records': records,
              'transfer': {'method': 'muon', 'rates': TRANSFER_RATES, 'seeds': TRANSFER_SEEDS,
                           'records': transfer_records, 'summary': transfer_summary}}
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT.write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False), encoding='utf-8')
    plot_updates(records)
    plot_transfer(transfer_records)
    print('Resumen de transferencia:', json.dumps(transfer_summary['targets'], ensure_ascii=False), flush=True)
    print('JSON:', OUTPUT, flush=True)
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofTwo bounds and a direction
Prove: Prove the scale of the change for a rank-one update and construct a counterexample without alignment.
0
Let ΔW=uvᵀ have size m×n, n≥2 and x be nonzero. For positive constants independent of dimensions, a√n≤‖x‖≤A√n and c√(m/n)≤‖ΔW‖₂≤C√(m/n). Also assume |vᵀx|≥ρ‖v‖‖x‖ with ρ>0.

Step 1 of 3. What upper bound follows for the layer response?

NumericChanging width with Adam
In the table's convention, a hidden matrix uses η=0.01 at base width 256. What rate does it use at width 2048, with the same base rate?
NumericInput shape
For the 784→2048 layer, calculate √(fan_out/fan_in).
NumericOutput shape
For the 2048→10 layer, calculate √(fan_out/fan_in).
NumericHidden layer shape
For the 2048→2048 layer, calculate √(fan_out/fan_in).
NumericHe and spectral norm
Use the approximation σ(√fan_in+√fan_out), with σ=√(2/fan_in), for a 2048×2048 Gaussian He matrix. What value do you get?
NumericHe for the first matrix
Apply σ(√fan_in+√fan_out), with σ=√(2/fan_in), to a He matrix for the 784→2048 layer.
NumericHe for the last matrix
Apply the same He approximation to a matrix for the 2048→10 layer.
QuizWhat can one shape establish?
In the approximations you calculated, which layer has the highest ratio of Gaussian He edge to reference √(fan_out/fan_in)?
CodeBuild Adam groups
Implement mup_param_groups(model, base_width, width, lr). The model exposes named_parameters() with exactly input.weight, input.bias, hidden.weight, hidden.bias, output.weight and output.bias. The matrices have shapes (width,d), (width,width), (k,width) and their biases have lengths width, width and k; d and k are positive. Return (groups, output_multiplier): a list of groups with one parameter each and its lr, and the multiplier base_width/width. The hidden.weight rate is lr·base_width/width and all others are lr. Reject invalid dimensions or rates, unexpected names and shared parameters with ValueError. Parameters may be objects with a shape attribute; do not depend on PyTorch to build the groups.
def mup_param_groups(model, base_width, width, lr):
  pass
Shift+Enter to run
QuizA responsible transfer claim
A rate selected on a narrow model works on a wide one on a single split. What conclusion is best supported?
QuizWhat transfers and across what
According to tables 1 and 2 of Tensor Programs V, select the statements compatible with μTransfer.

More than one answer may be correct.

QuizAn iteration is not an identity
A lab uses five Muon steps for the hidden matrix and AdamW for the output. What follows?

After solving the exercises, use this cell to check the three shapes and their ratios. The Gaussian edge is an approximation, not a measured random draw.

[ ]Check the three shapesBrowser
import math

print('Tasa oculta:',0.01*256/2048)
for fan_in,fan_out in ((784,2048),(2048,2048),(2048,10)):
    reference=math.sqrt(fan_out/fan_in)
    he_edge=math.sqrt(2/fan_in)*(math.sqrt(fan_in)+math.sqrt(fan_out))
    print(f'{fan_in}→{fan_out}: referencia={reference:.8f}, borde He={he_edge:.8f}, razón={he_edge/reference:.5f}')

References