Modded-NanoGPT Track 1 Speedrun Progression chart on 8× NVIDIA H100 from Record #91 (67.56s) through Record #92 (39.90s), PR #391 (34.86s), PR #397/#396 (30.67s), PR #404 (30.25s), PR #407/#406 (29.90s), to PR #414/#413 (29.86s on Nov 29, 2026)

New Track 1 record attempt — PR #413 (code) & PR #414 (record logs): Over 16 consecutive unseeded 8×H100 runs (zero dropped), we averaged 29.8578 ± 0.0146 s — −244.6 ms faster than interleaved #406 (30.1024 ± 0.0043 s, Welch p = 4.82 × 10⁻²³) on the exact same node, with mean val_loss 3.27869 ± 0.00144 (13/16 < 3.28, one-sided p = 0.00122 ≪ 0.01) and 44.66 Wh GPU energy (−0.38 Wh vs #407). On a node clocked like our Nov 22 #407 run (29.9025 s), that corresponds to 29.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.

Playful cartoon of 8 H100 GPU runners sprinting across a Goal: ≤ 3.28 Loss finish ribbon under a 29.86 s stopwatch (−245 ms faster!), carrying Faster 50k-Word Updates and wearing +42 Attention Dials goggles

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 all 50,304 words in the dictionary, it only scores a smaller random subset (10,240 → 24,576 words 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,304 words so its final probabilities lock in cleanly.
Timeline showing how a 30-second 1,049-step LLM run uses two brushes: Steps 0–970 (92% of run) use a Broad Brush (Sampled Softmax over 10k–24k of 50k words), while Steps 970–1,029 (Stage 3 Taper, final 59 steps) switch to a Fine Brush (Full 50,304-word Softmax) where dense lm_head dW took ~3.6 ms/step; PR #413 keeps the fine brush for logits and dX while sampling 1-in-4 rows for dW for −165 ms with zero loss hit

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):

  1. dX = G @ W (per-token feedback): tells each of the 40,960 tokens in the batch how to adjust the 11 transformer layers below it. Every single token needs its own exact signal, so dX must stay 100% exact.
  2. dW = G.T @ x (shared table update): averages across all 40,960 tokens to update one shared 50,304-word output table W.

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):

Two-panel editorial cartoon comparing a stressed teacher checking all 50,303 wrong answers on all 40,960 quizzes (Old Way: Slow!) against a relaxed smiling teacher who always grades the right answer on every quiz (100% exact) and spot-checks only 1 in 4 quizzes for wrong answers (count ×4) — 4× less work, −165 ms saved with zero loss hit

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,304 wrong words. Averaging 1 out of every 4 tokens (and multiplying by 4×) gives an unbiased estimate that is 4× 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.
Three-step visual anatomy of Sampled LM-Head dW in Stage 3 Taper: Full-vocab logit gradient G (40,960 × 50,304) splits into top branch Positive Mass max(G, 0) sampled 1-in-4 rows (weight × 4, 4× smaller unbiased FP8 GEMM) and bottom branch Target Spikes min(G, 0) + <copy> added via exact sparse scatter-add on 100% of tokens, while dX = G @ W stays 100% exact, cutting dense dW GEMM from 8.62 ms to 0.00 ms and transpose copies from 7.49 ms to 1.81 ms for −165 ms net savings

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, dW

In 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:

Three-panel cartoon showing Quiet Room (20 words: easy to hear key words), Crowded Stadium (1,408 words: important words get drowned out), and Mask-Aware SSMax (+42 auto-focus dials on headphones turning up focus based on crowd size so key words stand out sharply again)

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.

Educational diagram of Mask-Aware SSMax (#409): Top strip shows packed token stream with <|endoftext|> document boundaries and sliding-window cap; Left card shows diluted flat softmax attention across 1,408 keys without scaling; Right card shows crisp peaked attention with Mask-Aware SSMax (+42 scalars, τ = max(0.25, 1 + s·(log N_vis − 5.5))); Bottom bar shows Triton QK-Norm+RoPE fusion (+2 µs fwd, zero extra HBM reads) saving 4 training steps (−80 ms net)

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) @ v

On 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, q is 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 to rel = 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:

Three-column scorecard funnel showing experiments killed on 1×H100 ($7.31), experiments killed on 8×H100 diagnostic A/B, and the two survivors in PR #413 / #414 reaching 29.858 s (N=16, p = 0.0012, 44.66 Wh)

