Module contents
Stage 3 of 8Research 110 min

Hyperparameters across scale

Measure learning-rate transfer and its effect on scaling estimates.

After this lesson you can

  • Sweep learning rate at no fewer than four sizes using short runs.
  • Fit the dependence of optimal learning rate on size.
  • Implement μP and check that the optimum is stable across widths.
  • Estimate scaling-law bias from fixing a single learning rate.

Before you start

A frontier can be the optimizer’s frontier

Imagine four models of increasing width, all trained with the same learning rate, the one that worked best on the smallest. The two largest finish worse than the small ones. If you fit a law L∝N−αL\propto N^{-\alpha} to those four losses, you get a negative exponent: “more parameters make the model worse.” In this example that conclusion is not justified: tuning each size’s rate changes the observed trend. To interpret a capacity comparison, specify the opportunity to learn given to each point.

The figure is not an illustration: these are measurements from this lesson’s lab. A tiny causal transformer at four widths d∈{8,16,32,64}d\in\{8,16,32,64\} learns artificial sequences for 20 AdamW steps with eight rates and two seeds per configuration. Left: final loss versus rate; the dashed line joins each width’s minimum. Right: loss versus parameter count NN with each width’s best rate and with the fixed rate you choose on the slider.

InteractiveDoes the optimal rate move?
  • d = 8
  • d = 16
  • d = 32
  • d = 64
  • minima
  • best rate on the grid
  • fixed rate 0.1

Training loss on artificial sequences, averaged over laboratory seeds 1 and 2. Lines connect measured learning rates. The exponents describe slopes through these four points.

Parameterization
0.1
η* at d = 8 and 160.1 · 0.1
η* at d = 32 and 640.03 · 0.03
Slope of ln η* versus ln d−0.69
Exponent using the best rate0.22
Exponent using the fixed rate−1.81
Exponent bias−2.04
With standard parameterization, the minimum shifts toward lower rates as width grows, and fixed rate 0.1 (best for d = 8) ruins widths 32 and 64: the fitted exponent changes from 0.22 to −1.81. Switch to μP: the minimum stays at 0.1 or 0.2 and the same fixed rate barely changes the exponent.

Under standard parameterization grid minima fall at 0.1, 0.1, 0.03 and 0.03; with μP, at 0.1, 0.2, 0.2 and 0.1. At fixed rate 0.1, widths 32 and 64 have losses 0.2260.226 and 1.101.10 versus 0.00140.0014 and 0.00110.0011 at their best rate: factors of about 160 and 1000, two and three orders of magnitude growing with size, exactly what rotates a slope. Try a small rate such as 0.01 too: there the fixed rate favors larger models, which under standard parameterization learn faster at the same rate, and the exponent inflates to 1.64 instead of collapsing. Bias can go in both directions.

Keep in mind from the outset what these numbers are not. The task is trivial (loss reaches 10−410^{-4}), evaluation uses the same sequences as training, the grid is coarse and two seeds poorly measure uncertainty. They show the mechanism using real data and check the calculation chain; they are not a language law. The goal is to understand why this happens, how to correct it and how to measure bias in your own project.

What it means to optimize each point

Write L^(N,η,s)\hat L(N,\eta,s) for loss at size NN, rate η\eta and seed ss, with budget and schedule implicit. An explicit criterion chooses η^∗(N)=arg⁡min⁡η1S∑sL^(N,η,s)\hat\eta^\ast(N)=\arg\min_\eta \frac1S\sum_s\hat L(N,\eta,s) on a selection set and evaluates the decision on held-out seeds or data. Selecting and evaluating with the same measurements makes the minimum optimistic: among noisy options, arg⁡min⁡\arg\min preferentially selects the lucky one.

What you hold fixed is part of the claim. The run queue supplies identifiers and provenance; the horizon-matched schedule ensures you do not read an intermediate point of a long run as the end of a short one. Fix optimizer, effective batch, tokens, numerical precision, data and evaluation rule, and vary only rate. A training minimum at 20 steps can move if selecting by validation loss after thousands of steps: a high rate learns quickly and can end in a worse region.

A natural grid is geometric, because a factor of two means the same near 10−410^{-4} as near 10−210^{-2} (loss near the minimum depends on ln⁡η\ln\eta). Two rules prevent most errors. If the best value is at an edge, you have not located the minimum: extend the range. If it is interior, refine between neighbors to distinguish a flat region from a narrow minimum. And never silently discard nonfinite loss: a rate diverging in one of two seeds can appear excellent if you average only successes.

What the studies teach

Hyperparameter scaling laws turn this practice into a fit. DeepSeek LLM, section 3.1 swept rate and batch size at budgets from 101710^{17} to 2⋅10192\cdot10^{19} FLOPs, considered nearly optimal every configuration whose generalization error exceeded the minimum by at most 0.25 %, and fitted

ηopt=0.3118 C−0.1250,Bopt=0.2920 C0.3271,\eta_{\mathrm{opt}}=0.3118\,C^{-0.1250},\qquad B_{\mathrm{opt}}=0.2920\,C^{0.3271},

which they validated with models of 102010^{20} FLOPs. Their CC is not 6ND6ND: it is MDMD, with MM the FLOPs per token without embeddings, including attention computation but not vocabulary computation. Multiplying budget by 16 divides rate by 160.125=216^{0.125}=\sqrt2; this is algebra from the fit, not a new measurement, and an exponent against CC is not an exponent against width: converting one into the other requires specifying how NN, depth and data grow together.

