Modernizing the architecture with ablations
Transform GPT-2 into a modern Llama-style block with RoPE, RMSNorm, SwiGLU, no biases, grouped-query attention, and QK-norm. Measure each change using a small-scale ablation protocol with fixed token and parameter budgets, per-variant learning-rate tuning, and multiple seeds.
After this lesson you can
- Implement RoPE, RMSNorm, SwiGLU, GQA, and QK-norm as configuration options.
- Design an ablation protocol with a fixed budget, a short learning-rate sweep, and 3 seeds.
- Run ablations on an approximately 30M-parameter model and measure validation loss.
- Choose the final configuration from evidence and document nonsignificant effects.
Before you start
Change one component and know what changed
The GPT in this pathway copies GPT-2 (2019) decisions: learned positions added to tokens, LayerNorm before each sublayer, a width- GELU MLP, biases in every linear layer, and a key and value head for each query head. Four years later, LLaMA (2023) describes a different block: RMSNorm instead of LayerNorm, SwiGLU instead of GELU at width , and rotary position embeddings (RoPE) instead of absolute positions. The public Llama 3 implementation adds grouped-query attention (GQA) and omits linear-layer biases.
| Component | GPT-2 | Modern block | Claimed benefit |
|---|---|---|---|
| Positions | learned table added to input | Q and K rotation (RoPE) | Q·K depends on relative displacement |
| Normalization | LayerNorm (center and scale) | RMSNorm (scale only) | fewer operations, same stabilizing effect |
| MLP | GELU, width | SwiGLU, width | better loss at equal parameter count |
| Biases | in every linear layer | none | simpler; parameter count barely changes |
| KV heads | one per query | shared by groups (GQA) | smaller KV cache in inference |
| Q and K | unnormalized | QK-norm (optional) | bounded attention logits |
The table states what each piece promises, not what it delivers in your model. Narang and colleagues (2021) reimplemented dozens of Transformer modifications in one codebase under the same budget and concluded most did not improve results appreciably; GLU variants and RMSNorm were among those that did. We will do the same at reduced scale: an ablation that can reveal improvement, no difference, or degradation and report which occurred with uncertainty.
Start with the most geometric component. In the figure, a two-coordinate query and key rotate according to positions and . Press “Add 1 to both positions” several times: both arrows on the left rotate but their product does not change. Then move only or change a coordinate of : the product changes.
The modern block in this lab is the GPT pre-norm block with five independent switches, RoPE, RMSNorm, SwiGLU, no biases, and GQA, plus a sixth, QK-norm, unused by LLaMA but used by many later models. Each switch is a configuration option, so baseline, individual variants, and complete block all come from the same class and training loop.
Positions as rotations
The first pair rotates one radian per position; the last, with , takes on the order of positions for a full turn. This is the same geometric wavelength scale as the original Transformer’s sinusoidal positions, applied as a Q and K rotation rather than added to input. RoFormer introduced the construction, studied in the Transformers module.
Proof
Each block is a planar rotation, so and because angles add. Block-diagonal matrices multiply and transpose blockwise, so the same holds for . Then . With and the difference is unchanged. Norm preservation is orthogonality: .
∎The theorem concerns the positional term with fixed and . In a model, depends on content at position and, from the second layer onward, all preceding context. One exact, testable property follows: without absolute positions, shifting the entire sequence changes no first-layer attention score. The lab checks it.
Two implementation details distinguish correct RoPE from an apparent implementation. First, pairing convention: here are consecutive coordinates, while other implementations pair with , rotating “halves”. Both are RoPE, but their weights are not interchangeable without permuting rows of and . Second, order relative to QK-norm: normalize first, then rotate, so rotation acts on normalized vectors and preserves their norms.
Normalize without centering
LayerNorm subtracts the mean and divides by standard deviation; RMSNorm only divides by root mean square. The difference appears in an extreme case: if all coordinates agree, with , LayerNorm returns zero before bias and RMSNorm returns apart from . RMSNorm retains the invariance important for stability, scale invariance ( for as ), and gives up translation invariance. Zhang and Sennrich proposed it precisely as a cheaper LayerNorm. In Narang and colleagues’ table 1, with 223 million parameters, replacing LayerNorm with RMSNorm lowered final loss from 1.838 to 1.821 and raised throughput from 3.50 to 3.68 steps per second.
We implement it from scratch with a precision detail: under autocast, Q and K normalization inputs arrive in bf16. Computing mean square in bf16 loses precision, and mixing bf16 input with float32 weight prevents PyTorch from using its fused kernel. Our version converts to float32, normalizes, and returns to input dtype, as Llama does.
A gated MLP
The branch proposes a value and the gate branch determines, coordinate by coordinate and according to input, how much passes. This multiplicative interaction between two linear projections is absent from GPT’s MLP.
The cost is the third matrix. GPT’s width- MLP has weights; SwiGLU at width has . Matching gives , LLaMA’s : with , ; with , exactly 2048. Without reducing width, the variant has 50% more MLP parameters and any improvement is confounded with size. In Shazeer (2020) table 1, with width reduced from 3072 to 2048 to match parameters and operations, validation log-perplexity moves from 1.997 (ReLU) and 1.983 (GELU) to 1.944 (SwiGLU) after 65 536 steps, with standard deviations 0.003 to 0.010 across four runs; after 524 288 steps, from 1.677 and 1.679 to 1.636.
Remove biases, share KV heads, and normalize Q and K
No biases. Removing linear and LayerNorm biases eliminates a few thousand parameters out of almost 30 million; MLP width recovers them. The change is deliberately small: it checks that the protocol does not detect differences where it should not.
GQA. With grouped-query attention, there are query heads and key and value heads, with dividing : query head uses KV head . There are still distinct queries, so costs the same. What shrinks is storage and reading during generation. For a cache of positions, batch , and layers, keys and values occupy
proportional to . For our model (, , bf16), this is bytes per token and sequence with , and half with . Ainslie and colleagues motivate GQA because autoregressive inference is limited by memory bandwidth needed to load keys and values. In their table 1, T5-XXL with 8 KV groups attains average score 47.1 versus 47.2 with all heads, with inference time 0.28 s versus 1.51 s. That result comes from a large model converted from a trained one. Our model must measure whether head sharing costs loss.
QK-norm. Our variant applies learned RMSNorm over each head’s dimension to and before rotation, retaining the usual scale. The original QKNorm uses normalization with a learned scale instead of , so ours is a variant rather than a reproduction. Its benefit can be proved.
Proof
Rotations preserve norms, so Cauchy-Schwarz bounds the numerator by . Also , and coordinatewise multiplication by multiplies the norm by at most . Thus , likewise for , and division by gives the bound.
∎Without QK-norm, logits grow with norms of and , which nothing bounds. With it they can grow only if gains grow. At and initial gains of 1, the bound is . This does not guarantee stability throughout training because gains are learned, but it moves the issue to numbers per layer that can be monitored. See QK-norm.
The experiment that would distinguish changes
Each clause closes the door on a false conclusion.
One change per variant. If a variant changes two things, its effect cannot be attributed to either. The combined variant measures cumulative improvement, which need not equal the sum of individual effects because components interact.
Same budget. Matching tokens, parameters, and compute are different constraints. We match tokens, with the same steps, batch, and context, and body parameters, layers performing matrix multiplications, excluding token and position tables. MLP width is the free variable: parameter count is an affine function of width, so evaluate it at two widths to solve for the closest target. Matching body also approximately matches compute per token: matrix multiplications cost around operations per token for forward and backward, plus an attention term proportional to unchanged by our variants, since GQA reduces , not queries. Wall time is not matched because elementwise operations, normalization, and kernel efficiency differ, so it is measured separately. One consequence matters: GQA saves parameters in and and returns them in a wider MLP, so its comparison does not isolate head count alone.
One rate per variant. Optimal rate depends on architecture. If every variant uses the baseline rate, baseline has home advantage and a variant tolerating higher rates appears worse than it is. Each variant tries the same rate grid with one selection seed, selects the best by selection-split loss, and only then trains on evaluation seeds evaluated on another split. Choosing and claiming on the same evaluation biases results toward the selected variant.
Paired differences. For a given seed, baseline and variant see the same batches in the same order and are evaluated on the same windows. Their noise is therefore similar, and partly cancels it. Formally, if seed losses have variances and and correlation ,
which with is less than the variance of comparing independent runs. This is the same principle as paired tests by example. With seeds, mean , and sample standard deviation , the two-sided 95% t interval is
It assumes independent, approximately normal differences. With , the quantile is more than twice the normal 1.96: three seeds resolve only effects large relative to their variability. An interval containing zero does not prove the effect is zero, only that these seeds cannot distinguish it.
Multiple comparisons. With seven variants against baseline, the chance that at least one interval excludes zero by chance exceeds the nominal 5%. Holm orders p-values from smallest to largest, multiplies the th by , and enforces a nondecreasing sequence. It controls the probability of any false positive in the family without assuming independence. See also multi-seed evaluation.
Lab: components, table, and sweep
The lab has four cells run in the same notebook. The first implements the configurable block from scratch and checks each component on CPU with small tensors. The second builds a table with paired differences, t intervals, and Holm correction, and tests it on synthetic numbers. The third defines the protocol and resumable sweep. The fourth launches it only when requested via an environment variable, so running the notebook top to bottom does not accidentally start hours of training.
Required data from previous lessons: the full sweep reads the corpus from long pretraining (P06_PRETRAIN_DIR/corpus, default p06_pretrain/corpus), and the short verification run uses the p06-l02 sample (P06_DATA_DIR, default p06_data). Both manifests use the same format and vocabulary of 512 tokens plus end-of-text; cells verify each shard’s SHA-256 before use.
import math
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(2)
def rotate(x, positions, base=10000.0):
"""RoPE sobre el último eje de x (lote, cabezas, posiciones, canales), en parejas consecutivas."""
width = x.shape[-1]
if width % 2:
raise ValueError('La dimensión de cabeza debe ser par')
inv = base ** (-torch.arange(0, width, 2, device=x.device, dtype=torch.float32) / width)
angle = positions.to(device=x.device, dtype=torch.float32)[:, None] * inv # (posiciones, width/2)
c, s = angle.cos().to(x.dtype), angle.sin().to(x.dtype)
even, odd = x[..., 0::2], x[..., 1::2]
return torch.stack((even*c - odd*s, even*s + odd*c), dim=-1).flatten(-2)
class RMSNorm(nn.Module):
"""RMSNorm desde cero: sin restar la media, en float32 y devuelta en el tipo de la entrada."""
def __init__(self, d, eps=1e-5):
super().__init__()
self.eps, self.weight = eps, nn.Parameter(torch.ones(d))
def forward(self, x):
x32 = x.float()
y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)
return (y * self.weight).to(x.dtype)
class Attention(nn.Module):
def __init__(self, d, heads, kv_heads, bias, rope, qknorm):
super().__init__()
if d % heads or heads % kv_heads or (d // heads) % 2:
raise ValueError('Cabezas incompatibles o dimensión de cabeza impar')
self.heads, self.kv_heads, self.width, self.rope = heads, kv_heads, d // heads, rope
self.q = nn.Linear(d, d, bias=bias)
self.k = nn.Linear(d, kv_heads*self.width, bias=bias)
self.v = nn.Linear(d, kv_heads*self.width, bias=bias)
self.out = nn.Linear(d, d, bias=bias)
self.qnorm = RMSNorm(self.width) if qknorm else nn.Identity()
self.knorm = RMSNorm(self.width) if qknorm else nn.Identity()
def forward(self, x):
b, t, d = x.shape
q = self.q(x).view(b, t, self.heads, self.width).transpose(1, 2)
k = self.k(x).view(b, t, self.kv_heads, self.width).transpose(1, 2)
v = self.v(x).view(b, t, self.kv_heads, self.width).transpose(1, 2)
q, k = self.qnorm(q), self.knorm(k) # QK-norm por cabeza, antes de rotar
if self.rope:
pos = torch.arange(t, device=x.device)
q, k = rotate(q, pos), rotate(k, pos) # V no se rota
repeat = self.heads // self.kv_heads # cada cabeza KV sirve a un grupo de consultas
k, v = k.repeat_interleave(repeat, dim=1), v.repeat_interleave(repeat, dim=1)
result = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.out(result.transpose(1, 2).contiguous().view(b, t, d))
class FeedForward(nn.Module):
def __init__(self, d, hidden, bias, swiglu):
super().__init__()
self.swiglu = swiglu
self.up = nn.Linear(d, hidden, bias=bias)
self.gate = nn.Linear(d, hidden, bias=bias) if swiglu else None
self.out = nn.Linear(hidden, d, bias=bias)
def forward(self, x):
h = F.silu(self.gate(x)) * self.up(x) if self.swiglu else F.gelu(self.up(x), approximate='tanh')
return self.out(h)
def make_norm(d, cfg):
return RMSNorm(d) if cfg['rms'] else nn.LayerNorm(d, eps=1e-5, bias=cfg['bias'])
class Block(nn.Module):
def __init__(self, d, heads, hidden, cfg):
super().__init__()
self.n1, self.n2 = make_norm(d, cfg), make_norm(d, cfg)
self.attn = Attention(d, heads, cfg['kv_heads'], cfg['bias'], cfg['rope'], cfg['qknorm'])
self.mlp = FeedForward(d, hidden, cfg['bias'], cfg['swiglu'])
def forward(self, x):
x = x + self.attn(self.n1(x))
return x + self.mlp(self.n2(x))
class StudyGPT(nn.Module):
"""GPT de estudio: cada opción de cfg activa una pieza del bloque moderno."""
def __init__(self, vocab, context, d, layers, heads, hidden, cfg):
super().__init__()
self.context, self.cfg = context, dict(cfg)
self.token = nn.Embedding(vocab, d)
self.position = None if cfg['rope'] else nn.Embedding(context, d)
self.blocks = nn.ModuleList([Block(d, heads, hidden, cfg) for _ in range(layers)])
self.norm = make_norm(d, cfg)
self.apply(self.init)
for block in self.blocks: # proyecciones que suman al residuo, escaladas como en GPT-2
nn.init.normal_(block.attn.out.weight, std=0.02/math.sqrt(2*layers))
nn.init.normal_(block.mlp.out.weight, std=0.02/math.sqrt(2*layers))
@staticmethod
def init(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, std=0.02)
if isinstance(module, nn.Linear) and module.bias is not None:
nn.init.zeros_(module.bias)
def forward(self, ids):
b, t = ids.shape
if t > self.context:
raise ValueError('Contexto demasiado largo')
x = self.token(ids)
if self.position is not None:
x = x + self.position(torch.arange(t, device=ids.device))
for block in self.blocks:
x = block(x)
return F.linear(self.norm(x), self.token.weight) # salida atada a la tabla de tokens
def configs(heads):
base = dict(rope=False, rms=False, swiglu=False, bias=True, kv_heads=heads, qknorm=False)
out = {'base': base}
for name, changes in [('rope', dict(rope=True)), ('rms', dict(rms=True)),
('swiglu', dict(swiglu=True)), ('sin_sesgos', dict(bias=False)),
('gqa', dict(kv_heads=heads//2)), ('qknorm', dict(qknorm=True)),
('moderno', dict(rope=True, rms=True, swiglu=True, bias=False,
kv_heads=heads//2, qknorm=True))]:
out[name] = dict(base, **changes)
return out
def body_params(model):
"""Parámetros sin las tablas de tokens y posiciones: los que pasan por multiplicaciones de matrices."""
skip = {id(model.token.weight)} | ({id(model.position.weight)} if model.position is not None else set())
return sum(p.numel() for p in model.parameters() if id(p) not in skip)
def count_for(vocab, context, d, layers, heads, hidden, cfg):
with torch.device('meta'):
model = StudyGPT(vocab, context, d, layers, heads, hidden, cfg)
return body_params(model), sum(p.numel() for p in model.parameters())
def matched_width(vocab, context, d, layers, heads, target, cfg):
"""Ancho de la MLP cuyo número de parámetros del cuerpo queda más cerca de target (es afín en el ancho)."""
a, b = count_for(vocab, context, d, layers, heads, 1, cfg)[0], count_for(vocab, context, d, layers, heads, 2, cfg)[0]
hidden = max(1, round(1 + (target - a) / (b - a)))
return (hidden, *count_for(vocab, context, d, layers, heads, hidden, cfg))
# ---- Pruebas con tensores pequeños: identidades y formas, no resultados de entrenamiento.
torch.manual_seed(8)
q, k = torch.randn(1, 2, 1, 8), torch.randn(1, 2, 1, 8)
def r(x, position): return rotate(x, torch.tensor([position]))
# 1. RoPE: el producto depende solo de n - m (todas las frecuencias a la vez) y conserva normas.
assert torch.allclose((r(q, 3)*r(k, 7)).sum(-1), (r(q, 13)*r(k, 17)).sum(-1), atol=1e-5)
assert torch.allclose(r(q, 3).norm(dim=-1), q.norm(dim=-1), atol=1e-6)
assert not torch.allclose((r(q, 3)*r(k, 7)).sum(-1), (r(q, 3)*r(k, 8)).sum(-1), atol=1e-3)
# 2. Con RoPE y sin posiciones absolutas, desplazar la secuencia no cambia las puntuaciones.
att = Attention(16, 2, 2, False, True, False)
x = torch.randn(1, 6, 16)
with torch.no_grad():
qq = att.q(x).view(1, 6, 2, 8).transpose(1, 2); kk = att.k(x).view(1, 6, 2, 8).transpose(1, 2)
s0 = rotate(qq, torch.arange(6)) @ rotate(kk, torch.arange(6)).transpose(-1, -2)
s5 = rotate(qq, torch.arange(6)+5) @ rotate(kk, torch.arange(6)+5).transpose(-1, -2)
assert torch.allclose(s0, s5, atol=1e-5)
# 3. RMSNorm coincide con la de PyTorch, conserva un vector constante y LayerNorm lo anula.
z = torch.randn(3, 8) * 5
assert torch.allclose(RMSNorm(8)(z), nn.RMSNorm(8, eps=1e-5)(z), atol=1e-5)
one = torch.ones(2, 8)
assert torch.allclose(nn.LayerNorm(8, elementwise_affine=False)(one), torch.zeros_like(one))
assert torch.allclose(RMSNorm(8)(one), one, atol=1e-5)
# 4. GQA: repetir las cabezas KV equivale a que cada consulta use la de su grupo.
q = torch.randn(1, 4, 5, 8); k = torch.randn(1, 2, 5, 8); v = torch.randn(1, 2, 5, 8)
expanded = F.scaled_dot_product_attention(q, k.repeat_interleave(2, 1), v.repeat_interleave(2, 1), is_causal=True)
manual = torch.cat([F.scaled_dot_product_attention(q[:, i:i+1], k[:, i//2:i//2+1], v[:, i//2:i//2+1], is_causal=True)
for i in range(4)], dim=1)
assert torch.allclose(expanded, manual, atol=1e-6)
# 5. SwiGLU coincide con su fórmula y deja pasar gradientes.
ff = FeedForward(4, 6, False, True)
sample = torch.randn(3, 4, requires_grad=True)
assert torch.allclose(ff(sample), ff.out(F.silu(ff.gate(sample))*ff.up(sample)), atol=1e-7)
ff(sample).sum().backward()
assert sample.grad is not None and torch.isfinite(sample.grad).all()
# 6. Causalidad en todas las variantes: cambiar el futuro no altera los logits del pasado.
for name, cfg in configs(4).items():
model = StudyGPT(31, 12, 32, 2, 4, 64, cfg).eval()
ids = torch.randint(0, 31, (2, 12)); altered = ids.clone(); altered[:, 6:] = (altered[:, 6:]+1) % 31
with torch.no_grad():
a, b = model(ids), model(altered)
assert a.shape == (2, 12, 31) and torch.isfinite(a).all() and torch.allclose(a[:, :6], b[:, :6], atol=1e-5)
print('RoPE, RMSNorm, GQA, SwiGLU y causalidad: controles superados')
# ---- Presupuesto de parámetros del modelo de estudio (vocabulario de p06-l02: 512 + fin de texto).
VOCAB, CONTEXT, D, LAYERS, HEADS = 513, 512, 640, 6, 8
target, total = count_for(VOCAB, CONTEXT, D, LAYERS, HEADS, 4*D, configs(HEADS)['base'])
print(f'Base: {target:,} parámetros de cuerpo, {total:,} en total')
for name, cfg in configs(HEADS).items():
hidden, body, total = matched_width(VOCAB, CONTEXT, D, LAYERS, HEADS, target, cfg)
step = count_for(VOCAB, CONTEXT, D, LAYERS, HEADS, hidden+1, cfg)[0] - body
assert abs(body - target) <= step / 2 # el redondeo deja el error en medio escalón
kv = 2 * LAYERS * cfg['kv_heads'] * (D // HEADS) * 2 # K y V, todas las capas, bf16
print(f'{name:>10} ancho MLP {hidden:5d} cuerpo {body:,} ({body-target:+,}) '
f'total {total:,} caché KV {kv:,} B por token')npm run lab and open the connection link.The budget table shows effective rounding: no variant differs from baseline by more than 4160 body parameters, less than two ten-thousandths. RoPE variants have 327 680 fewer total parameters because they lack a position table; that is why we match body rather than total. SwiGLU width 1706 is the preceding section’s , and GQA receives an MLP of 2880 instead of 2560.
import numpy as np
from scipy import stats
def paired(runs, baseline, variant, tokens=None):
"""Diferencias Δ_s = L_variante,s − L_base,s en el mismo checkpoint (el último si tokens es None)."""
def at(run):
points = {p['tokens']: p['val_loss'] for p in run['checkpoints']}
return points.get(tokens if tokens is not None else max(points))
base = {r['seed']: at(r) for r in runs if r['variant'] == baseline}
diffs = {r['seed']: at(r) - base[r['seed']] for r in runs
if r['variant'] == variant and r['seed'] in base and at(r) is not None and base[r['seed']] is not None}
return np.array([diffs[s] for s in sorted(diffs)])
def summarize(d, level=0.95):
"""Media, intervalo t bilateral y valor p de la prueba t emparejada sobre las diferencias d."""
n = len(d)
mean = float(d.mean()) if n else float('nan')
if n < 2:
return dict(n=n, mean=mean, lo=float('nan'), hi=float('nan'), p=float('nan'))
se = d.std(ddof=1) / np.sqrt(n)
half = stats.t.ppf(0.5 + level/2, n - 1) * se
p = float(2*stats.t.sf(abs(mean)/se, n - 1)) if se > 0 else (0.0 if mean else 1.0)
return dict(n=n, mean=mean, lo=mean - half, hi=mean + half, p=p)
def holm(pvalues):
"""Ajuste de Holm para controlar la tasa de error por familia al comparar varias variantes."""
order = np.argsort(pvalues); m = len(pvalues); adjusted = np.empty(m); running = 0.0
for rank, i in enumerate(order):
running = max(running, min(1.0, (m - rank) * pvalues[i]))
adjusted[i] = running
return adjusted
def ablation_table(artifact, baseline='base'):
runs = artifact['runs']
names = list(dict.fromkeys(r['variant'] for r in runs))
rows = []
for name in names:
finals = np.array([min(r['checkpoints'], key=lambda p: -p['tokens'])['val_loss']
for r in runs if r['variant'] == name])
own = [r for r in runs if r['variant'] == name]
rows.append(dict(variant=name, n=len(finals), loss=finals.mean(), sd=finals.std(ddof=1) if len(finals) > 1 else float('nan'),
lr=own[0].get('lr'), tokens_per_s=np.mean([r['config']['tokens_per_second'] for r in own]) if 'config' in own[0] else float('nan'),
memory_gib=max(r['config']['peak_allocated_bytes'] for r in own)/2**30 if 'config' in own[0] else float('nan'),
**({} if name == baseline else {'delta': summarize(paired(runs, baseline, name))})))
others = [row for row in rows if 'delta' in row]
for row, p in zip(others, holm(np.array([row['delta']['p'] for row in others]))):
row['p_holm'] = p
print(f"{'variante':>11} {'n':>2} {'pérdida':>8} {'desv.':>7} {'Δ media':>8} {'IC 95 % de Δ':>20} {'p Holm':>7} {'tasa':>7} {'tok/s':>8} {'GiB':>5}")
for row in rows:
d = row.get('delta')
ic = f"[{d['lo']:+.4f}, {d['hi']:+.4f}]" if d else ''
print(f"{row['variant']:>11} {row['n']:>2} {row['loss']:8.4f} {row['sd']:7.4f} "
f"{(format(d['mean'], '+.4f') if d else ''):>8} {ic:>20} {(format(row['p_holm'], '.3f') if d else ''):>7} "
f"{row['lr'] if row['lr'] else float('nan'):7.1e} {row['tokens_per_s']:8.0f} {row['memory_gib']:5.2f}")
return rows
# ---- Pruebas de la tabla con valores sintéticos elegidos a mano (no son mediciones).
d = np.array([-0.02, -0.01, -0.03])
s = summarize(d)
ci = stats.ttest_rel(np.zeros(3) + d, np.zeros(3)).confidence_interval(0.95)
assert np.isclose(s['lo'], ci.low) and np.isclose(s['hi'], ci.high)
assert np.isclose(s['p'], stats.ttest_rel(d, np.zeros(3)).pvalue)
assert np.allclose(holm(np.array([0.01, 0.04, 0.03])), [0.03, 0.06, 0.06])
toy = {'runs': [{'variant': v, 'seed': s, 'lr': 1e-3, 'checkpoints': [{'tokens': 10, 'val_loss': 9.0}, {'tokens': 20, 'val_loss': base + off}]}
for s, base in [(1, 3.0), (2, 3.1), (3, 2.9)] for v, off in [('base', 0.0), ('b', -0.01*s)]]}
assert np.allclose(paired(toy['runs'], 'base', 'b'), [-0.01, -0.02, -0.03])
print('Diferencias emparejadas, intervalos t y ajuste de Holm: controles superados')npm run lab and open the connection link.The next cell defines the protocol. Two configurations share code: full, the sweep you will run, and short, a 150-step version used to verify the lab end to end. Validation is split at the document end nearest halfway: the first part selects rate and the second measures results, without shared documents. For one seed, every variant receives the same batches because the generator depends only on seed, and is evaluated on the same fixed windows. Every rate schedule is identical: linear warmup and cosine decay to 10% of peak. JSON is rewritten after each run so an interruption preserves completed work and relaunching resumes. If the protocol changes, the code refuses to mix results.
import hashlib, json, math, os, time
import numpy as np
from pathlib import Path
PRESETS = {
# Barrido del lector: el modelo de unos 30M de parámetros, 41M tokens por ejecución, corpus de p06-l06.
'full': dict(context=512, batch=32, steps=2500, warmup=150, eval_every=250, eval_windows=128,
rates=[5e-4, 1e-3, 2e-3], corpus='pretrain', max_train_tokens=400_000_000),
# Ejecución corta de verificación: el mismo modelo, 150 pasos, la muestra de p06-l02.
'short': dict(context=256, batch=16, steps=150, warmup=15, eval_every=25, eval_windows=32,
rates=[1e-3, 3e-3], corpus='l02', max_train_tokens=400_000_000),
}
SELECT_SEED, EVAL_SEEDS = 11, [21, 22, 23]
def corpus_dir(kind):
if kind == 'l02':
return Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
return Path(os.environ.get('P06_PRETRAIN_DIR', 'p06_pretrain')).resolve() / 'corpus'
def sha_file(path):
digest = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(1 << 24):
digest.update(chunk)
return digest.hexdigest()
def load_corpus(folder, max_train_tokens):
"""Abre con memmap los shards de un manifiesto de p06-l02 o p06-l06 y verifica tamaño y SHA-256.
Del entrenamiento usa los primeros shards hasta max_train_tokens; la validación, entera."""
manifest = json.loads((folder/'manifest.json').read_text(encoding='utf-8'))
parts = {}
for split in ('train', 'valid'):
arrays, total = [], 0
for shard in manifest['parts'][split]['shards']:
if split == 'train' and total >= max_train_tokens:
break
path = folder/shard['file']
if path.stat().st_size != 2*shard['tokens'] or sha_file(path) != shard['sha256']:
raise ValueError(f"Shard dañado o incompleto: {shard['file']}")
arrays.append(np.memmap(path, dtype='<u2', mode='r')); total += shard['tokens']
parts[split] = arrays
return parts, manifest['eot_id'], manifest['vocab_sha256']
def split_validation(valid, eot):
"""Parte la validación por el fin de documento más cercano a la mitad:
selección y evaluación no comparten ningún documento."""
valid = np.concatenate([np.asarray(a) for a in valid])
ends = np.flatnonzero(valid == eot)
cut = int(ends[np.searchsorted(ends, len(valid)//2)]) + 1
return [valid[:cut]], [valid[cut:]]
def windows(arrays, batch, length, generator, device):
"""Ventanas de length+1 tokens con inicio uniforme entre todas las posiciones válidas de los shards."""
usable = np.array([len(a) - length - 1 for a in arrays])
offsets = np.concatenate([[0], np.cumsum(usable)])
picks = torch.randint(0, int(offsets[-1]), (batch,), generator=generator).tolist()
rows = []
for g in picks:
i = int(np.searchsorted(offsets, g, side='right')) - 1
start = g - int(offsets[i])
rows.append(np.asarray(arrays[i][start:start+length+1], dtype=np.int64))
rows = torch.from_numpy(np.stack(rows)).to(device)
return rows[:, :-1], rows[:, 1:]
def lr_at(step, peak, warmup, steps, floor=0.1):
"""Calentamiento lineal y coseno hasta floor*peak; el mismo plan para todas las variantes."""
if step <= warmup:
return peak * step / warmup
return peak * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * (step - warmup) / (steps - warmup))))
def optimizer(model, lr):
"""AdamW con decaimiento solo en las matrices del cuerpo (no en tablas, normas ni sesgos)."""
decays = lambda n, p: p.ndim >= 2 and not n.startswith(('token', 'position'))
decay = [p for n, p in model.named_parameters() if decays(n, p)]
rest = [p for n, p in model.named_parameters() if not decays(n, p)]
return torch.optim.AdamW([{'params': decay, 'weight_decay': 0.1}, {'params': rest, 'weight_decay': 0.0}],
lr=lr, betas=(0.9, 0.95), fused=torch.cuda.is_available())
def evaluate(model, fixed, vocab):
model.eval(); total = 0.0
with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):
for x, y in fixed:
total += F.cross_entropy(model(x).float().reshape(-1, vocab), y.reshape(-1)).item()
model.train()
return total / len(fixed)
def train_run(name, cfg, seed, lr, P, data, fixed, target):
vocab = data['vocab']
hidden, body, total = matched_width(vocab, P['context'], D, LAYERS, HEADS, target, cfg)
torch.manual_seed(seed) # inicialización: depende solo de la semilla
model = StudyGPT(vocab, P['context'], D, LAYERS, HEADS, hidden, cfg).cuda()
opt = optimizer(model, lr)
batches = torch.Generator().manual_seed(1000 + seed) # mismos lotes para todas las variantes de una semilla
points, train_time = [], 0.0
torch.cuda.reset_peak_memory_stats()
for step in range(1, P['steps'] + 1):
x, y = windows(data['train'], P['batch'], P['context'], batches, 'cuda')
torch.cuda.synchronize(); start = time.perf_counter()
for group in opt.param_groups:
group['lr'] = lr_at(step, lr, P['warmup'], P['steps'])
with torch.autocast('cuda', dtype=torch.bfloat16):
loss = F.cross_entropy(model(x).float().reshape(-1, vocab), y.reshape(-1))
if not torch.isfinite(loss):
raise RuntimeError(f'Pérdida no finita: {name}, semilla {seed}, paso {step}')
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
torch.cuda.synchronize(); train_time += time.perf_counter() - start
if step % P['eval_every'] == 0:
points.append({'tokens': step * P['batch'] * P['context'], 'val_loss': evaluate(model, fixed, vocab)})
run = {'variant': name, 'seed': seed, 'lr': lr, 'checkpoints': points,
'config': {'hidden': hidden, 'body_parameters': body, 'parameters': total, 'options': cfg,
'tokens_per_second': P['steps'] * P['batch'] * P['context'] / train_time,
'peak_allocated_bytes': torch.cuda.max_memory_allocated()}}
del model, opt
torch.cuda.empty_cache()
return run
def sweep(preset='full', out=None, variants=None):
"""Barrido reanudable: guarda tras cada ejecución y omite las que ya están en el JSON."""
if not torch.cuda.is_available():
raise RuntimeError('El barrido necesita una GPU con CUDA')
P = PRESETS[preset]
folder = corpus_dir(P['corpus'])
parts, eot, vocab_sha = load_corpus(folder, P['max_train_tokens'])
data = {'train': parts['train'], 'vocab': eot + 1}
selection, evaluation = split_validation(parts['valid'], eot)
def fixed(part):
g = torch.Generator().manual_seed(92)
return [windows(part, P['batch'], P['context'], g, 'cuda') for _ in range(P['eval_windows'] // P['batch'])]
sel_batches, eval_batches = fixed(selection), fixed(evaluation)
target = count_for(data['vocab'], P['context'], D, LAYERS, HEADS, 4*D, configs(HEADS)['base'])[0]
path = Path(out or os.environ.get('P06_ABLATION_DIR', 'p06_ablation')) / f'ablaciones-{preset}.json'
path.parent.mkdir(parents=True, exist_ok=True)
protocol = {'preset': preset, **P, 'd': D, 'layers': LAYERS, 'heads': HEADS, 'vocab': data['vocab'],
'target_body_parameters': target, 'selection_seed': SELECT_SEED, 'evaluation_seeds': EVAL_SEEDS,
'vocab_sha256': vocab_sha, 'train_tokens': int(sum(len(a) for a in parts['train'])),
'selection_tokens': int(len(selection[0])), 'evaluation_tokens': int(len(evaluation[0]))}
state = json.loads(path.read_text(encoding='utf-8')) if path.exists() else {'protocol': protocol, 'selection': {}, 'runs': []}
if state['protocol'] != protocol:
raise ValueError(f'{path} se generó con otro protocolo: usa otra carpeta')
def save():
tmp = path.with_suffix('.tmp'); tmp.write_text(json.dumps(state, ensure_ascii=False, indent=1), encoding='utf-8'); tmp.replace(path)
for name, cfg in configs(HEADS).items():
if variants and name not in variants:
continue
tried = state['selection'].setdefault(name, {})
for lr in P['rates']:
if str(lr) not in tried:
run = train_run(name, cfg, SELECT_SEED, lr, P, data, sel_batches, target)
tried[str(lr)] = run['checkpoints'][-1]['val_loss']; save()
print(f'{name}: tasa {lr:g} -> selección {tried[str(lr)]:.4f}', flush=True)
best = min(P['rates'], key=lambda lr: tried[str(lr)])
for seed in EVAL_SEEDS:
if not any(r['variant'] == name and r['seed'] == seed for r in state['runs']):
run = train_run(name, cfg, seed, best, P, data, eval_batches, target)
state['runs'].append(run); save()
print(f"{name}: semilla {seed}, tasa {best:g}, evaluación {run['checkpoints'][-1]['val_loss']:.4f}, "
f"{run['config']['tokens_per_second']:.0f} tokens/s", flush=True)
return path
# Comprobaciones en CPU con datos sintéticos: ventanas, plan de la tasa y partición por documentos.
toy = [np.arange(10, dtype='<u2'), np.arange(100, 106, dtype='<u2')]
x, y = windows(toy, 64, 3, torch.Generator().manual_seed(0), 'cpu')
assert torch.equal(x[:, 1:], y[:, :-1]) and torch.all(y - x == 1) # cada ventana cae dentro de un shard
assert set(x[:, 0].tolist()) == {0, 1, 2, 3, 4, 5, 100, 101} # todos los inicios válidos, nada más
assert lr_at(15, 1e-3, 15, 150) == 1e-3 and abs(lr_at(150, 1e-3, 15, 150) - 1e-4) < 1e-12
docs = np.array([5, 6, 9, 7, 9, 1, 2, 3, 9, 4, 9], dtype='<u2') # 9 marca el fin de documento
sel, ev = split_validation([docs], 9)
assert sel[0][-1] == 9 and len(sel[0]) + len(ev[0]) == len(docs)
for preset, P in PRESETS.items():
runs = len(configs(HEADS)) * (len(P['rates']) + len(EVAL_SEEDS))
tokens = P['steps'] * P['batch'] * P['context']
print(f"{preset}: {runs} ejecuciones de {tokens/1e6:.2f}M tokens, {runs*tokens/1e9:.2f}G tokens en total")npm run lab and open the connection link.import os, json
preset = os.environ.get('P06_L08_SWEEP')
if preset:
path = sweep(preset)
rows = ablation_table(json.loads(path.read_text(encoding='utf-8')))
else:
print('Barrido no lanzado: define P06_L08_SWEEP=short (verificación) o P06_L08_SWEEP=full (barrido completo).')npm run lab and open the connection link.To launch from a terminal, set the variable and run the notebook or a script containing all four cells: P06_L08_SWEEP=short for verification and P06_L08_SWEEP=full for the full sweep. Results are stored in P06_ABLATION_DIR, default p06_ablation, as ablaciones-short.json or ablaciones-full.json, and can be loaded into the next section’s explorer.
The full sweep is 48 runs of 40.96 million tokens, 1.97 G tokens. At the short-run measured rates of 33 000 to 54 000 tokens per second depending on variant, that is on the order of 10 to 17 hours on an RTX 4060. Because it resumes, you can spread it across nights or run only selected variants with sweep('full', variants=['base', 'swiglu']). Memory is determined by the modern variant: in a 40-step measurement at context 512 it peaked at 1.09 GiB with 4 sequences per batch and 1.64 GiB with 8. Linear extrapolation to the sweep’s 32 sequences gives about 5 GiB, versus about 3 GiB for baseline.
Short-run results and expectations
The short run (P06_L08_SWEEP=short) uses the same roughly 30-million-parameter model but trains for 150 steps of 16 sequences of 256 tokens, 614 400 tokens per run, on the p06-l02 sample: 2.2 million training tokens, 120 838 validation tokens for rate selection, and 115 870 for evaluation. The 40 runs took about 10 minutes. This checks the pipeline end to end; it is not the experiment, since the model has barely started learning. This table was printed by the fourth cell with P06_L08_SWEEP=short; selected rate was for all, and Δ is variant minus baseline in nats:
| Variant | Mean loss | Std. dev. | Mean Δ | 95% CI for Δ | Holm p | Tokens/s | Peak GiB |
|---|---|---|---|---|---|---|---|
| base | 3.9805 | 0.0508 | 53 504 | 1.17 | |||
| rope | 3.6369 | 0.0316 | −0.3437 | [−0.4923, −0.1950] | 0.070 | 47 737 | 1.17 |
| rms | 4.1058 | 0.1662 | +0.1253 | [−0.2728, +0.5234] | 1.000 | 41 337 | 1.30 |
| swiglu | 3.9404 | 0.0205 | −0.0402 | [−0.1994, +0.1191] | 1.000 | 46 488 | 1.28 |
| sin_sesgos | 3.9747 | 0.0203 | −0.0058 | [−0.0822, +0.0706] | 1.000 | 50 553 | 1.17 |
| gqa | 4.0700 | 0.2184 | +0.0895 | [−0.3291, +0.5081] | 1.000 | 48 587 | 1.19 |
| qknorm | 4.0373 | 0.0071 | +0.0568 | [−0.0735, +0.1870] | 1.000 | 43 142 | 1.41 |
| moderno | 3.6466 | 0.0563 | −0.3339 | [−0.5422, −0.1257] | 0.122 | 32 679 | 1.65 |
The explorer loads those same 24 evaluation runs. Start with baseline versus the modern block at the last checkpoint, then select rows in the lower panel for each variant and move the checkpoint backwards.
Four readings, all from this short run:
- RoPE and the full block stand out but do not pass Holm. The three
ropeseeds give of −0.29, −0.33, and −0.41, andmodernogives −0.25, −0.33, and −0.42. Their uncorrected intervals exclude zero, with p-values 0.010 and 0.020, but Holm over seven comparisons multiplies them by 7 and 6: 0.070 and 0.122. With three seeds, even an effect of one-third of a nat does not survive correction. The full block not winning more than RoPE alone is informative too: cumulative improvement is not the sum of individual effects. - One seed can pull the mean. For
rmsandgqa, two of three differences are near zero and the third is +0.30 and +0.28. The mean becomes positive and interval enormous. Select those variants in the explorer and inspect per-seed curves before the mean. - The selected rate is at the grid boundary. Every variant chose , the smaller of two values tried, since gave 4.12 to 4.76 in selection versus 3.74 to 4.10. When the best rate lies at the edge, the optimum may lie outside: the full sweep grid therefore includes .
- The modern block is slower without compilation. Its 32 679 tokens per second versus baseline 53 504 comes from small operations launched individually by PyTorch: hand-written RMSNorm, four operations instead of one kernel, QK-norm, SwiGLU’s third matrix, and the
repeat_interleavecopy for GQA. These are rates from runs lasting a few seconds, sensitive to any other GPU process. The full sweep measures them more precisely, andtorch.compilecan fuse many of those operations.
What should we expect from the full sweep? There is no published number for this model and corpus, and we will not invent one. References bound the order of magnitude. In Narang and colleagues, with 223 million parameters and 524 288 steps, the best changes move final loss by hundredths: 1.838 baseline, 1.821 with RMSNorm, and 1.789 with SwiGLU; standard deviation of early loss across five runs is 0.003 to 0.008. In Shazeer, SwiGLU improves over GELU by 0.039 after 65 536 steps and 0.043 after 524 288. Ainslie and colleagues find that grouping KV heads into 8 groups barely changes quality. RoPE’s early advantage in the short run may plausibly shrink with longer training because the learned position table has barely had steps to learn. The full sweep, with ten checkpoints, lets you see its evolution. Effects of RMSNorm, SwiGLU, no biases, and GQA are expected to be hundredths or less, on the order of seed noise, with some indistinguishable from zero across three seeds. That too is a result.
Choose the final configuration
The full sweep gives, for each variant, mean loss and standard deviation over three seeds, paired difference versus baseline with interval and Holm p-value, throughput, and memory. The moderno row is cumulative improvement against the GPT-2 block under the same token and body-parameter budget, which approximately matches compute per token. Use this to decide component by component:
- Resolved improvement (Holm p-value below 0.05 and ): adopt it and record effect size with interval.
- Unresolved effect but cost advantage: GQA halves our model’s KV cache, 15 360 versus 7680 bytes per token and sequence, which matters at inference even without improved loss. It can be adopted for cost while stating that its loss effect is indistinguishable from noise with three seeds, rather than saying it has no effect.
- Unresolved effect and greater cost, such as QK-norm with no improvement and lower rate: leave it as a disabled option and document the interval so nobody repeats it without knowing.
- Combination: compare
modernowith the sum of individual effects. If clearly smaller, components overlap; if larger, they interact. In both cases validate the final configuration as a whole.
The final report is more than the table: include the rate grid and winner per variant, seed count, correction, and nonsignificant effects with intervals. An ablation concluding “at this scale most changes are indistinguishable from noise” is a good result when well measured; that is what Narang and colleagues found at much larger scale.
Exercises
Step 1 of 3. How can the product be rewritten so the two rotations are adjacent?
import numpy as np
def swiglu(x, W_gate, W_up, W_out):
pass
def matched_width(d):
passA modern architecture is a set of decisions measurable one by one. Identities, such as RoPE seeing only displacement, QK-norm bounding logits, and GQA reducing cache by , are proved and checked with tests. Loss improvement requires a protocol with matched budget, per-variant rates, paired seeds, and intervals. The final decision weighs that effect and its uncertainty against memory and throughput cost.