New Track 1 record attempt — PR #413 (code) & PR #414 (record logs): Over 16 consecutive unseeded
8×H100runs (zero dropped), we averaged29.8578 ± 0.0146 s—−244.6 msfaster than interleaved#406(30.1024 ± 0.0043 s, Welchp = 4.82 × 10⁻²³) on the exact same node, with meanval_loss3.27869 ± 0.00144(13/16 < 3.28, one-sidedp = 0.00122 ≪ 0.01) and44.66 WhGPU energy (−0.38 Whvs#407). On a node clocked like our Nov 22#407run (29.9025 s), that corresponds to29.66 s.
In my previous post on Looped Transformers, looping made the model learn a bit better (3.2679 validation loss), but cost roughly twice as much GPU time as standard single-pass training in the modded-nanogpt speedrun — a community race to train a GPT-2-scale language model from scratch to ≤ 3.28 validation loss on 8× NVIDIA H100 GPUs as fast as possible.
At the end of that post, we recorded a GPU profiler trace of the final stretch of training (Stage 3 Taper). One slow piece stood out right away: updating the model's final word-prediction table (the lm_head, which scores all 50,304 possible next words) was taking ~3.6 ms per step across the last 59 steps.
Below is what happened when we went after it — starting with cartoon-simple mental models and small pure-NumPy (picoGPT) snippets, walking through the nine ideas that failed along the way, and finishing with the GPU profiler proof of what actually worked.
1. Idea #1 (67% of the Win, −165 ms): Updating the Final Word Table 4× Faster
If you have never trained an LLM before, Stage 3 Taper is easiest to picture like painting a portrait on a 30-second timer:
- For the first 92% of training (Steps
0–970), the trainer uses a broad brush to move fast. Instead of scoring every word against all50,304words in the dictionary, it only scores a smaller random subset (10,240 → 24,576words per step — called sampled softmax). - For the final 59 steps (Stage 3 Taper), it switches to a fine brush: the step size tapers down and the model scores all
50,304words so its final probabilities lock in cleanly.
In simplified picoGPT-style Python, that two-brush training loop looks like this:
# Simplified modded-nanogpt training loop (broad brush -> fine brush)
for step in range(1049):
if step < 970: # Stages 0–2: broad brush (fast!)
cand = sample_vocab(P=10240..24576) # only score a slice of the 50k words
loss = cross_entropy(x @ W[cand].T, targets_in_cand)
else: # Stage 3 Taper + Ext: fine brush!
# Score ALL 50,304 words -> expensive! This is where our 1-in-4 dW trick kicks in.
loss = cross_entropy(x @ W.T, targets)On every training step, the final word-prediction layer (logits = x @ W.T) has to do two big matrix multiplies during backpropagation (the step that calculates how to adjust the model's weights):
dX = G @ W(per-token feedback): tells each of the40,960tokens in the batch how to adjust the 11 transformer layers below it. Every single token needs its own exact signal, sodXmust stay 100% exact.dW = G.T @ x(shared table update): averages across all40,960tokens to update one shared50,304-word output tableW.
During the broad-brush stages, modded-nanogpt already sped up dW using a trick from PRs #371 (@romeerp) and #382 (@krishaab). During the fine-brush Stage 3 Taper, however, it fell back to computing dW densely across all 40,960 tokens and all 50,304 words — taking ~14.3 ms every 4 steps (16.1 ms including transpose copies).
Assuming you cannot skip the fine brush altogether (we tried delaying full softmax into Stage 3, and validation loss got worse by +4 to +7 millinats, where 1 mnat = 0.001 loss), what can you do?
Think of it like grading 40,960 multiple-choice quizzes that each have 50,304 answer choices. Checking every single wrong choice on every single quiz is exhausting. Instead, you can always grade the right answer on every quiz (100% exact!), and only spot-check 1 in 4 quizzes for the wrong answers (counting them 4× so the average stays identical):
Looking directly at the error matrix G = predicted_probabilities − true_word, that grading trick maps 1-to-1 onto the math:
- Almost every cell is tiny and positive: small probabilities spread smoothly across all
50,304wrong words. Averaging 1 out of every 4 tokens (and multiplying by4×) gives an unbiased estimate that is4×cheaper to compute. - One cell per token is big and negative (
≈ −1): the actual next word (plus#406's<copy>pointer slot). We keep those 100% exact on every single token.
In pure NumPy (picoGPT style), the whole change is just 10 lines:
def lm_head_backward(x, W, G, targets, group=4, offset=0):
dX = G @ W # per-token feedback stays 100% exact
- dW = G.T @ x # dense [V, T] @ [T, D] (40,960 rows!)
+ # 1. Sample 1 in every `group` rows of the positive softmax mass (scaled by `group` -> unbiased)
+ rows = np.arange(offset, len(x), group)
+ G_pos_sub = np.maximum(G[rows], 0.0)
+ dW = (group * G_pos_sub.T) @ x[rows] # 4× smaller matrix multiply!
+
+ # 2. Add the negative target spikes 100% exactly on EVERY token
+ # (Standard CE: only targets[i] < 0; in modded-nanogpt, <copy> & MTP targets are also added exact.)
+ all_rows = np.arange(len(x))
+ g_neg = np.minimum(G[all_rows, targets], 0.0)
+ np.add.at(dW, targets, g_neg[:, None] * x) # exact sparse scatter-add
return dX, dWIn modded-nanogpt's actual GPU code (track_1_short/perf/kernels/cplm.py), the fast sampled_head.ce_backward kernel already existed for Stages 0–2. Wiring it into Stage 3 Taper took seven net lines of code (+11 / −4 lines) — and on 8×H100 it saved −165 ms with zero validation-loss penalty (3.2767 vs 3.2767 at matched steps).
(See the Appendix at the bottom for a runnable NumPy script that verifies E[dW_sampled] == dW_exact to 10⁻¹⁵.)
2. Idea #2 (33% of the Win, −80 ms Net): 42 Numbers That Keep Attention Sharp
While profiling #406, we also checked the newest open PRs on KellerJordan/modded-nanogpt. One idea stood out: @FeSens's PR #409 (Centered Mask-Aware SSMax, posted Nov 25 on the 40.45 s master baseline).
Here is the intuition without any math jargon. Inside a Transformer, attention works like listening for the right voices in a room. In a small room of 20 words, the 2 important voices stand out clearly. In a crowded stadium of 1,408 words, hundreds of background voices whisper at once and drown out the signal. Mask-Aware SSMax adds one tiny automatic focus dial per attention head (7 attention layers × 6 attention heads = 42 learned numbers total) that turns up focus based on how big the crowd actually is:
Under the hood, Mask-Aware SSMax counts how many earlier words N_vis each token can actually see (stopping at <|endoftext|> document boundaries and the layer's sliding-window limit), and scales each attention query by τ = max(0.25, 1 + s · (log N_vis − 5.5)). All 42 learned slopes start at 0.0, so step 0 is exact identity.
In picoGPT's attention function, it is a 4-line diff:
def attention(q, k, v, mask, log_n_vis=None, ssmax_s=None):
+ if ssmax_s is not None:
+ # Centered Mask-Aware SSMax: soften short docs, sharpen long windows
+ tau = np.maximum(0.25, 1.0 + ssmax_s * (log_n_vis - 5.5))
+ q = q * tau[:, None]
return softmax(q @ k.T / np.sqrt(q.shape[-1]) + mask) @ vOn the GPU, doing that multiplication as a separate PyTorch step would waste memory bandwidth reading and writing q back and forth across all 7 layers. Instead, we fused it directly into #406's existing Triton attention-prep kernel (perf/kernels/qkv_rope.py):
- In the forward pass,
qis scaled while it is already sitting in the GPU's fastest on-chip scratchpad (registers), costing just+2 µs/step. - In the backward pass, the dot product needed for
s's gradient turns out to be algebraically identical to a dot product the normalization kernel already computes in registers — zero extra GPU memory reads (+33–48 µs/step, verified against FP32 PyTorch autograd torel = 2.43 × 10⁻⁷).
Because the speedrun races to a fixed 3.28 loss target, learning slightly better per step lets you stop earlier. On 1×H100 (3 paired seeds), fused SSMax improved validation loss by −3.06 mnats. On 8×H100 on top of #406 (which already includes YaRN window scaling and extra attention upgrades), the remaining headroom was enough to trim 4 steps (1,053 → 1,049 steps), trading +45 ms of kernel time for −125 ms of skipped steps (−80 ms net).
3. The Graveyard: Nine Ideas That Looked Promising and Still Died
Before spending serious 8×H100 money, we screened ten candidates cheaply on a single 1×H100 ($7.31 total) and then tested the survivors on 8×H100. Most ideas did not survive — and a few failed in ways that taught us more than the winners did:
Killed on 1×H100 ($7.31 total screening)
S3_fwd(Fused FP8 quantizer — the Compiler Fusion Trap): Our standalone microbenchmark was1.79×faster with0bit mismatches (projecting−400 ms), yet inside compiled training it ran+0.33 to +0.57 ms/stepslower. Wrapping it as an opaque custom PyTorch op stopped thetorch.compile(Inductor) compiler from fusing it with the normalization step right before it, forcing an extra round-trip to GPU memory that erased the win:
S1&S2(Custom RMSNorm / FP8 Triton kernels): Our profiler showed PyTorch emitting low-occupancy reduction kernels, so hand-written multi-warp Triton replacements looked like an easy−300 ms. In practice, PyTorch 2.10's fused backward was still faster (andS2's approximate transpose hitNaNon warmup).MuonGS& Adaptive-Radius MuonH (#410/#411): Orthogonalizing updates via Gram-Schmidt or adaptive radius hurt validation loss by+206to+468mnats on#406's optimizer while slowing each step by+0.6–1.4 ms.RELU_THRESH=0.05&TailAveragesreset (180st): Both hurt validation loss (+1.16and+3.0mnats) on 3-seed1×H100checks.
Killed on 8×H100 (Diagnostic A/B)
S3(dual_quant_bwdfor MLP backward): Projected−112 msfaster on1×H100, yet ran+30 msslower on8×H100(30.188 svs30.158 s) because Inductor's default backward already overlapped with NVLink multi-GPU communication — a reminder that single-GPU kernel wins do not always transfer to 8 GPUs.S3_FULL_SOFTMAX_DELAY(D=44andD=59Taper steps): Trying to keep the broad brush (P = 24,576) into Stage 3 Taper cut time to29.51–29.79 s, but cost+4.0to+6.9mnats (3.2815/3.2844). Stage 3 Taper really needs all50,304words for forward scores anddX; onlydWcan be 4× sampled without hurting loss.Sub-Top L=9Looped Transformer + SSMax (Follow-up to our Looped post): Stacking ourSub-Top L=9loop on top of SSMax stacked additively on8×H100, pushing validation loss down to3.2741at31.855 s(G=40) and3.2827at30.897 s(G=16). Interpolated break-even at3.278is~31.3 s— still~1.2 sbehind 1-pass#406, confirming looping is not ready for a sub-29.9 s run yet.G=44(−8steps,29.69 sRAW): Our first single run hit29.686 s / 3.2785, so we started multi-run validation there — and checked in at minute 20. Four consecutive runs averaged3.27945(2/4 > 3.28), too tight to clearp < 0.01reliably. Stopping early at minute 20 saved~$20and let us calibrate the exact+0.25 mnats/stepslope and pivot cleanly toG=48.
4. N=16 Interleaved Results on 8×H100 (and Why Round 5 Mattered)
We ran five interleaved rounds on one 8× NVIDIA H100 80GB HBM3 SXM5 node (RunPod AP-IN-1, 56/56 NV18 NVSwitch, PyTorch 2.10.0+cu128, Triton 3.6.0, zero nvidia-smi or profiler attached during any timed run, zero runs dropped):
| Arm | Runs (n) |
Steps | Wall Time (AP-IN-1) |
vs #406 (same node) |
val_loss (mean ± sd) |
One-sided p (< 3.28) |
|---|---|---|---|---|---|---|
#406 baseline (interleaved) |
5 |
1,053 |
30.1024 ± 0.0043 s |
0 ms |
3.27830 ± 0.00199 (4/5 < 3.28) |
p = 0.0643 |
PR #413 / #414 (S4b=4 + fused #409, G=48) |
16 |
1,049 |
29.8578 ± 0.0146 s |
−244.6 ms (−0.81%) |
3.27869 ± 0.00144 (13/16 < 3.28) |
t = −3.635, p = 0.00122 |
Three details worth noting:
- Speed precision & node silicon bin: Across all 5 interleaved rounds, the round-by-round paired delta was
−0.2451 ± 0.0093 s(paired t = −58.66,p = 5.06 × 10⁻⁷; Welcht = −59.42,p = 4.82 × 10⁻²³). Notice thisAP-IN-1node clocked#406at30.1024 s(~+200 msslower than the Nov 22 node where#406/#407clocked29.9025 s) — yetPR #413 / #414still beat29.9025 sin raw unnormalized seconds (29.8578 s,−44.7 msraw;29.660 snormalized). - Why we ran Round 5 (
N=12 → N=16, zero dropped runs): After Rounds 1–4 (n=12), a single noisy seed in Round 2 (3.2821, visible at the top of Panel A) left one-sidedp = 0.0135— just0.0035shy of0.01, even though the other 11 runs averaged3.27855(p = 0.0016). Instead of dropping or cherry-picking anything, we kept all 12 runs and added Round 5 (+1 #406,+4 PR #413). All four Round-5 runs finished under3.28(3.2797, 3.2777, 3.2776, 3.2779), bringing the fulln=16set cleanly to3.27869 ± 0.00144,p = 0.00122 ≪ 0.01(non-parametric Wilcoxonp = 0.00356). - Power & energy (
NVML 10 Hzseparate run): Right after the timed runs finished, a dedicated 10 Hznvidia-smitelemetry run clocked29.872 s(+14.2 msobserver overhead,val_loss = 3.2788) at5,385.2 Wmean active 8-GPU power (673.2 W/GPU, peak5,568.2 W,1,882 MHzmean SM clock,98.7%util,70 °Cmax) —44.66 What the 16-run mean time (−0.38 Whlower than#407's45.04 Wh) and34,309 MiBpeak allocated VRAM (+0 MiBvs#406).
5. Inside the CUPTI Profiler: Hardware Proof of −154.7 ms & Where Sub-29.5 s Lives
Before terminating the 8×H100 node, we captured a Rank-0 NVIDIA CUPTI 3-stage kernel profile of PR #413 (steps 200, 700, and 980 — Stages 1, 2, and 3 Taper) and downloaded the traces locally for analysis.
The hardware counters line up closely with our stopwatch ablations:
- Stage 3 Taper
S4b=4(−154.7 msCUPTI vs−165 msstopwatch): Eliminating the dense full-vocablm_head dWGEMM (8.615 ms → 0.000 msper 4 steps) and shrinking_transpose_copy_kernel(7.490 ms → 1.811 ms,−5.679 ms) against the replacementGROUP=4sampleddWGEMM (2.304 ms) +_sample_transpose(1.502 ms) yields−10.488 msper 4 steps =−2.622 ms/step× 59 Taper steps =−154.7 ms. - Fused SSMax (
+42 msCUPTI vs+45 msstopwatch):_qk_norm_rope_forward_kernelgrew by just+2 µs/step, and_qkv_norm_rope_pack_fp8_backward_kernelgrew by+33–48 µs/step(~+42 msacross1,049steps).
And Panel B points straight to the four biggest remaining targets if we want to push toward sub-29.5 s next:
Not bad for +138 net lines of code (0 changes to train_gpt.py) and zero extra VRAM.
How this experiment was run & attribution
- Upstream PRs (paired code + record, same 2-PR convention as
#406/#407):- Code PR:
KellerJordan/modded-nanogpt#413(atveit:pr/wr5-ssmax-s3-sampled-head, commit894b331,7files,+176 / −38lines on#406) - Record PR:
KellerJordan/modded-nanogpt#414(atveit:pr/wr5-ssmax-s3-sampled-head-record, commit5df6c16, README + all 21 official UUID logs)
- Code PR:
- Compute & discipline: Built with Google Antigravity and parallel Gemini agents for kernel authoring,
1×H100multi-seed screening ($7.31on RunPodEUR-IS-3),8×H100 SXM5diagnostics +N=16interleaved runs + separate 10 Hz NVML + Rank-0 CUPTI profiling (~$110on8×H100, RunPodAP-IN-1, total campaign~$117.7). All pods were terminated (HTTP 204,$0.00/hr) immediately after downloading logs and traces; all deep CUPTI and statistical analysis ran locally on macOS. - Transparency note: The 21 official UUID logs in
#414were recorded from our ablation checkout (d59fdd0) withSSMAX_ENABLED=1 S3_SAMPLED_HEAD_WG=4 SCHEDULE_GROWTH_STEPS=48(all other experimental flags off); clean commit894b331(#413) strips the unused disabled modules and makes that exact configuration the default. - Credit:
#409by@FeSens(Mask-Aware Softmax Scaling): Centered Mask-Aware SSMax (+42per-head slopes), ported and fused into#406's Tritonqkv_rope.py(~33% of our speedup /−80 msnet).#371(@romeerp) /#382(@krishaab): original sampledlm_head dWformulation (sampled_head.py) for sampled-softmax stages, which we extended into full-vocab Stage 3 Taper (~67% of our speedup /−165 ms).#406/#407(@atveit),#404(@caraxesml),#396/#397(@atveit),#393(@francesco-prignano), and themodded-nanogptcommunity (@KellerJordan,@YouJiacheng,@classiclarryd,@DevenPzak,@NathanGodey), plus Jay Mody's picoGPT.
Appendix: Executable picoGPT NumPy Code
If you want to try both ideas yourself on a laptop in pure NumPy (no PyTorch or GPU needed), both snippets below are completely self-contained and heavily commented.
1. Stage 3 Sampled lm_head dW + Unbiasedness Check
Each step only needs one of the 4 row phases (offset = 0, 1, 2, or 3), scaling that 1/4 slice by 4×. Averaging across all 4 phases recovers the exact dense weight gradient down to float64 machine precision (~10⁻¹⁵):
import numpy as np
def lm_head_backward_exact(x, W, G):
"""Standard (dense) backward pass for logits = x @ W.T.
x: [T, D] final hidden states (T tokens, width D)
W: [V, D] output vocabulary table (V words, width D)
G: [T, V] cross-entropy gradient (predicted_probs - one_hot(targets))
"""
dX = G @ W # [T, D]: error flowing back into each token's transformer layers
dW = G.T @ x # [V, D]: full dense sum over all T tokens (expensive when T=40k, V=50k!)
return dX, dW
def lm_head_backward_sampled(x, W, G, targets, group=4, offset=0):
"""Unbiased 1-in-`group` sampled positive dW + exact negative targets + exact dX.
Standard CE has G[i, j] < 0 ONLY at j == targets[i] (in modded-nanogpt, the extra
<copy> pointer column and multi-token targets are also excluded from sampling and added exact).
"""
# 1. Keep per-token feedback dX 100% exact so the transformer layers get clean gradients.
dX = G @ W
# 2. Positive part (tiny softmax probabilities on all wrong words):
# Take only 1 out of every `group` rows (here 1/4 of rows) and multiply by `group` (4x)
# so the expected value stays strictly unbiased, while cutting the GEMM by 4x!
rows = np.arange(offset, len(x), group) # e.g. [0, 4, 8, ...] when offset=0
G_pos_sub = np.maximum(G[rows], 0.0) # keep only positive entries >= 0
dW = (group * G_pos_sub.T) @ x[rows] # 4x smaller matrix multiply
# 3. Negative part (large ~ -1.0 spikes on the true target word):
# Add these 100% EXACTLY for every single token (only 1 column per row -> cheap scatter!).
all_rows = np.arange(len(x))
g_neg = np.minimum(G[all_rows, targets], 0.0) # [T] negative error at each true word
np.add.at(dW, targets, g_neg[:, None] * x) # exact sparse scatter-add into dW
return dX, dW
# --- Self-check: average over the 4 phase offsets (0, 1, 2, 3) and compare to exact dW ---
rng = np.random.default_rng(0)
T, D, V = 64, 16, 128 # toy batch: 64 tokens, width 16, 128 words
x = rng.standard_normal((T, D))
W = rng.standard_normal((V, D)) * 0.1
targets = rng.integers(0, V, size=T)
# Forward softmax probabilities + exact cross-entropy gradient G = probs - one_hot(targets)
logits = x @ W.T
probs = np.exp(logits - logits.max(axis=-1, keepdims=True))
probs /= probs.sum(axis=-1, keepdims=True)
G = probs.copy()
G[np.arange(T), targets] -= 1.0
dX_exact, dW_exact = lm_head_backward_exact(x, W, G)
dW_avg = sum(
lm_head_backward_sampled(x, W, G, targets, group=4, offset=k)[1]
for k in range(4)
) / 4.0
print("max |E[dW_sampled] - dW_exact|:", np.max(np.abs(dW_avg - dW_exact))) # ~3.5e-15 (exact!)2. Packed-Document Centered Mask-Aware SSMax (picoGPT Attention)
When training packs multiple variable-length documents back-to-back in one flat array (seqlens marks where each document starts and ends), each token's visible history pos must reset to 1 at every new document and stop growing once it hits the layer's sliding window_size:
import numpy as np
def mask_aware_log_n(seqlens, T, window_size):
"""Compute centered log(# visible keys) for every token in a packed stream.
seqlens: cumulative document boundaries, e.g. [0, 7, 16] = Doc 1 (len 7), Doc 2 (len 9)
T: total tokens in the flat stream (16 here)
window_size: sliding attention window cap (e.g. 128..1408 tokens)
"""
pos = np.empty(T, dtype=np.float32)
for start, end in zip(seqlens[:-1], seqlens[1:]):
length = end - start
# Position resets to 1 at the start of every new document!
pos[start:end] = np.arange(1, length + 1, dtype=np.float32)
# Cap at the layer's sliding window, take log, and center around log(245) ≈ 5.5
# -> negative for short contexts (< 245 tokens), positive for long windows (> 245 tokens)
visible = np.minimum(pos, float(window_size))
return np.log(visible) - 5.5
def ssmax_scale_queries(q, seqlens, window_size, ssmax_s):
"""Scale attention queries q [T, H, D] by per-head window-aware factor tau.
ssmax_s: [H] learned FP32 slopes (1 per head, initialized to 0.0 -> tau = 1.0 at step 0)
"""
log_n = mask_aware_log_n(seqlens, q.shape[0], window_size) # [T]
# Floor at 0.25 so extreme short contexts never flip sign or vanish
tau = np.maximum(0.25, 1.0 + log_n[:, None] * ssmax_s[None, :]) # [T, H]
return q * tau[:, :, None] # fused in registers on GPU!
# --- Quick check on a 16-token stream with 2 packed documents [0..7) and [7..16) ---
q = np.ones((16, 6, 8), dtype=np.float32)
print("zero-init diff:", np.max(np.abs(ssmax_scale_queries(q, [0, 7, 16], 128, np.zeros(6)) - q)))Best regards,
Amund