The clearest example of its importance to a scaling law is Porian and colleagues, who explain the discrepancy between Kaplan’s exponent (a≈0.88a\approx0.88 for Nopt∝CaN_{\mathrm{opt}}\propto C^a) and Chinchilla’s (a=0.5a=0.5). Reproducing Kaplan’s protocol yields a=0.835a=0.835 on RefinedWeb. Counting final-layer FLOPs lowers it to 0.706, and correcting warmup duration to 0.602. Starting from that configuration (without cosine decay), also tuning rate, batch size and AdamW β2\beta_2 by size (table 4: rate 0.013 and batch 20 at 5 million parameters, 0.0047 and 160 at 108 million) leaves a=0.497a=0.497, less than 1 % from Chinchilla: a 0.1 exponent shift due solely to hyperparameter choice. They also find β2=0.95\beta_2=0.95 suboptimal for small batches of 128 or less, so their table uses β2\beta_2 of 0.99 up to 149 million parameters and 0.95 above.

Optimal rates falling with size in these studies is not an Adam theorem: it depends on how dimensions grow, parameterization, ε\eps, weight decay and schedule. There is, however, a precise mechanism illustrating a possible width dependence and motivating a correction that must then be evaluated.

A mechanism for width dependence in Adam

Take an internal linear layer, h=Wx\vb{h}=\mat{W}\vb{x} with W∈Rn×d\mat{W}\in\R^{n\times d}, and input x\vb{x} whose coordinates are order one (for example, normalization output). In standard initialization Wij∼N(0,1/d)W_{ij}\sim\mathcal N(0,1/d), independently of one another and of x\vb{x}, so, conditional on fixed input, hi=∑jWijxjh_i=\sum_jW_{ij}x_j has variance ∥x∥2/d\|\vb{x}\|^2/d, the mean of xj2x_j^2: order one if that mean stays bounded as dd grows. The dd terms have random signs and cancel; the sum grows as d\sqrt d and the factor 1/d1/\sqrt d compensates. Now look at what a step of the Adam optimizer does.

Proof

The gradient is the outer product G=gx⊤\mat{G}=\vb{g}\vb{x}\T, with entries Gij=gixjG_{ij}=g_ix_j. After the first step, starting from zero moments, the moment matrices are M1=(1−β1)G\mat{M}_1=(1-\beta_1)\mat{G} and V1=(1−β2)G⊙G\mat{V}_1=(1-\beta_2)\mat{G}\odot\mat{G}; bias correction divides them by 1−β11-\beta_1 and 1−β21-\beta_2, so M^1=G\hat{\mat{M}}_1=\mat{G} and V^1=G⊙G\hat{\mat{V}}_1=\mat{G}\odot\mat{G}. With ε=0\eps=0, the update is ΔWij=−η Gij/∣Gij∣=−ηsign⁡(gi)sign⁡(xj)\Delta W_{ij}=-\eta\,G_{ij}/|G_{ij}|=-\eta\operatorname{sign}(g_i)\operatorname{sign}(x_j). Then (ΔWx)i=−ηsign⁡(gi)∑jsign⁡(xj) xj=−ηsign⁡(gi)∑j∣xj∣(\Delta\mat{W}\vb{x})_i=-\eta\operatorname{sign}(g_i)\sum_j\operatorname{sign}(x_j)\,x_j=-\eta\operatorname{sign}(g_i)\sum_j|x_j|.

∎

The difference from initialization appears in alignment: the dd terms of this update have the same sign because ΔW\Delta\mat{W} is built from x\vb{x} itself. If ∣x∣‾\overline{|x|} remains bounded and away from zero as dd grows, the sum is order dd, without cancellation. In this particular case, a rate proportional to 1/d1/d bounds the first step’s contribution to layer output. This motivates a rule for internal matrices, but does not prove the optimal rate for full training or guarantee stability or learning at the same pace. In our sweep discrete minima yield a slope of ln⁡η^∗\ln\hat\eta^\ast versus ln⁡d\ln d of −0.69-0.69; its difference from −1-1 has no identified cause, since the grid, other tensors, later steps and task all intervene.

The theorem is exact on the first step with one example. With batches, gradients are sums of outer products gx⊤\vb{g}\vb{x}\T, but Adam normalizes their components nonlinearly and later updates are not necessarily sums of those products or similarly aligned. Tensor Programs results study width limits under specific assumptions; they do not turn this calculation into a universal law of the optimum. In the lab you will check the formula for d=64d=64, 256256 and 10241024.

Rules for other tensors depend on their role. In an embedding table with one-hot input, only one row receives that example’s gradient; under the first-step assumptions its displacement per coordinate does not sum dd inputs. The output matrix has width as input and fixed vocabulary as output: in the theorem’s case, without correction, logits move ηd ∣x∣‾\eta d\,\overline{|x|}. In attention, the limits studied by μP allow training correlations that make q⋅k\vb{q}\cdot\vb{k} grow as dhd_h; this does not imply it occurs in every run.

μP: what changes with width

Maximal update parameterization, μP, defines a family of models with coordinated initialization, multiplier and per-parameter-group rate rules so each layer continues learning at an order-one rate as width grows. Its practical consequence, and what makes it useful, is that the base rate tuned in a small model transfers to a wide one under the method’s assumptions. It does not mean dividing every rate by width. μP theory and abc parameterizations derive rules distinguishing growing dimensions from fixed ones; here we apply them.

