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
- 15He/Kaiming initializationUpdate-to-data ratioAdamW timescaleMean-field signal propagationDepth-to-width ratio
- 13Generalization in the kernel regimeLimitations of the kernel regimeNTK evolution and kernel alignment
- 02Operator normSingular value decompositionPolar decompositionNewton-Schulz orthogonalization
- 06Steepest descent under a general normSpectral steepest descent and MuonAdamAdamW (decoupled weight decay)
- 00PyTorch optimizer API
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.
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 , compare activations of the same network before and after the step, for example
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.
The second view of the figure is a linear model constructed so each step can be calculated, not an additional Fashion-MNIST measurement. With , , target and loss , take and alternating signs in , so . In standard and NTK, ; in μP, . With reference rate , the effective rates are , and , respectively. The initial gradient is for and for . The μP output rate applies to the effective weight: if and the raw weight uses rate , the factor appears once in backward and once when returning to the effective weight.
Therefore the relative RMS of is exactly in standard and NTK, and in μP. After the step, the output is in standard and 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 : a parameter’s multiplier, initialization scale and learning rate. A common representation is , with and , using exponents per tensor. Depending on the convention, powers can move between and . 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 , multiplier one and a common rate. A typical NTK parameterization places explicit factors such as 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 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 , with independent and . The initial output remains order one in probability. For a differentiable loss, a fixed-rate SGD step has the form and , where incorporates rate, error and input. Expanding,
Since , the second term grows as if 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 . The same factor appears when differentiating with respect to : a step of size in that variable is equivalent to rate on the effective weight. For a square hidden layer, that rate decreases as . 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 . Consider an MLP , with fixed input and output dimensions and :
| Tensor or layer | Weight initialization | Multiplier | Adam rate | SGD scale relative to base |
|---|---|---|---|---|
| Input | variance for ReLU | 1 | ||
| Hidden matrix | variance | 1 | 1 | |
| Raw output weights | variance | |||
| Biases of width | zero in this example | 1 | ||
| Output bias, fixed dimension | zero | 1 | 1 |
Constants and 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 . 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 ; 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, 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 . 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 at width 64 and at 256. Applying to the wide network gives mean loss , versus for the best wide point: a difference of . In μP the corresponding difference is ; at rate the two wide seeds give and , a separation of . 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 , mean losses of for standard and for μP, versus and 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 and decoupled decay , the multiplicative part of one step is . After steps, the isolated contribution of the initial weight is multiplied by ; gradient updates also affect the final weight. Changing the group rate or number of steps changes that retention even if 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 , with and . The spectral condition of Yang, Simon and Bernstein compares operator norms of effective weights and updates with the scale
within their family and asymptotic regime. A constant learning rate can appear as an update factor. indicates upper and lower bounds with constants independent of width: it does not mean the norm must be exactly at each step.
To check the scale of weights in the μP table, take fixed input dimension and output dimension , hidden width and fixed base width . With approximate Gaussian edge , the input matrix has norm of order and the hidden matrix order one. At the output, the effective weight multiplies a matrix of standard deviation by : its standard deviation is and its edge is of order . Since and remain fixed, this has the same order as . Standard He output initialization, in contrast, has an order-one edge and its ratio to grows as .
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 bound.
If , inequality gives an upper bound of order . A lower bound requires the update to align nondegenerately with : the same operator norm can act in an orthogonal direction and produce zero. In the aligned example, output norm 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.
To interpret the panel, distinguish spectral and Frobenius norms: the same Frobenius norm can be distributed across many singular values. In μP measure 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 to for standard AdamW when width changes from 64 to 256; in μP it goes from to , and with Muon from to . Constant factors, including input size and base width, can make a ratio very different from one without invalidating an scale. At the output of the Muon hybrid, which uses standard AdamW in that layer, the ratio goes from to : 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 has full rank in its smaller dimension, the exact polar factor 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 , with rows and columns. This can be checked in the update function of the Muon repository. For wide matrices it does not match ; 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 and orthogonalizes . The formulation in the spectral descent lesson accumulates and orthogonalizes : with zero initial states both inputs are proportional by . 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 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.
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))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)"""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()
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.
"""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()npm run lab and open the connection link.Exercises
Step 1 of 3. What upper bound follows for the layer response?
def mup_param_groups(model, base_width, width, lr):
passMore than one answer may be correct.
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.
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
- Yang and Hu, Feature Learning in Infinite-Width Neural Networks, 2020.
- Yang and colleagues, Tensor Programs V: Zero-Shot Hyperparameter Transfer, 2022.
- Yang, Simon and Bernstein, A Spectral Condition for Feature Learning, 2023.
- Jordan, Muon: An optimizer for hidden layers, 2024.
- Bernstein and Newhouse, Old Optimizer, New Norm, 2024.
- Everett and colleagues, Scaling Exponents Across Parameterizations and Optimizers, 2024.
- Microsoft, mup library.
- Yang and colleagues, Tensor Programs VI, 2023.
- Bordelon and colleagues, Depthwise Hyperparameter Transfer in Residual Networks, 2023.