Killed on 1×H100 ($7.31 total screening)

  • S3_fwd (Fused FP8 quantizer — the Compiler Fusion Trap): Our standalone microbenchmark was 1.79× faster with 0 bit mismatches (projecting −400 ms), yet inside compiled training it ran +0.33 to +0.57 ms/step slower. Wrapping it as an opaque custom PyTorch op stopped the torch.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:
Diagram of the Compiler Fusion Trap: Top row shows PyTorch Inductor fusing RMSNorm + FP8 Cast into 1 kernel with 1 write to GPU memory (HBM); Bottom row shows Custom Op S3_fwd breaking fusion so Kernel 1 writes BF16 to HBM and Kernel 2 reads BF16 back, making a 1.79× faster microbenchmark +0.33 to +0.57 ms/step slower in real training
  • 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 (and S2's approximate transpose hit NaN on warmup).
  • MuonGS & Adaptive-Radius MuonH (#410/#411): Orthogonalizing updates via Gram-Schmidt or adaptive radius hurt validation loss by +206 to +468 mnats on #406's optimizer while slowing each step by +0.6–1.4 ms.
  • RELU_THRESH=0.05 & TailAverages reset (180 st): Both hurt validation loss (+1.16 and +3.0 mnats) on 3-seed 1×H100 checks.

Killed on 8×H100 (Diagnostic A/B)

  • S3 (dual_quant_bwd for MLP backward): Projected −112 ms faster on 1×H100, yet ran +30 ms slower on 8×H100 (30.188 s vs 30.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=44 and D=59 Taper steps): Trying to keep the broad brush (P = 24,576) into Stage 3 Taper cut time to 29.51–29.79 s, but cost +4.0 to +6.9 mnats (3.2815 / 3.2844). Stage 3 Taper really needs all 50,304 words for forward scores and dX; only dW can be 4× sampled without hurting loss.
  • Sub-Top L=9 Looped Transformer + SSMax (Follow-up to our Looped post): Stacking our Sub-Top L=9 loop on top of SSMax stacked additively on 8×H100, pushing validation loss down to 3.2741 at 31.855 s (G=40) and 3.2827 at 30.897 s (G=16). Interpolated break-even at 3.278 is ~31.3 s — still ~1.2 s behind 1-pass #406, confirming looping is not ready for a sub-29.9 s run yet.
  • G=44 (−8 steps, 29.69 s RAW): Our first single run hit 29.686 s / 3.2785, so we started multi-run validation there — and checked in at minute 20. Four consecutive runs averaged 3.27945 (2/4 > 3.28), too tight to clear p < 0.01 reliably. Stopping early at minute 20 saved ~$20 and let us calibrate the exact +0.25 mnats/step slope and pivot cleanly to G=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):

Two-panel real-data chart: Left panel scatters all 21 interleaved 8×H100 runs (16 PR #413/#414 runs at 29.858 ± 0.015 s and 3.27869 val_loss vs 5 interleaved #406 runs at 30.102 ± 0.004 s, showing −244.6 ms speedup, Welch p = 4.8e-23, and p = 0.00122 < 3.28); Right panel shows the exact same-node ablation waterfall from 30.102 s (#406) + 45 ms (SSMax kernel) − 165 ms (Stage-3 Taper sampled dW) − 125 ms (G: 52→48) = 29.858 s
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:

  1. 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⁻⁷; Welch t = −59.42, p = 4.82 × 10⁻²³). Notice this AP-IN-1 node clocked #406 at 30.1024 s (~+200 ms slower than the Nov 22 node where #406/#407 clocked 29.9025 s) — yet PR #413 / #414 still beat 29.9025 s in raw unnormalized seconds (29.8578 s, −44.7 ms raw; 29.660 s normalized).
  2. 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-sided p = 0.0135 — just 0.0035 shy of 0.01, even though the other 11 runs averaged 3.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 under 3.28 (3.2797, 3.2777, 3.2776, 3.2779), bringing the full n=16 set cleanly to 3.27869 ± 0.00144, p = 0.00122 ≪ 0.01 (non-parametric Wilcoxon p = 0.00356).
  3. Power & energy (NVML 10 Hz separate run): Right after the timed runs finished, a dedicated 10 Hz nvidia-smi telemetry run clocked 29.872 s (+14.2 ms observer overhead, val_loss = 3.2788) at 5,385.2 W mean active 8-GPU power (673.2 W/GPU, peak 5,568.2 W, 1,882 MHz mean SM clock, 98.7% util, 70 °C max) — 44.66 Wh at the 16-run mean time (−0.38 Wh lower than #407's 45.04 Wh) and 34,309 MiB peak allocated VRAM (+0 MiB vs #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.

Two-panel Rank-0 CUPTI hardware analysis: Left panel proves Stage 3 Taper sampled dW eliminates nvjet_rqtst_144x128 dense dW GEMM (8.62 ms to 0.00 ms) and cuts _transpose_copy_kernel (7.49 ms to 1.81 ms), replaced by GROUP=4 sampled dW (2.30 ms) + _sample_transpose (1.50 ms) for −10.49 ms per 4 steps (−154.7 ms/run); Right panel shows remaining PR #413 kernel budget across Stage 1 (13.5 ms/st), Stage 2 (31.2 ms/st), and Stage 3 Taper (33.7 ms/st)

The hardware counters line up closely with our stopwatch ablations:

  • Stage 3 Taper S4b=4 (−154.7 ms CUPTI vs −165 ms stopwatch): Eliminating the dense full-vocab lm_head dW GEMM (8.615 ms → 0.000 ms per 4 steps) and shrinking _transpose_copy_kernel (7.490 ms → 1.811 ms, −5.679 ms) against the replacement GROUP=4 sampled dW GEMM (2.304 ms) + _sample_transpose (1.502 ms) yields −10.488 ms per 4 steps = −2.622 ms/step × 59 Taper steps = −154.7 ms.
  • Fused SSMax (+42 ms CUPTI vs +45 ms stopwatch): _qk_norm_rope_forward_kernel grew by just +2 µs/step, and _qkv_norm_rope_pack_fp8_backward_kernel grew by +33–48 µs/step (~+42 ms across 1,049 steps).

And Panel B points straight to the four biggest remaining targets if we want to push toward sub-29.5 s next:

Four-card roadmap showing where the next half-second lives from Rank-0 CUPTI traces of PR #413 on 8×H100: 1. Stage-3 Forward LM Head (~6.6 ms/step: Fwd logit GEMM 2.51 ms, CPLM CE LUT 1.63 ms, Exact dX GEMM ~2.5 ms); 2. Multi-GPU NCCL Comms (4.6 ms/step: Sparse n-gram all_to_all 1.18 ms/call, ReduceScatter + AllGather overlap); 3. G3 Dense & MoE Gluon (4.4–5.0 ms/step); 4. FlashAttention-3 (4.4–4.5 ms/step)

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):
  • Compute & discipline: Built with Google Antigravity and parallel Gemini agents for kernel authoring, 1×H100 multi-seed screening ($7.31 on RunPod EUR-IS-3), 8×H100 SXM5 diagnostics + N=16 interleaved runs + separate 10 Hz NVML + Rank-0 CUPTI profiling (~$110 on 8×H100, RunPod AP-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 #414 were recorded from our ablation checkout (d59fdd0) with SSMAX_ENABLED=1 S3_SAMPLED_HEAD_WG=4 SCHEDULE_GROWTH_STEPS=48 (all other experimental flags off); clean commit 894b331 (#413) strips the unused disabled modules and makes that exact configuration the default.
  • Credit:
    • #409 by @FeSens (Mask-Aware Softmax Scaling): Centered Mask-Aware SSMax (+42 per-head slopes), ported and fused into #406's Triton qkv_rope.py (~33% of our speedup / −80 ms net).
    • #371 (@romeerp) / #382 (@krishaab): original sampled lm_head dW formulation (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 the modded-nanogpt community (@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⁻¹⁵):

Visual walkthrough showing why 1-in-4 row sampling is strictly unbiased: four staggered phases (offset 0, 1, 2, 3) each pick every 4th row with weight 4×, so averaging across all 4 phases recovers every row with exact weight 1× (max error 3.5e-15), while negative target spikes are always added 100% exactly
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:

Four-row step-by-step array diagram of Mask-Aware log(N_vis) on a 16-token packed stream with seqlens = [0, 7, 16]: Row 1 splits Doc 1 (7 tokens) and Doc 2 (9 tokens); Row 2 resets pos from 1..7 and 1..9; Row 3 caps by window_size and centers via log(min(pos, window_size)) − 5.5; Row 4 scales each attention head's query q by τ = max(0.25, 1 + s_h · log_n)
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