Choose a base width d0d_0 and write m=d/d0m=d/d_0. In our example width and MLP (4d4d) grow, while vocabulary, context, head count and depth are fixed. In the reference μP package formulation, equivalent to Tensor Programs V, Adam’s rules are:

  • Internal matrices (both dimensions grow: projection matrices WQ\mat{W}_Q, WK\mat{W}_K and WV\mat{W}_V, attention output and both MLP matrices): initialization with variance 1/fan-in1/\text{fan-in} and rate η/m\eta/m. This exactly corrects the theorem’s factor dd.
  • Embeddings, normalizations and biases (only one dimension grows): unchanged rate η\eta.
  • Output: multiplier 1/m1/m in application, weights with variance constant in dd and rate η\eta. Start with standard deviation 1/d1/\sqrt d and multiply initial weights by m\sqrt m, so their standard deviation becomes 1/d01/\sqrt{d_0}. On the idealized first step with ε=0\eps=0, Adam is invariant to positive gradient rescaling and multiplier 1/m1/m acts on logit changes like rate η/m\eta/m; you will prove this in the exercises.
  • Attention: scale dh0/dh\sqrt{d_{h0}}/d_h instead of 1/dh1/\sqrt{d_h}, consistent with linear growth of q⋅k\vb{q}\cdot\vb{k}. At base width both coincide.

At d=d0d=d_0 all rules reduce to the example’s standard parameterization, so the d=8d=8 curves are identical in both figure versions. Changing only initialization, multiplier or rates leaves a different parameterization, and such a mixture can work worse than either; in the lab you will see what a coordinate check detects when a piece is missing. μP tables sometimes distribute factors differently among weights, multipliers and rates: they are equivalent to one another, but mixing components from different formulations breaks equivalence.

Two implementation details can cost hours if forgotten. If your GPT ties input and output weights, the shared tensor has two roles with different rules; the reference package offers a specific output for that case, and in a custom implementation you must document the rule applied and check its update. If you use a rate schedule, multiply each group by the same relative factor; overwriting all rates with an absolute value erases precisely the group difference. Here we use AdamW without weight decay and with other PyTorch defaults; we do not check when ε\eps dominates or the effect of gradient clipping.

Tensor Programs V shows practical scope: tuning hyperparameters on a 40-million-parameter proxy and transferring them beats published GPT-3 6700-million figures with tuning cost 7 % of pretraining; from a 13-million proxy, it beats BERT-large (350 million) with tuning cost equivalent to one pretraining run. In the particular comparison with their GPT-3 reproduction, the authors also changed attention and numerical precision (FP32 versus FP16), so the observed difference does not isolate hyperparameter transfer.

The coordinate check

The coordinate check diagnoses μP. For several widths, measure typical per-coordinate magnitude of each activation, for example mean ∣hj∣|h_j|, and its change after a few training steps on the same input. In layers and regimes where the prediction applies, seek scales stabilizing with width; quantities such as initial logits are expected to behave differently. Do not use total norms: with order-one coordinates, Euclidean norm grows as d\sqrt d even when all is well.

Measure what can fail. Normalization output has scale one by construction and is less informative about the previous scale; also examine outputs of trained matrices (attention, MLP), logits and, in a complete study, attention logits separately. Measure change Δh=ht−h0\Delta h=h_t-h_0, not just hth_t: under the initialization assumptions described, initial μP logits decrease as 1/m1/\sqrt m, and the official procedure notes this decline. Asymptotic order-one predictions for training changes depend on model assumptions.

A flat check proves neither correctness nor transfer; a rising or falling slope flags something to investigate but does not itself prove an error. With few widths, seeds and steps, transients, the measured quantity or unmet assumptions may matter, and two networks with similar activations can have different gradients. It is therefore a diagnostic complementary to loss-versus-rate curves, not a replacement.

Local lab: transformer and parameter groups

The repository does not include a finished GPT we can import here, so we build a minimal one reproducing the relevant pieces: two causal attention heads, a pre-normalized residual block, fourfold MLP and output untied from embeddings. The first cell implements both parameterizations from scratch. Matrix weights are explicitly initialized so as not to depend on the nn.Linear default initialization. Output is rescaled only once at creation: reloading a checkpoint must not apply the factor again.

[ ]Minimal transformer and parameterizationsLocal GPU
import math
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import json

torch.set_num_threads(1)
BASE = 8
VOCAB = 16
T = 8

