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 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 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 with each width’s best rate and with the fixed rate you choose on the slider.
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 and versus and 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 ), 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 for loss at size , rate and seed , with budget and schedule implicit. An explicit criterion chooses 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, 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 as near (loss near the minimum depends on ). 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 to FLOPs, considered nearly optimal every configuration whose generalization error exceeded the minimum by at most 0.25 %, and fitted
which they validated with models of FLOPs. Their is not : it is , with the FLOPs per token without embeddings, including attention computation but not vocabulary computation. Multiplying budget by 16 divides rate by ; this is algebra from the fit, not a new measurement, and an exponent against is not an exponent against width: converting one into the other requires specifying how , 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 ( for ) and Chinchilla’s (). Reproducing Kaplan’s protocol yields 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 by size (table 4: rate 0.013 and batch 20 at 5 million parameters, 0.0047 and 160 at 108 million) leaves , less than 1 % from Chinchilla: a 0.1 exponent shift due solely to hyperparameter choice. They also find suboptimal for small batches of 128 or less, so their table uses 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, , 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, with , and input whose coordinates are order one (for example, normalization output). In standard initialization , independently of one another and of , so, conditional on fixed input, has variance , the mean of : order one if that mean stays bounded as grows. The terms have random signs and cancel; the sum grows as and the factor compensates. Now look at what a step of the Adam optimizer does.
Proof
The gradient is the outer product , with entries . After the first step, starting from zero moments, the moment matrices are and ; bias correction divides them by and , so and . With , the update is . Then .
∎The difference from initialization appears in alignment: the terms of this update have the same sign because is built from itself. If remains bounded and away from zero as grows, the sum is order , without cancellation. In this particular case, a rate proportional to 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 versus of ; its difference from 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 , 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 , and .
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 inputs. The output matrix has width as input and fixed vocabulary as output: in the theorem’s case, without correction, logits move . In attention, the limits studied by μP allow training correlations that make grow as ; 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 and write . In our example width and MLP () 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 , and , attention output and both MLP matrices): initialization with variance and rate . This exactly corrects the theorem’s factor .
- Embeddings, normalizations and biases (only one dimension grows): unchanged rate .
- Output: multiplier in application, weights with variance constant in and rate . Start with standard deviation and multiply initial weights by , so their standard deviation becomes . On the idealized first step with , Adam is invariant to positive gradient rescaling and multiplier acts on logit changes like rate ; you will prove this in the exercises.
- Attention: scale instead of , consistent with linear growth of . At base width both coincide.
At all rules reduce to the example’s standard parameterization, so the 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 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 , 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 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 , not just : under the initialization assumptions described, initial μP logits decrease as , 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.
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}")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 ; in standard parameterization all groups share the rate. Cell output confirms the theorem to printed precision: the measured change matches . 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.
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}")npm run lab and open the connection link.Read slopes of against . In this standard measurement, attention-output change rises from 0.17 to 1.74 between and (slope ), 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 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 (slopes and ), although logits grow much less (). 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 training runs of 20 steps, with no weight reuse between rates. In a real sweep add checkpoint state, attempts, durations, exceptions and data version.
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)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 with at the studied points, and define the fixed-rate log penalty, .
Proof
By definition, . The slope with intercept is , and the denominator is positive because there are two distinct . Since , the slope equals plus the covariance ratio of and ; changing sign gives the formula. If the reference law is not exact, the same argument holds replacing 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 ) moves only the intercept. A penalty growing with size reduces and can change its sign; one that decreases inflates it. And a constant additive penalty is not multiplicative: grows as falls, so it also biases. With an irreducible floor, , fitting a line to without estimating no longer recovers ; 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, in this architecture.
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()npm run lab and open the connection link.Under standard parameterization fixed-rate penalties are : zero where 0.1 is best and enormous at the two widest widths. The exponent changes from 0.22 at the best rate to at the fixed rate, and the theorem reproduces the exact value. With μP, penalties are small () 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 , 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 against at a common horizon. Chinchilla’s question differs: does optimal size 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 as all parameters and use the previous lesson’s proxy : for nominal budget we train with tokens, so compute under the proxy falls below by less than FLOPs. Horizon follows from budget: width 64 at FLOPs receives 31 tokens, two steps (one of three 8-token sequences and another of 7 tokens), while width 4 at 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 using the best discrete point and its two neighbors, in two ways: on loss and on .
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")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 ), or 0.595 and 0.631 (parabola in ). 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 ; 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 against at a common horizon, fixed rate is devastating ( versus 0.22). For 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 to one in 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.
- Controlled family. Fixed vocabulary, context, depth, data and head count; only width grows (or, if something else grows, record it). With fixed head count grows and attention scale is ; if instead heads grow with fixed , dimension classification changes.
- 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.
- 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.
- 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.
- 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 ), 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
Step 1 of 4. What is the gradient with respect to ?
import numpy as np
def coordinate_report(activations, tol=0.25):
passA scaling law compares procedures, not just sizes: each point must receive its best rate, or one whose penalty does not covary with , because exponent bias is exactly minus the regression slope of against . In the lab, a fixed rate moved the exponent from 0.22 to . Adam’s first step in an internal matrix moves each output coordinate , without cancellation; μP distributes factor 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.