class TinyTransformer(nn.Module):
    def __init__(self, width, mup=False):
        super().__init__()
        assert width % 2 == 0
        self.width, self.mup = width, mup
        self.token = nn.Embedding(VOCAB, width)
        self.pos = nn.Embedding(T, width)
        self.ln1, self.ln2, self.lnf = nn.LayerNorm(width), nn.LayerNorm(width), nn.LayerNorm(width)
        self.qkv = nn.Linear(width, 3*width, bias=False)
        self.attn_out = nn.Linear(width, width, bias=False)
        self.up = nn.Linear(width, 4*width, bias=False)
        self.down = nn.Linear(4*width, width, bias=False)
        self.readout = nn.Linear(width, VOCAB, bias=False)
        for layer in (self.qkv, self.attn_out, self.up, self.down, self.readout):
            nn.init.normal_(layer.weight, std=1 / math.sqrt(layer.in_features))
        if mup:
            with torch.no_grad():
                self.readout.weight.mul_(math.sqrt(width / BASE))

    def forward(self, ids):
        b, t = ids.shape
        d = self.width
        h = self.token(ids) + self.pos(torch.arange(t, device=ids.device))
        q, k, v = self.qkv(self.ln1(h)).chunk(3, dim=-1)
        def split(x):
            return x.view(b, t, 2, d//2).transpose(1, 2)
        q, k, v = map(split, (q, k, v))
        scale = math.sqrt(BASE / 2) / (d / 2) if self.mup else 1/math.sqrt(d/2)
        scores = (q @ k.transpose(-1, -2)) * scale
        mask = torch.ones(t, t, dtype=torch.bool, device=ids.device).triu(1)
        weights = scores.masked_fill(mask, float('-inf')).softmax(-1)
        out = (weights @ v).transpose(1, 2).contiguous().view(b, t, d)
        h = h + self.attn_out(out)
        h = h + self.down(F.gelu(self.up(self.ln2(h))))
        logits = self.readout(self.lnf(h))
        return logits / (d/BASE) if self.mup else logits

def optimizer(model, lr):
    hidden = [model.qkv.weight, model.attn_out.weight, model.up.weight, model.down.weight]
    ids = {id(p) for p in hidden}
    other = [p for p in model.parameters() if id(p) not in ids]
    return torch.optim.AdamW([
        {'params': hidden, 'lr': lr / (model.width/BASE) if model.mup else lr},
        {'params': other, 'lr': lr},
    ], weight_decay=0)

def run(width, mup, lr, seed, steps=20):
    torch.manual_seed(seed)
    model = TinyTransformer(width, mup)
    opt = optimizer(model, lr)
    x = (torch.arange(T).repeat(4,1) + torch.arange(4)[:,None]*3) % VOCAB
    y = (x + 1) % VOCAB
    for step in range(steps):
        opt.zero_grad()
        loss = F.cross_entropy(model(x).reshape(-1,VOCAB), y.reshape(-1))
        if not torch.isfinite(loss):
            return None
        loss.backward()
        opt.step()
    with torch.no_grad():
        return float(F.cross_entropy(model(x).reshape(-1,VOCAB), y.reshape(-1)))

# El teorema del primer paso, comprobado con el Adam de PyTorch.
torch.manual_seed(0)
for d in (64, 256, 1024):
    layer = nn.Linear(d, d, bias=False)
    nn.init.normal_(layer.weight, std=1/math.sqrt(d))
    x_test, g_test = torch.randn(d), torch.randn(d)
    h0 = layer(x_test).detach()
    opt = torch.optim.Adam(layer.parameters(), lr=1e-3, eps=0)
    (layer(x_test) * g_test).sum().backward()   # así dL/dh = g_test
    opt.step()
    change = (layer(x_test).detach() - h0).abs()
    print(f"d={d:5d}  |Δh| medio {change.mean():.6f}  predicción η·Σ|x_j| {1e-3*x_test.abs().sum():.6f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The task is a family of deterministic sequences whose target is the next integer modulo the vocabulary. It is deliberately simple: it checks the procedure, not generalization. In μP only the four internal matrices receive η/m\eta/m; in standard parameterization all groups share the rate. Cell output confirms the theorem to printed precision: the measured change matches η∑j∣xj∣\eta\sum_j|x_j|. Quadrupling width generates different Gaussian inputs, so the ratio of sums is approximately four, not exactly four.

Now the coordinate check. With PyTorch hooks we capture attention and MLP output and logits, train three steps at the same base rate and measure mean change per coordinate, averaged over three seeds. We compare three variants: standard, complete μP and “half μP,” which has μP initialization, output multiplier and attention scale but forgets to divide internal matrix rates.

[ ]Coordinate checkLocal GPU
x_demo = (torch.arange(T).repeat(4, 1) + torch.arange(4)[:, None]*3) % VOCAB
y_demo = (x_demo + 1) % VOCAB

def capture(model, inputs, names=("attn_out", "down")):
    values, hooks = {}, []
    for name in names:
        def record(_module, _args, output, key=name):
            values[key] = output.detach().clone()
        hooks.append(getattr(model, name).register_forward_hook(record))
    try:
        with torch.no_grad():
            values["logits"] = model(inputs).detach().clone()
    finally:
        for hook in hooks:
            hook.remove()
    return values

def coordinate_check(width, variant, lr=0.01, steps=3, seeds=(1, 2, 3)):
    rows = []
    for seed in seeds:
        torch.manual_seed(seed)
        net = TinyTransformer(width, mup=(variant != "estándar"))
        if variant == "μP a medias":
            opt = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=0)
        else:
            opt = optimizer(net, lr)
        before = capture(net, x_demo)
        for _ in range(steps):
            opt.zero_grad()
            F.cross_entropy(net(x_demo).reshape(-1, VOCAB), y_demo.reshape(-1)).backward()
            opt.step()
        after = capture(net, x_demo)
        rows.append({k: float((after[k] - before[k]).abs().mean()) for k in before})
    return {k: float(np.mean([r[k] for r in rows])) for k in rows[0]}

check_widths = [8, 16, 32, 64, 128, 256]
for variant in ("estándar", "μP", "μP a medias"):
    table = {w: coordinate_check(w, variant) for w in check_widths}
    print(variant)
    for key in ("attn_out", "down", "logits"):
        series = [table[w][key] for w in check_widths]
        slope = np.polyfit(np.log(check_widths), np.log(series), 1)[0]
        print(f"  Δ{key:8s}", " ".join(f"{v:6.3f}" for v in series), f"  pendiente {slope:+.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read slopes of ln⁡∣Δh∣\ln|\Delta h| against ln⁡d\ln d. In this standard measurement, attention-output change rises from 0.17 to 1.74 between d=8d=8 and d=256d=256 (slope +0.66+0.66), and logit change from 0.28 to 2.71: at the same rate measured changes are about ten times larger at the largest width. With μP attention change is similar from d=16d=16 onward (0.13 to 0.12). Logits fall from 0.28 to 0.13; this measurement mixes output and input changes and does not itself identify the cause. In the half variant attention and MLP change again grows with dd (slopes +0.55+0.55 and +0.77+0.77), although logits grow much less (+0.14+0.14). Looking at multiple layers guides investigation, but a finite table does not uniquely identify a slope’s origin or prove the other rules correct.

Run and record the sweep

The next cell records the sweep in SQLite: each row is a canonical configuration with parameterization, width, rate, seed and procedure version, and its key is the configuration hash. A single worker claims pending jobs; on restart it returns interrupted ones to the queue and retains completed ones. That recovery assumes no other worker is alive: with concurrency you need leases and atomic claims, as in the previous lesson.

The cost is 2⋅4⋅8⋅2=1282\cdot4\cdot8\cdot2=128 training runs of 20 steps, with no weight reuse between rates. In a real sweep add checkpoint state, attempts, durations, exceptions and data version.

[ ]Sweep queue and resultsLocal GPU
import hashlib
import sqlite3
from pathlib import Path

outdir = Path("labs/runs/p14-l03")
outdir.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(outdir / "lr-sweep.sqlite3")
db.execute("CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, config TEXT NOT NULL, state TEXT NOT NULL, loss REAL, error TEXT)")
widths = [8, 16, 32, 64]
rates = [0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.2, 0.3]
jobs = [dict(version="tiny-transformer-v1", width=w, mup=m, lr=lr, seed=s, steps=20)
        for m in (False, True) for w in widths for lr in rates for s in (1, 2)]
def job_key(job):
    payload = json.dumps(job, sort_keys=True, separators=(",", ":"), allow_nan=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest(), payload

with db:
    db.execute("UPDATE runs SET state='pending' WHERE state='running'")
    for job in jobs:
        key, payload = job_key(job)
        db.execute("INSERT OR IGNORE INTO runs VALUES (?, ?, 'pending', NULL, NULL)", (key, payload))

for job in jobs:
    key, payload = job_key(job)
    with db:
        claimed = db.execute("UPDATE runs SET state='running' WHERE id=? AND state='pending'", (key,)).rowcount
    if not claimed:
        continue
    try:
        value = run(job["width"], job["mup"], job["lr"], job["seed"], job["steps"])
        if value is None or not math.isfinite(value):
            raise ValueError("pérdida no finita")
        with db:
            db.execute("UPDATE runs SET state='done', loss=? WHERE id=?", (value, key))
    except Exception as exc:
        with db:
            db.execute("UPDATE runs SET state='failed', error=? WHERE id=?", (str(exc), key))
rows = [(json.loads(config), state, loss, error)
        for config, state, loss, error in db.execute("SELECT config, state, loss, error FROM runs")]
current = [(j, state, loss, error) for j, state, loss, error in rows if j.get("version") == "tiny-transformer-v1"]
print("Trabajos por estado:", db.execute("SELECT state, COUNT(*) FROM runs GROUP BY state").fetchall())
assert len(current) == len(jobs) and all(state == "done" for _, state, _, _ in current)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The version field must change when code or data change; the schema does not verify that identity itself. Retrying after failure retrains from the seed and does not resume weights. A failed job never becomes zero loss or disappears: it stays in the table with its error.

How much a poor rate changes the law

Now the central question: if you fix one rate for all sizes, how wrong is the exponent? Suppose well-optimized loss satisfies L∗(N)=AN−αL_\ast(N)=AN^{-\alpha} with A>0A>0 at the studied points, and define the fixed-rate log penalty, r(N)=ln⁡[Lfija(N)/L∗(N)]r(N)=\ln[L_{\mathrm{fija}}(N)/L_\ast(N)].

Proof

By definition, yi=ln⁡L∗(Ni)+ri=ln⁡A−αxi+riy_i=\ln L_\ast(N_i)+r_i=\ln A-\alpha x_i+r_i. The slope with intercept is ∑i(xi−xˉ)(yi−yˉ)/∑i(xi−xˉ)2\sum_i(x_i-\bar x)(y_i-\bar y)/\sum_i(x_i-\bar x)^2, and the denominator is positive because there are two distinct xix_i. Since yi−yˉ=−α(xi−xˉ)+(ri−rˉ)y_i-\bar y=-\alpha(x_i-\bar x)+(r_i-\bar r), the slope equals −α-\alpha plus the covariance ratio of xx and rr; changing sign gives the formula. If the reference law is not exact, the same argument holds replacing α\alpha with the exponent fitted to reference losses at those same points, and then the identity is exact without any model assumption.

∎

Three consequences. A uniform multiplicative penalty (constant rir_i) moves only the intercept. A penalty growing with size reduces α^\hat\alpha and can change its sign; one that decreases inflates it. And a constant additive penalty is not multiplicative: ln⁡(1+c/L∗)\ln(1+c/L_\ast) grows as L∗L_\ast falls, so it also biases. With an irreducible floor, L=E+AN−αL=E+AN^{-\alpha}, fitting a line to ln⁡L\ln L without estimating EE no longer recovers α\alpha; here we fit logarithms of positive losses as a descriptive diagnostic.

The next cell aggregates seeds, locates minima, fits the slope of optimal rate against width and applies the theorem at fixed rate 0.1, best for the small model. The axis is actual parameter count, N=12d2+46dN=12d^2+46d in this architecture.

[ ]Grid analysisLocal GPU
import matplotlib.pyplot as plt

aggregate = {}
for mode in (False, True):
    for width in widths:
        for lr in rates:
            vals = [loss for j, state, loss, _ in current
                    if j["mup"] == mode and j["width"] == width and j["lr"] == lr]
            assert len(vals) == 2
            aggregate[(mode, width, lr)] = float(np.mean(vals))

fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
for ax, mode in zip(axes, (False, True)):
    for width in widths:
        ax.plot(rates, [aggregate[(mode, width, lr)] for lr in rates], marker="o", label=f"d={width}")
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set(xlabel="Tasa base", ylabel="Pérdida de entrenamiento", title="μP" if mode else "Estándar")
    ax.legend()
fig.tight_layout()
fig.savefig(outdir / "lr-curves.png")
plt.close(fig)

for mode in (False, True):
    name = "μP" if mode else "Estándar"
    minima = [min(rates, key=lambda lr: aggregate[(mode, width, lr)]) for width in widths]
    slope = np.polyfit(np.log(widths), np.log(minima), 1)[0]
    params = np.array([sum(p.numel() for p in TinyTransformer(width, mode).parameters()) for width in widths])
    selected = np.array([aggregate[(mode, width, lr)] for width, lr in zip(widths, minima)])
    fixed = np.array([aggregate[(mode, width, 0.1)] for width in widths])
    alpha_selected = -np.polyfit(np.log(params), np.log(selected), 1)[0]
    alpha_fixed = -np.polyfit(np.log(params), np.log(fixed), 1)[0]
    r = np.log(fixed / selected)
    x = np.log(params)
    predicted = alpha_selected - np.sum((x - x.mean()) * (r - r.mean())) / np.sum((x - x.mean())**2)
    print(f"{name}: mínimos {minima}, pendiente de ln η* frente a ln d {slope:+.2f}")
    print(f"  penalizaciones r_i {np.round(r, 2).tolist()}")
    print(f"  exponente con mejor tasa {alpha_selected:.3f}, con tasa fija {alpha_fixed:.3f}, teorema {predicted:.3f}")

payload = [{"config": j, "state": state, "loss": loss, "error": error}
           for j, state, loss, error in current]
(outdir / "lr-results.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
db.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Under standard parameterization fixed-rate penalties are r=(0, 0, 5.05, 6.94)r=(0,\,0,\,5.05,\,6.94): zero where 0.1 is best and enormous at the two widest widths. The exponent changes from 0.22 at the best rate to −1.81-1.81 at the fixed rate, and the theorem reproduces the exact value. With μP, penalties are small (0, 0.59, 0.42, 00,\,0.59,\,0.42,\,0) and have no trend: the exponent barely changes, from 1.06 to 1.08. This is μP’s usefulness for a scaling law: if rate transfers, one rate does not bias the comparison.

These exponents describe memorization losses falling to 10−410^{-4}, where logarithms amplify tiny absolute differences; do not compare them with Chinchilla. Moreover, they are selected and evaluated on the same measurements. For research results use separate selection and evaluation seeds and propagate selection uncertainty into the fit.

A direct test of isoFLOP allocation

The theorem concerns the slope of LL against NN at a common horizon. Chinchilla’s question differs: does optimal size Nopt(C)N_{\mathrm{opt}}(C) change if rate is fixed? Answering requires multiple budgets and, within each, multiple sizes with tokens matched to budget. The following test uses three budgets, five widths and three rates under standard parameterization, and compares fixed rate 0.1 with the best grid rate in each profile. Width 4 was added after a pilot whose minima fell on the lower edge: this is an exploratory extension, not a preregistered confirmation.

We count NN as all parameters and use the previous lesson’s proxy C=6NDC=6ND: for nominal budget CC we train with D=⌊C/(6N)⌋D=\lfloor C/(6N)\rfloor tokens, so compute under the proxy falls below CC by less than 6N6N FLOPs. Horizon follows from budget: width 64 at 10710^7 FLOPs receives 31 tokens, two steps (one of three 8-token sequences and another of 7 tokens), while width 4 at 4⋅1074\cdot10^7 receives 17,730 tokens, 555 steps. With such different horizons, one rate does not mean the same at both ends of the profile. To locate the minimum we interpolate a parabola in ln⁡N\ln N using the best discrete point and its two neighbors, in two ways: on loss and on ln⁡L\ln L.

[ ]Exploratory isoFLOP profilesLocal GPU
def budget_run(width, lr, seed, budget):
    torch.manual_seed(seed)
    model = TinyTransformer(width, False)
    opt = optimizer(model, lr)
    n = sum(p.numel() for p in model.parameters())
    total_tokens = int(budget // (6*n))
    remaining = total_tokens
    while remaining:
        t = min(T, remaining)
        batch = min(4, remaining // t)
        x = (torch.arange(t).repeat(batch, 1) + torch.arange(batch)[:, None]*3) % VOCAB
        y = (x + 1) % VOCAB
        opt.zero_grad()
        loss = F.cross_entropy(model(x).reshape(-1, VOCAB), y.reshape(-1))
        if not torch.isfinite(loss):
            raise ValueError("pérdida no finita")
        loss.backward()
        opt.step()
        remaining -= batch*t
    x = (torch.arange(T).repeat(4, 1) + torch.arange(4)[:, None]*3) % VOCAB
    y = (x + 1) % VOCAB
    with torch.no_grad():
        final = float(F.cross_entropy(model(x).reshape(-1, VOCAB), y.reshape(-1)))
    if not math.isfinite(final):
        raise ValueError("evaluación no finita")
    return {"params": n, "tokens": total_tokens, "actual_flops": 6*n*total_tokens, "loss": final}

budgets = [1e7, 2e7, 4e7]
iso_widths = [4, 8, 16, 32, 64]
profile_rates = [0.003, 0.03, 0.1]
profiles = []
for budget in budgets:
    for width in iso_widths:
        for lr in profile_rates:
            for seed in (1, 2):
                result = budget_run(width, lr, seed, budget)
                profiles.append({"budget": budget, "width": width, "lr": lr,
                                 "seed": seed, **result})
                assert 0 <= budget - result["actual_flops"] < 6*result["params"]

def mean_loss(budget, width, lr):
    values = [r["loss"] for r in profiles
              if r["budget"] == budget and r["width"] == width and r["lr"] == lr]
    assert len(values) == 2
    return float(np.mean(values))

ns = [sum(p.numel() for p in TinyTransformer(width).parameters()) for width in iso_widths]
fixed_profiles, tuned_profiles = [], []
for budget in budgets:
    fixed = [mean_loss(budget, width, 0.1) for width in iso_widths]
    tuned = [min(mean_loss(budget, width, lr) for lr in profile_rates) for width in iso_widths]
    fixed_profiles.append(fixed)
    tuned_profiles.append(tuned)
    print(f"C={budget:.0e}  fija {' '.join(f'{v:.1e}' for v in fixed)}")
    print(f"         mejor {' '.join(f'{v:.1e}' for v in tuned)}")

def interior_optimum(params, losses, log_loss):
    k = int(np.argmin(losses))
    if k == 0 or k == len(losses) - 1:
        return None
    x = np.log(np.asarray(params[k-1:k+2], dtype=float))
    y = np.asarray(losses[k-1:k+2], dtype=float)
    a, b, _ = np.polyfit(x, np.log(y) if log_loss else y, 2)
    if a <= 0:
        return None
    vertex = -b/(2*a)
    if vertex < x[0] or vertex > x[-1]:
        return None
    return float(np.exp(vertex))

for log_loss in (False, True):
    label = "parábola en ln L" if log_loss else "parábola en L"
    fixed_optima = [interior_optimum(ns, losses, log_loss) for losses in fixed_profiles]
    tuned_optima = [interior_optimum(ns, losses, log_loss) for losses in tuned_profiles]
    print(label, "| N_opt fija:", [round(v) if v else None for v in fixed_optima],
          "| N_opt mejor:", [round(v) if v else None for v in tuned_optima])
    if all(v is not None for v in fixed_optima + tuned_optima):
        a_fixed = float(np.polyfit(np.log(budgets), np.log(fixed_optima), 1)[0])
        a_tuned = float(np.polyfit(np.log(budgets), np.log(tuned_optima), 1)[0])
        print(f"  exponente a: fija {a_fixed:.3f}, mejor {a_tuned:.3f}, diferencia {a_fixed - a_tuned:+.3f}")
    else:
        print("  No identificable: falta algún mínimo interior con interpolación válida.")

fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
for i, budget in enumerate(budgets):
    axes[0].plot(ns, fixed_profiles[i], marker="o", label=f"C={budget:.0e}")
    axes[1].plot(ns, tuned_profiles[i], marker="o", label=f"C={budget:.0e}")
for ax, title in zip(axes, ("Tasa fija 0.1", "Mejor tasa de la rejilla")):
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set(xlabel="Parámetros totales", ylabel="Pérdida de entrenamiento", title=title)
    ax.legend()
fig.tight_layout()
fig.savefig(outdir / "isoflop-lr.png")
plt.close(fig)
(outdir / "isoflop-lr.json").write_text(json.dumps(profiles, indent=2), encoding="utf-8")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The result is instructive precisely because it is unexpected. Discrete minima fall at widths 8, 8 and 16 with both procedures, and the allocation exponent barely moves: 0.759 at the fixed rate and 0.762 at the best (parabola in LL), or 0.595 and 0.631 (parabola in ln⁡L\ln L). The printed table explains why. Rate 0.1 is best on the grid for widths 4, 8 and 16, and penalty falls only on 32 and 64, to the right of each profile’s optimum. A penalty falling far from the minimum does not move the arg⁡min⁡\arg\min; it enters only through the neighbor used in interpolation, such as width 32 at the largest budget.

So the lesson has two parts. For the slope of LL against NN at a common horizon, fixed rate is devastating (−1.81-1.81 versus 0.22). For Nopt(C)N_{\mathrm{opt}}(C) bias depends on where the penalty falls relative to the optimum, and here it is small. Note the other difference: changing from a parabola in LL to one in ln⁡L\ln L moves the exponent 0.16 at fixed rate and 0.13 at the best, far more than rate does (0.003 and 0.037). With three points per profile, estimator choice dominates; register it before looking and report it. None of these numbers estimates bias in a language law: these are three artificial-task profiles, with two seeds and chosen after a pilot.

Design a transfer that can fail

For your GPT, the confirmatory experiment has five pieces, fixed before training.

  1. Controlled family. Fixed vocabulary, context, depth, data and head count; only width grows (or, if something else grows, record it). With fixed head count dhd_h grows and attention scale is 1/dh1/d_h; if instead heads grow with fixed dhd_h, dimension classification changes.
  2. Verified implementation. Base shapes, parameter groups with their effective rates, multipliers preserved by the schedule, and a flat coordinate check at no fewer than four widths.
  3. Selection and holdout. Sweep the base rate at small widths with selection seeds; hold out a larger width and fresh seeds, and also run its own sweep at that width as a reference.
  4. A success criterion that can fail. For example: the transferred rate lies within the tolerance band (fixed in advance, in the same unit as loss) of the held-out width’s own sweep. If that sweep’s best value is at the edge, the result is indeterminate, not a success.
  5. Complete accounting. Compute for all rates, seeds, failures and validations is part of strategy cost. An efficiency comparison hiding it favors the procedure with more hidden work.

For the project’s isoFLOP frontier, a rate calibrated for one horizon may not work for another because step count changes between budgets. μP aims to ease transfer across widths under its assumptions, but does not guarantee removal of all dependence or by itself solve dependence on duration and batch. A viable strategy with one GPU is to sweep rate at a few representative points of each profile, check that the chosen-rate penalty is small near the optimum (where, as you just saw, it can bias NoptN_{\mathrm{opt}}), and include that sensitivity in frontier analysis. Save the full table and derived table with the rate chosen per configuration, to regenerate the fit with another rule.

Finally, transfer across width does not imply transfer across depth, context or batch size: each axis changes shapes and dynamics, and each needs its own comparison.

Exercises

NumericA hypothetical transfer rule
In a standard-parameterized family, Adam's optimal rate is 3⋅10−33\cdot10^{-3} at width 256. If, as an explicit hypothesis, optimal rate is inversely proportional to width, what rate is predicted for width 1024?
NumericFirst-step size
An internal matrix of width d=1024d=1024 receives normalization output as input, with ∣x∣‾=0.8\overline{|x|}=0.8. No input or output-gradient coordinate is zero. It is trained without weight decay using Adam (bias correction, ε=0\eps=0), base rate η=10−3\eta=10^{-3}, in μP with base width d0=256d_0=256. How much does each output coordinate move on the first step with one example?
QuizA first-step mechanism
In the theorem on Adam's first step with one example, nonzero inputs and gradients and ε=0, what mechanism can motivate a lower rate in a wider matrix?
ProofWhy μP output uses the base rate
Prove: In μP with an output multiplier, logits are z=1mWx\vb{z}=\frac1m\mat{W}\vb{x} with W∈RV×d\mat{W}\in\R^{V\times d}, fixed VV and m=d/d0m=d/d_0. With Adam (bias correction, ε=0\eps=0) and base rate η\eta, the first step on one example moves each logit η d0 ∣x∣‾\eta\,d_0\,\overline{|x|}, independently of width.
0
Let g=∂ℓ/∂z\vb{g}=\partial\ell/\partial\vb{z} and suppose no coordinate of g\vb{g} or x\vb{x} is zero.

Step 1 of 4. What is the gradient with respect to W\mat{W}?

NumericExponent bias by hand
Four sizes N=106,107,108,109N=10^6,10^7,10^8,10^9 have reference losses following exactly L∗∝N−0.3L_\ast\propto N^{-0.3}. A fixed rate multiplies them by ere^{r} with r=(0, 0, 0.1, 0.3)r=(0,\,0,\,0.1,\,0.3). What exponent α^fija\hat\alpha_{\mathrm{fija}} does least-squares fitting of ln⁡L\ln L against ln⁡N\ln N give?
QuizHow many rates are needed?
You know optimal rate lies between 10−410^{-4} and 10−110^{-1}; throughout that range, loss strictly increases with absolute distance between ln⁡η\ln\eta and the logarithm of the minimum; seed noise is negligible. You want the best rate on a geometric grid including both endpoints to lie within a factor 2\sqrt2 of the continuous minimum. How many rates are needed at minimum in one pass?
CodeA coordinate-check report
Implement coordinate_report(activations, tol=0.25). It receives a dictionary {width: {layer: NumPy array}} (for example, Δh changes measured after a few steps). Return a tuple (stats, slopes, flagged): stats[layer][width] is the mean absolute value; slopes[layer] is the least-squares slope of ln stats against ln width; flagged is the sorted list of layers with |slope| > tol. Raise ValueError if there are fewer than two widths, widths do not have the same layers, or a layer is empty, has nonfinite values or is identically zero. Do not modify the arrays.
import numpy as np

def coordinate_report(activations, tol=0.25):
  pass
Shift+Enter to run
QuizPenalty and slope
At four sizes a line is fitted to ln⁡L\ln L against ln⁡N\ln N. A fixed rate multiplies all reference losses by exactly the same positive factor other than 1. What changes?
Key idea

A scaling law compares procedures, not just sizes: each point must receive its best rate, or one whose penalty ri=ln⁡(Lfija/L∗)r_i=\ln(L_{\mathrm{fija}}/L_\ast) does not covary with ln⁡N\ln N, because exponent bias is exactly minus the regression slope of rr against ln⁡N\ln N. In the lab, a fixed rate moved the exponent from 0.22 to −1.81-1.81. Adam’s first step in an internal matrix moves each output coordinate η d ∣x∣‾\eta\,d\,\overline{|x|}, without cancellation; μP distributes factor 1/m1/m across internal rates, output multiplier and attention scale so the base rate transfers across width. The coordinate check reveals half-implemented μP, and only a held-out width with its own sweep confirms transfer.