Skip to content

qwen4_exp: land the 2026-08-31 long-context TTFT campaign (QSA tensor cores, mHC grid fix, MoE CTA striding) - #68

Merged
AzeezIsh merged 41 commits into
mainfrom
perf/qwen4exp-ttft-campaign
Sep 26, 2026
Merged

AzeezIsh merged 41 commits into
mainfrom
perf/qwen4exp-ttft-campaign

Conversation

@AzeezIsh

@AzeezIsh AzeezIsh commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Lands the Flash-Next (qwen4_exp) long-context TTFT campaign that had lived only on reiner (wt-q4e, perf/moe-transpose-allowlist, last commit 2026-09-01). The untouched original is on backup/qwen4exp-ttft-campaign-2026-09-01.

Result (GB10, nvidia/Qwen3.8-Flash-Next-NVFP4)

Cold TTFT, main66 (5b07b953) vs this branch. Jobs 239 and 263; util 0.88, max-seq 34000, prefill chunk 16384, prefix caching off. Each cell is the client median of 7, except 31.5k, which is the server TTFT= median of 3.

prompt main66 this PR, before TC2 default (c8bbd90f8) this PR (TC2 default)
~160 tok 0.866 s 0.332 s —
~2.6k 3.98 s 1.766 s 1.705 s
~10.2k 19.40 s 7.42 s 6.51 s
31.5k 92.24 s 24.36 s 20.97 s (4.4x)

What is in it

Default-on changes, near-identical output:

  • a QSA scorer that replays the reference reduction DAG in one thread (qsa_score_rows_exact);
  • head-grouped prefill attention (_g);
  • butterfly / vector-load / shift / pipeline micro-wins;
  • GPU prefill top-k;
  • skipping the dense prefill pass that QSA overwrites;
  • mHC collapse routed by machine fill: split-K via cuBLASLt for the skinny down/inject GEMMs, which cuts the prefill fixed cost from 143 to 22 ms;
  • MoE prefill m-tiles strided instead of launching ~1 M no-op CTAs;
  • the MoE transpose orchestrator extended to qwen4_exp.

Also default-on:

  • ATLAS_GDN_PIPE (762d3bbe6). Output-identical on Flash-Next (job 243) and on the 27B (job 252: ppl 0.000 %, JSD 0).
  • ATLAS_QSA_ATTN_TC2 (7747b77b3), NVIDIA only, through qsa_attn_tc2_enabled().
    • Evidence (TC2 alone, jobs 258/263): dense ppl 0.000 %, above-bound −0.019 %, needles 12/12, and the TTFT column above.
    • ATLAS_QSA_ATTN_TC2=0 restores the exact grouped kernel. An explicit ATLAS_QSA_ATTN_TC / L8 opt-in keeps its own kernel.
    • A once-per-process INFO line names the variant that dispatched.
  • ATLAS_QSA_SCORE_TC stays opt-in: it costs +0.222 % ppl for ~0.8 s (job 258).

Correctness fixes:

  • 1ea4e20ca, the MoE prefill grid. 9ca70af11 handed a shortened m-tile grid to every MoE launch, but only the two _t_k64 kernels stride. Every untransposed / m128 / fp4 / e8m0 / FP8-down kernel silently dropped hot experts' rows. With ATLAS_MOE_TRANSPOSE=0 that showed as dense ppl +14.9 % and above-bound +174 % (job 267). HIP targets that never run the transpose pass would have produced wrong output.
  • --gdn-fused-norm hard-coded SiLU where qwen4_exp needs sigmoid.
  • A BC audit of the acc_s sites.

Numerics (honest version)

  • Near-identical, not bit-identical: dense-region ppl is +0.036 % vs main66 and above-bound −0.014 % (8 × 12k windows).
    • The per-commit bisect (jobs 259/264) finds two effects that cancel: the MoE transpose (cfc6dae8e) at +0.52 %, and the mHC routing (379d741e0) at about −0.48 %.
    • On the fixed head with the same binary, the transposed MoE path reads +0.74 % dense vs the untransposed path (job 269 F vs F0). That precision question is tracked on [job] Qwen3.8-Flash-Next: long-context cold prefill to SGLang parity (stage 1 = #68) #74 and does not block this PR.
  • Long greedy generations diverge from main (top-1 46.9 %, job 251). Any reassociation diverges QSA's chaotic top-k, so the gates are ppl, needles and the task-level ST leg, not greedy identity.
  • Job 269: the MoE fix leaves the default path byte-identical to the pre-fix head (greedy hashes and ppl), and the ATLAS_MOE_TRANSPOSE=0 escape hatch is sane again.
  • Job 272 (merge-train tree):
    • defaults reproduce job 258's TC2 arm exactly (0/8 windows differ, log tc2);
    • TC2=0 reproduces job 269's exact arm bit-for-bit (log grouped);
    • the new unit test passes on GB10.

Memory

This PR's mHC split dispatcher (hc_pre_split) looks kernels up on every call. kernel_audit::record appended an unbounded row for every lookup, which made this PR the top consumer of per-step heap growth under the recipe profile (job 273 jemalloc profile: 51 % of growth). #82 fixes that generically, together with a pre-existing xgrammar leak, and it lands in the same merge train.

Merge gate (maintainer, 2026-09-26)

This PR merges with #78, #67, #82 and #83 as one train. The combined tree is 53f4a3d3a.

  • ST-995 (job 280): PASS, 84.72 / 84.68 against bars of 82.72 / 81.65. TC2 was engaged, and RssAnon stayed flat at ~1.76 GB over all 995 requests.
    • The harness is deterministic for a fixed tree: repeat runs gave 83.52 three times, 83.22 twice and 85.83 twice.
    • Across trees, earlier Flash-Next gate runs on this box scored 85.73–86.03 (job 225 was 85.73 / 85.96). A 1-point gap between trees can't be resolved at n=995, so this is not attributed.
    • Per-item responses are now kept (responses.jsonl), so later arms can be paired against this run with bfcl_paired.py (exact McNemar).
  • Agentic perf leg (job 298): VALID. 1007 of 1007 turns, 0 failed, 0 missing, 89 min.
    • TTFT median 1.16 s, p99 2.76 s; TPOT median 63 ms; score 0.4899.
    • Server: 0 KV-exhausted and 0 errors; 98 % warm prefix hits.
    • The compliance checker's all_turns_observed fails, but that's a checker defect: it compares observed (capped at the 1006 scorable turns) with issued (1007).
  • MoE support-matrix check (jobs 306 → 346).
  • Merged in the GB10 train (main 1ab38536b). The tree is identical to the job-346 build.
  • Release build (all targets), unit tests on GB10, and job 274's memory and [job] GB10: raise the Atlas tensor-core GEMM ceiling (29-39 vs cuBLAS 75-206 TFLOP/s) #71 validations.
  • Follow-up, not blocking: a task-level A/B of the TC2 default, ATLAS_QSA_ATTN_TC2=0 on the same tree, paired per item against job 280 (job 315).

🤖 Generated with Devin

claude and others added 30 commits September 25, 2026 02:07
… tier automatically

Cold TTFT on qwen4_exp (GB10, Qwen3.8-Flash-Next NVFP4), fitted over
60..2800 tokens:

    before   TTFT = 0.950 s + ctx/692 tok/s
    after    TTFT = 0.444 s + ctx/1290 tok/s

i.e. the fixed term halves and the marginal rate nearly doubles; TTFT at
2800 tokens goes 4.61 s -> 2.63 s, and at 60 tokens 1.00 s -> 0.53 s.

Three defects, all of them silent:

1. Qwen3SsmLayer never overrode the MoE transpose trait methods, whose
   defaults are Ok(()). qwen4_exp is 36 gated-delta-net + 12 attention
   layers and ALL 48 carry a 512-expert MoE block, so the factory pass
   built the _t tables for 12 layers and skipped 36 without a log line.
   nsys confirmed it: the transposed kernels ran exactly 24 gate_up +
   24 down (= 12 layers x 2) while the untransposed
   moe_w4a16_grouped_gemm_ptrtable still took 216 launches and 38% of
   GPU time. This is the bulk of the win.

2. The factory pass was gated on a hardcoded allowlist of three
   model_type strings, so every other MoE model silently skipped it.
   Replaced with a capability check (config.num_experts > 0).

3. unified_layout/hybrid_layout were read independently from env at
   MoeLayer construction, so operator intent could disagree with the
   tier that actually ran. With both set on a box where hybrid does not
   fit, the pass ran UNIFIED -- freeing the [N,K/2] originals -- while
   use_t_layout_for_decode() still returned false, because its
   !self.hybrid_layout term read the env flag. Decode then fell through
   to the originals arm and dereferenced freed device memory. The flags
   are now DERIVED in transpose_for_prefill_unified_inner from the
   branch that runs, so they cannot disagree.

Tier selection is now automatic and ordered best-decode-first (hybrid,
full, gate_up+scratch, then unified as the memory-neutral last resort),
logged as one line with the full arithmetic. There is deliberately no
env var to turn this ON; ATLAS_MOE_TRANSPOSE=0 is an escape hatch to
turn it OFF, matching ATLAS_MOE_PREFILL_COPIES=0.

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit 9807337)
hc_pre_down was 89.3 ms and 19.4% of a 60-token prefill (nsys 2026-08-30),
second only to the MoE gate_up GEMM. It is one block per token, and every
warp re-read that token normed vector -- hc_dim floats, 40 KB at
hc_dim=10240 -- once per down_w row. At rank=320 that is the dominant
traffic term:

    down_w   T x rank x 20 KB = 393 MB
    nx       T x rank x 40 KB = 786 MB   <- dominant

Staging nx in shared drops it to one read per block (T x 40 KB = 2 MB),
a 3.0x cut in total traffic.

Measured, cold TTFT fitted over 60..2800 tokens:

    before   TTFT = 0.444 s + ctx/1290 tok/s
    after    TTFT = 0.406 s + ctx/1277 tok/s

The fixed term moves 444 -> 406 ms, well short of what a 3x traffic cut
should buy. 40 KB of shared caps occupancy at one block per SM, so the
kernel trades traffic for parallelism and lands latency-bound instead.
The principled fix is a real tiled GEMM -- tile hc_dim so the shared
footprint is small enough to keep several blocks resident, and tile tokens
so each weight row is reused -- which models at ~12x less traffic than the
original without the occupancy cost. Recorded rather than attempted here.

A first attempt tiled TOKENS only (8 per block). That cut just the 393 MB
weight term, so traffic fell 29% and wall time 6%; the nx term was left
untouched and still dominated. Reverted in favour of this.

BITWISE SAFE: each lane still walks i = lane, lane+32, ... over the full
hc_dim with the same shfl reduction, so the FMA sequence for every (t, r)
is unchanged -- only where the operand is read from moved. Greedy sanity
set is unchanged at 7/8 (the miss is a verbose answer truncated at
max_tokens=48, identical before and after).

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit 1e62188)
hc_pre_gemm carves five sub-buffers out of one scratch region. Their raw
offsets are not 16-byte aligned for all T: inj_pre is preceded by
lay * hc_mult * 2 = lay * 8 bytes, which is only 8-byte aligned when lay
is odd, so up_wt starts 8 bytes off. The path hands up_wt to the
tensor-core dense_gemm_bf16_pipelined, which issues 128-bit loads, and a
sub-16B start faults with CUDA_ERROR_MISALIGNED_ADDRESS (716).

That error is STICKY -- the context is destroyed and every later driver
call in the process returns the same status, so the server stops serving
entirely rather than failing one request:

    kernel launch failed: CUDA_ERROR_MISALIGNED_ADDRESS (716)
      (grid=[1024,2,1], block=[16,16,1])
    ... the CUDA context is destroyed. Errors of this class are sticky.

Latent today because the path is gated on T > 64 and T is normally the
even prefill chunk, but any odd T in 65..2047 reaches it. Found by
lowering that gate experimentally; the gate is restored (see below), so
this commit is the fix on its own.

No extra allocation is needed for the rounding. sizes.rs sizes the region
with ts = min(m, 2048) while the runtime offsets use lay = min(T, 2048)
<= ts, so below the slab there is already megabytes of headroom and at
T = ts the four roundings add at most 45 B. Padding it explicitly was
measured ~6% SLOWER at ctx 700 -- it shifts every later buffer in the
arena, and the alignment of those downstream allocations matters more
than the slack does.

NEGATIVE RESULT, recorded so it is not retried: the T <= 64 threshold
that sends short prefills to the hand-rolled hc_pre_split path rather
than this GEMM looks wrong -- the comment justifies it for decode, where
grid=[T] means grid=[1], and a 60-token PREFILL also has T <= 64 while
hc_pre_down + hc_pre_finish measured 143 ms, 31% of that prefill. It is
not wrong. Lowering it to 8 made cold TTFT WORSE at ctx 120
(0.555 -> 0.625 s, +13%, run-to-run variance <2%). The split path beats
the tensor-core GEMM at these shapes. Threshold left at 64.

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit b970388)
hc_pre_down stages the whole 40 KB normed row in shared and makes one
pass. That is right at T=1 -- decode needs a single pass and pays no
barriers -- but wrong at prefill widths, where it re-reads the 6.55 MB
down_w once per token: 393 MB at T=60, measured 859 GB/s against an
L2-resident weight set, i.e. ~85% of L2 peak. It was L2-bandwidth-bound.

hc_pre_down_tiled tiles tokens (HC_TT=8) so each weight row is amortised,
and chunks hc_dim (HC_CH=512) so the staged nx footprint is
HC_TT x HC_CH x 4 B rather than HC_TT x 40 KB. Both dimensions have to
move together: tiling tokens ALONE was measured and gave only -6%,
because TT x 40 KB overflows L1 and nx starts missing to L2, cancelling
the weight saving.

Dispatch is on T, because neither kernel wins everywhere (nsys, 87-token
prefill chunked 64+23):

    prefill hc_pre_down   89.2 ms -> 33.0 ms   prefill window 491.5 -> 438.3
    decode  hc_pre_down   28.8 ms -> 65.0 ms   679 calls, 2.3x WORSE

The decode regression is hc_dim/HC_CH = 20 chunks = 40 barriers for work
that needs one pass, so T <= HC_TT keeps the single-pass kernel.

End to end, fixed-prompt streaming TTFT, 7 reps per point:

    words   single-pass    tiled     delta
       40      0.5740s   0.5380s     -6.3%
       90      0.6210s   0.5990s     -3.5%
      300      0.8200s   0.7930s     -3.3%
                              aggregate -4.2%

Same direction at all three sizes. Ranges overlap, so no single point is
conclusive on its own; the sign consistency plus the independent nsys
prediction (-53 ms of a ~490 ms prefill, diluted by fixed overhead) is
what carries it. TPOT 57.71 ms against 57.96 ms baseline -- unchanged.

MEASUREMENT NOTE. This nearly got discarded twice. ttft_curve.py
recalibrates its filler per run, so A/B points land at different
prompt_tokens (116 vs 125) and the difference vanished into that jitter;
a fixed-word-count harness read the same change as -11%. Neither was
right. For A/B on this engine use a FIXED prompt and streaming TTFT
(scripts/fixttft.py), and do not compare across instruments -- they
disagree by ~25 ms on an identical build.

BITWISE IDENTICAL: for every (t, r) a lane still walks
i = lane, lane+32, ... in increasing order with the same shfl reduction.
Chunks are contiguous, in order, and HC_CH is a multiple of 32, so
chunking cannot reorder a lane walk. Only the order in which independent
(t, r) pairs are visited changed. Greedy sanity set unchanged at 7/8.

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit 94ba4fd)
… probe

`bf16_gemm_act_weight_t` takes a row-major `[N,K]` weight, so a caller holding
`[K,N]` has to materialise the transpose first. The mHC collapse was doing
exactly that: `hc_transpose_bf16` staged a 6.55 MB copy of `up_w` on every one
of its 97 call sites, 9.0 ms of a 422 ms prefill window, purely to satisfy the
NT tile kernel.

cuBLASLt does not need it -- `op_a` selects the layout -- so factor the body out
and add the `opN` twin. A row-major `[K,N]` weight IS a column-major `(N,K)`
matrix with `ld = N`, so only the A layout and the op change; compute type,
accumulation width and output layout are identical.

`available()` exists because the choice is a WEIGHT LAYOUT, made before any
GEMM runs. A per-call `Result` cannot express it: by the time the call fails,
the transpose has already been skipped.

(cherry picked from commit 43db65f)
…thing gate

nsys over the request window of a 118-token prompt (the whole-session kernel
summary is useless here -- it is 61% load-time moe_transpose_u8_batched).
dense_gemm_bf16_pipelined was 103.5 ms of a 483 ms window, and splitting it by
GRID DIMENSION shows why:

  projection    M      N      K     grid     us/call    n    total
  up           96  10240    320   80x1x1        43.7   99   4.3 ms
  down         96    320  10240    3x1x1       374.5   97  36.3 ms
  inject       96      4  10240    1x1x1       409.4   96  39.3 ms

up and down are the SAME 96x320x10240 MAC count and differ 8.6x, and inject
does 80x less arithmetic than down in more time. No arithmetic story fits; the
only variable is the grid. gemm_raw emits a 128x128 output tile, so N=320 and
N=4 are three CTAs and one CTA of a 48-SM part.

So route per projection on whether the tile grid can cover the part -- the rule
qwen3_ssm::kernel_select already uses -- and let cuBLASLt pick split-K for the
skinny ones. It does: down lands on nvjet_..._splitK at grid 40x1x3 (4.05 ms,
9x) and inject on a cutlass wmma at grid 3x1x23 (0.65 ms, 60x). 75.6 ms -> 4.7.

up now goes to the opN entry point, off up_w's stored [rank, hc_dim] directly,
which deletes hc_transpose_bf16 (9.0 ms). The scratch region still reserves
up_wt for the fallback arm: shrinking it would shift every later buffer in the
shared arena, and that measured 6% SLOWER when tried before.

HC_DECODE_MAX_T 64 -> 8. A prefill is chunked (96 + tail), so this gate decides
the TAIL: a 118-token prompt ran its 22-token tail on the hand-rolled split
kernels for 27.7 ms. Lowering it to 8 was measured as a 13% REGRESSION before
(TTFT_GAP.md 6b) and the conclusion drawn -- "the hand-rolled path beats the
tensor-core GEMM at these shapes" -- was wrong: that experiment moved all three
projections onto the collapse at once, including the two starved ones. With
those routed the premise of the split path (grid=[T] means grid=[1] at decode)
holds again, and 8 covers exactly the shapes it was written for: T=1 decode and
T=2/3/4 MTP verify.

Measured, scripts/fixttft.py, same binary pair, 7 reps:

  ctx ~124   0.5435 s -> 0.4540 s   (-16.5%)
  ctx ~600              0.7191 s

vs vLLM interpolated at the same token count: 1.87x -> 1.56x. sanity.py 7/8,
the same single miss as baseline -- and those prompts now exercise the collapse
rather than the split path, so they check the changed arithmetic.

(cherry picked from commit 70d270d)
The QSA prefill selection copies block scores to the host, sorts each row and
copies the list back. nsys cannot see what that costs, because while it runs no
kernel is running -- it is a hole in the timeline. Measuring the GPU IDLE gaps
instead of the kernels, on one 2769-token prefill:

  qsa_score_rows -> qsa_prefill_attn    148.08 ms    24 gaps    6170 us each

148 ms, 6.1% of a 2408 ms window, and the fifth-largest item in the whole
prefill. It is not the transfer (488 KB); it is the sorting, and it grows like
layers x slabs x rows x complete log complete. At 32k that is 12 layers x 15
slabs x 2048 rows x ~2000-element sorts, of the order of 1e10 comparisons on
one core.

Two changes, neither of which moves an output bit:

  * Only the first `topk` of the ordering is ever read, so partition with
    `select_nth_unstable_by` and sort only the prefix. The comparator is a
    TOTAL order -- score descending, ties broken by index, so no two distinct
    elements compare Equal -- which makes the partition point unique and
    `order[..topk]` exactly the prefix the full sort produced, in the same
    order. At 11k that is ~690 elements sorted down to 128.
  * The rows are independent, so fan them over the cores with
    `std::thread::scope` (already used in this crate's mistral loader; no new
    dependency). Each thread writes a disjoint slice of `host_lists`, so the
    bytes do not depend on the split or on completion order. Below 64 rows the
    spawn cost dominates and it stays serial.

The order has to be reproduced exactly, not just the selected SET:
`qsa_prefill_attn` walks the list warp-striped (`t = warp; t < n_tok; t += 8`)
and its online softmax accumulates in that order, so permuting the list
reassociates the sum.

Measured, scripts/curve.py, prefix caching off, max-seq-len 34000, 3 reps,
scored against vLLM's measured points interpolated piecewise-linearly:

  ctx    11066   17.222 s -> 12.190 s   3.06x -> 2.16x
  ctx     2854    2.485 s ->  2.327 s   1.74x -> 1.63x
  ctx      714    0.757 s ->  0.754 s   unchanged
  ctx      116    0.438 s ->  0.442 s   unchanged (QSA does not fire below the
                                        2048 indexer budget)

sanity.py 7/8, the same single miss as baseline.

This also corrects a note in the working repo: upstream PR #820 (qsa prefill)
was written off as "does not transfer, our prefill has no host round-trip".
`qsa_select.rs` is exactly that host round-trip.

(cherry picked from commit 8d4bb15)
…l attention

nsys on an 11066-token prefill: `qsa_prefill_attn` was 3702 ms, 32.6% of a
12.3 s window and three times the next kernel. It is not arithmetic -- the
selected K/V for a layer is a few MB. It is L2 traffic: grid=[rows, nq] gives
one block per (row, q head), and with nq=24 over nkv=2 every K/V byte is read
TWELVE times, ~51 GB per launch at ~1 TB/s.

The redundancy is structural and unnecessary: the selected block list is
indexed by ROW (`lists + r * topk`), not by head, so every q head of a row
attends over the identical key set. One block can serve a group of heads and
read each K/V row once.

`qsa_prefill_attn_g` does that with QSA_PA_G = 4. Bit-identical: each
(row, head) still walks the same warp-striped `t` sequence in the same order,
keeps its own online-softmax state, and merges across the same 8 warps in the
same order. Only the loads are shared, and K/V are converted to float before
use exactly as before. It also gives each warp four independent dot-product
chains per loaded key instead of one.

G is bounded by the merge buffer, `[8][G][hd]` floats: at hd=128, G=12 is 49 KB
and busts the 48 KB block limit, G=4 is 16 KB. `qsa_prefill_attn_grouped_ok`
checks that, plus `nq % G == 0` and `(nq / nkv) % G == 0` so every head in a
group maps to the same kv head -- the kernel derives `kvh` from the group's
first head. Geometries that fail any of those keep the one-head kernel, which
also remains what `qsa_tests_prefill.rs` checks against the CPU reference.

Verified in the PTX rather than trusting the build: `qsa_prefill_attn_g` is
present with 14 params and no `.local` declarations, i.e. no register spill.

Measured, scripts/curve.py, prefix caching off, max-seq-len 34000, 3 reps:

  ctx 11061   12.190 s -> 10.927 s   2.16x -> 1.94x
  ctx  2851    2.327 s ->  2.217 s   1.63x -> 1.55x
  ctx   711    0.754 s ->  0.752 s   unchanged
  ctx   114    0.442 s ->  0.441 s   unchanged (QSA does not fire below the
                                      2048 indexer budget)

sanity.py 7/8, the same single miss as baseline.

(cherry picked from commit 0a5853f)
…nel bitwise

Two follow-ups to 8d4bb15 and 0a5853f.

The score D2H landed in a `Vec<u8>` and was then converted with
`chunks_exact(4).map(from_le_bytes).collect()`, which walked every score a
second time and allocated the matrix twice. That matrix is `rows x stride`: at
30k context it is 2048 x 7500 = 15.4M floats PER SLAB, and a prefill runs ~14
slabs x 12 layers of them. Receiving straight into an `f32` buffer removes the
pass entirely -- `u8` has no alignment requirement and the allocation is
already 4-aligned, so the copy writes the same bytes to the same place. Both
sides are little-endian, which the `from_le_bytes` it replaces also assumed; a
`const` assertion now turns that into a build error instead of silent garbage.

The second change is a test, not a speedup. `qsa_prefill_attn_g`'s whole claim
is BIT-identity with `qsa_prefill_attn` -- same warp-striped `t` order, same
per-head online-softmax state, same cross-warp merge -- and the existing
coverage is a cosine check against a CPU reference, which would not catch a
reassociation that quietly costs the last mantissa bits. The new test runs both
kernels on the same inputs and requires every output element to match bit for
bit:

    qsa_prefill_attn_g == qsa_prefill_attn on 30720 elements ... ok
    qsa_prefill_attn vs CPU: worst cos = 0.999998230 ... ok

It also asserts `qsa_prefill_attn_grouped_ok` accepts the test geometry, so the
test cannot silently degrade into comparing the fallback with itself.

(cherry picked from commit 40060fd)
…er sort

Even after 8d4bb15 made the prefill top-k O(n) and multi-threaded, the gap
`qsa_score_rows -> qsa_prefill_attn_g` was still the LARGEST single item in a
30k prefill: nsys measured 8777 ms of dead GPU over 177 gaps, 49.6 ms each,
20% of a 43 s window.

The remaining cost was the comparator, not the algorithm. Selecting over
`complete` ~= 7400 elements per row costs ~20k comparisons, each of which
indexed back into the score matrix TWICE through a closure with bounds checks,
for 2048 rows per slab.

Packing `(score DESCENDING, index ASCENDING)` into one `u64` makes each
comparison a plain integer compare on a value already in a register. The float
goes through the standard monotone `f32 -> u32` map (flip the sign bit for
positives, invert every bit for negatives), inverted for descending order, with
the index in the low 32 bits as the tie-break.

That has to reproduce the old comparator EXACTLY -- not just the selected set
but its order, because `qsa_prefill_attn` walks the list warp-striped and its
online softmax accumulates in list order. A differential check over 500 random
values found exactly one disagreement: **-0.0**. It and +0.0 have different bit
patterns but compare Equal in IEEE, so the comparator fell through to the index
while the bit map ordered them. `acc` here is a sum of `fmaxf(dot, 0.0f)` scaled
by a positive, so -0.0 should be unreachable -- but that is a bad reason to
leave a selection subtly wrong, so the key canonicalises zero first.
`rank_key_tests::matches_the_comparator_it_replaces` now asserts the two orders
agree element for element over 510 values including both zeros and repeats.

The packed key is also strictly better defined than what it replaces: the old
`partial_cmp(..).unwrap_or(Equal)` is not a total order in the presence of NaN,
which makes `sort_by`'s output unspecified. Every distinct element now has a
distinct key.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps,
scored on the scheduler's own TTFT:

  ctx 30239   40.044 s -> 38.128 s   2.55x -> 2.43x   (with 40060fd)
  ctx 11063   10.501 s -> 10.528 s   unchanged (the row count per slab is the
                                     same; the win is in `complete`, which
                                     grows with context)

sanity.py 7/8, the same single miss as baseline.

(cherry picked from commit f600b5b)
The selection ran on the HOST: copy the whole score matrix D2H, sort each row,
copy the list back. That is a full stream drain per attention layer per slab,
and no kernel-time profile can see it because while it runs no kernel is
running. Measuring GPU IDLE instead (scripts/gaps.py), on a 30k prefill:

  qsa_score_rows -> qsa_prefill_attn_g   7279 ms   179 gaps   40.7 ms each

19% of a 41.6 s window and the largest single item in it. 8d4bb15 and f600b5b
took the sorting itself from O(n log n) with a closure to an O(n) integer
partition on all cores, and it was STILL that; the residue is shipping
`rows x stride` floats (60.8 MB per slab at 30k) across the bus and touching
them again on the CPU. So stop shipping them.

`qsa_topk_rows`: one block per row, bitonic top-K over packed u64 keys. Keep a
running ascending array of the K best; for each chunk of K new keys, sort them
ascending, take `min(A[i], B[K-1-i])` (the K smallest of the union, and bitonic
by the standard result), then a bitonic merge restores order. K = 512 = the
block width, which also bounds the `topk` it can serve; anything wider keeps
the host path.

EXACTNESS, which matters because `qsa_prefill_attn` walks the list warp-striped
and its online softmax accumulates in list order, so a permutation reassociates
the sum. Each element becomes ONE u64 via the same `rank_key` map the host uses
(monotone f32->u32, inverted for descending, index in the low bits). The keys
are DISTINCT because the index is in them, so any correct selection-and-sort of
distinct integers has exactly one answer -- there is no floating-point
reassociation anywhere in the kernel to get wrong. `qsa_rank_key` canonicalises
zero for the same reason the Rust side does: -0.0 and +0.0 differ in bits but
compare Equal in IEEE.

Verified rather than argued. `qsa_topk_rows_matches_host_selection` runs the
kernel against the ORIGINAL f32 comparator (not the packed key, so it tests the
spec and would catch a bug in the packing too) on a geometry chosen to exercise
what a single-chunk test would not: `complete` ~= 1250 spans three 512-wide
chunks so the running-best merge runs twice, exact ties force the index
tie-break, and both +0.0 and -0.0 appear.

  qsa_topk_rows == host selection on 7 rows x 512 ... ok

PTX checked too (6 params, no `.local`), because a new `.cu` can pass the build
without compiling.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps,
scored on the scheduler's own TTFT:

  ctx 30238   38.128 s -> 34.961 s   2.43x -> 2.23x
  ctx 11064   10.528 s -> 10.205 s   1.87x -> 1.81x
  ctx  2856    2.040 s              unchanged

sanity.py 7/8, the same single miss as baseline.

(cherry picked from commit 2298c4e)
…ntirely

Step 8b of the paged prefill is an OVERWRITE: `qsa.prefill_select` rewrites
`attn_out` for every global row at or past `inert_bound` (= budget + ratio - 1
= 2051). Step 8 computes dense paged attention for the whole chunk first. When
a chunk STARTS past that bound, every row it computes is thrown away without
ever being read -- and it is the expensive kind of waste, because dense
attention cost grows with position and these are the late rows.

nsys, 29670-token prefill. The paged chunks start at 8196, 16392 and 24588, all
past 2051:

  grid          rows    n       ms    kept
  24x129x1      8196   12    291.9    rows < 2051 only (chunk 0, cache_skip)
  24x128x1      8192   24   2613.2    NONE
  24x80x1       5090   12   1369.0    NONE

3982 ms of a 41.6 s window, discarded.

Skipping is output-identical by construction: `prefill_select` writes
`[max(bound, seq_start), seq_start + num_tokens)`, which at `seq_start >= bound`
is every row of the chunk. Three guards, all narrowing -- QSA present and
covering the chunk, single-stream (8b refuses batched for this model), and the
TurboQuant output bookend inert, so the skip never has to reason about rotating
a buffer nobody wrote.

VERIFIED, not argued. Same binary pair, three ~12.6k-token prompts (chunk 0 =
8196 via cache_skip, chunk 1 = ~3.8k at seq_len_start 8196, which is exactly
where the skip applies), greedy, plus the top-5 logprobs of the first generated
token as a numeric fingerprint -- the text alone is a weak discriminator because
these prompts share a 30-word vocabulary and all answer the same way:

  seed 11  ' are' -0.002378  ' appear' -6.627378  ' is' -7.127378  ...
  seed 22  ' are' -0.003420  ' appear' -6.253420  ' is' -6.753420  ...
  seed 33  ' are' -0.002337  ' appear' -6.752337  ' is' -7.002337  ...

Identical to the last decimal with and without the skip, on all three.

The `ATLAS_OP_DUMP` "attn_out_pre_gate" dump moves after 8b. It has to (there is
nothing to read before 8b when the dense pass is skipped) but it was also wrong
where it was: for any row past the bound -- which the last row of a long prompt
always is -- it dumped the dense value that 8b then discarded, and compared it
against a vLLM dump taken after ITS selective attention. Post-8b is both the
value that survives and the 1:1 comparison the comment claims.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps,
scored on the scheduler's own TTFT:

  ctx 30236   34.961 s -> 30.699 s   2.23x -> 1.96x
  ctx 11065   10.205 s ->  9.844 s   1.81x -> 1.75x
  ctx  2852    2.040 s ->  1.989 s   1.43x -> 1.39x

sanity.py 7/8, the same single miss as baseline.

Not addressed here: chunk 0 goes through the cache-skip path with
`seq_len_start == 0`, so it straddles the bound and still computes rows
[2051, 8196) that 8b discards -- ~250 ms of the 291.9 ms above. Truncating that
one needs a partial row range rather than a whole-launch skip.

(cherry picked from commit fd9e1df)
Companion to fd9e1df, which skipped the dense pass for chunks that start past
`inert_bound`. This is the chunk that STRADDLES it: chunk 0 runs through the
cache-skip path at `seq_len_start == 0`, so step 8b overwrites rows
[2051, num_tokens) while the dense flash pass computed all of them. At an 8196
token chunk that is 8196 computed, 2051 kept.

Truncating is exactly correct here, not merely close: `flash_seq_len` is `n`,
`flash_batch` is 1, and k/v_contiguous hold only this chunk, so it is causal
self-attention over the chunk's own tokens and row `r` never reads a key past
`r`. Computing `[0, bound)` gives bit-identical output for the rows that
survive; the rows past it are overwritten by 8b either way. Cost goes as L^2, so
2051/8196 leaves ~6% of the launch.

Guards match the paged version: single-stream only (batched stacks sequences
into `flash_seq_len`, so truncating would cut one in half) and the TurboQuant
output bookend inert, so this never rotates rows nobody wrote.

VERIFIED against the same reference build and the same three ~12.6k-token
prompts as fd9e1df, on the top-5 logprobs of the first generated token:

  seed 11  ' are' -0.002378  ' appear' -6.627378  ' is' -7.127378  ...
  seed 22  ' are' -0.003420  ' appear' -6.253420  ' is' -6.753420  ...
  seed 33  ' are' -0.002337  ' appear' -6.752337  ' is' -7.002337  ...

Identical to the last decimal.

The `ATLAS_OP_DUMP` "attn_out_pre_gate" dump moves after 8b for the same reason
it did in paged.rs: the last row of a long prompt is past the bound, so the dump
was showing a dense value 8b then discarded, compared against a vLLM dump taken
after ITS selective attention.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps,
scored on the scheduler's own TTFT:

  ctx 11062    9.844 s -> 9.560 s   1.75x -> 1.70x
  ctx 30239   30.699 s -> 30.569 s  1.96x -> 1.95x
  ctx  2852    1.989 s ->  1.978 s  1.39x

The 11k figure is the honest one: chunk 0 is a fixed 8196 tokens, so the saving
is a constant ~280 ms that matters less the longer the prompt gets.

sanity.py 7/8, the same single miss as baseline.

(cherry picked from commit 365b3ad)
`qsa_score_rows` launched ONE 128-thread block per OUTPUT SCALAR. Summing its
actual launch grids over a 29670-token prefill: **1.397 BILLION blocks** across
the 12 full-attention layers, each computing `n_heads * hd` = 512 MACs and
paying four block-wide reductions for them.

That kernel measured 1.43 TFLOP in 4.860 s = **294 GFLOP/s**. The MoE grouped
GEMM in the same prefill does 142.7 TFLOP in 5.089 s = **28.0 TFLOP/s**. Same
GPU, same request, 95x apart -- which is arithmetic, not a limiter inference.

`qsa_score_rows_b` gives each block QSA_SR_B = 16 consecutive `b` values and
stages the row's `q` in shared memory once instead of re-reading it per output.
Block count drops 16x; the arithmetic does not change at all.

BIT-IDENTICAL, and that is a requirement rather than a nicety: these scores feed
a top-k, so a shifted score changes WHICH blocks are attended, not merely by how
much. Every output still contracts through the same `qsa_block_reduce_sum` over
the same 128 threads in the same tree, accumulates `fmaxf(dot, 0)` over `hh` in
the same order, and scales by the same `rsqrtf(hd)`. Staging `q` through shared
changes where a float is read from, never its value. Both branch conditions in
the tile loop are block-uniform, so every thread runs the same sequence of
`__syncthreads` inside the reduction.

Verified on the same three ~12.6k-token prompts and the same top-5 logprob
fingerprints used for fd9e1df and 365b3ad -- identical to the last decimal on
all three seeds. sanity.py 7/8, the same single miss as baseline.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps,
scored on the scheduler's own TTFT:

  ctx 30236   30.569 s -> 29.523 s   1.95x -> 1.88x
  ctx 11066    9.560 s ->  9.527 s
  ctx  2859    1.978 s ->  1.976 s

WHAT THIS SAYS ABOUT THE REST. A 16x cut in block count bought ~1.05 s of a
4.86 s kernel, so CTA overhead was roughly a fifth of it and the other four
fifths are the four block-wide reductions per output. Removing those means a
GEMM -- `S[r,h,b] = q[r,h,:] . k[b,:]` is `[rows*4, 128] x [128, n_blocks]`,
then relu and sum over `h` -- which reassociates the contraction and therefore
needs `kl_drift.py --precision-change`, not this commit's bit-identity
argument. That is the next step here, and it is a numerics change to block
selection, so it wants a real gate rather than a logprob spot-check.

(cherry picked from commit 8d595d5)
`qsa_score_rows_b` spends four block-wide reductions per output, and 8d595d5
measured those as ~4/5 of its cost. `qsa_score_rows_gemm` removes them: a CTA
owns an 8x32 tile of scores, stages that tile's `q` rows and `k` blocks in
shared once, and each thread contracts ONE score serially over `hd`. Same MACs,
no reduction machinery.

It works, and it is fast:

  ctx 30241   29.523 s -> 26.314 s   1.88x -> 1.68x  vs the vLLM reference
  ctx 11062    9.527 s ->  9.014 s   1.69x -> 1.60x

It is not wired up, because it fails the quality gate.

WHAT THE GATE FOUND. The `d` contraction becomes a sequential per-thread sum
instead of a block-wide tree, which reassociates it. `qsa_score_rows_gemm_
vs_reference_drift` measures the consequence directly: **4.2e-7 worst relative
drift, 44% of scores bit-exact** — ordinary FP32 reassociation over 128 terms.
The kernel is correct.

But these scores feed a top-k over thousands of blocks, and near-ties either
side of the 512th place flip, so the attended set genuinely changes:

  needle recall (lc_check.py)          12/12, unchanged
  kl_drift --precision-change          top-1 69.3%, mean JSD 2.0e-1,
                                       105 greedy flips at margin > 0.02

The project's acceptance bar for QSA is **>=98% top-1 agreement** against the
llama.cpp reference. 69.3% is not close. Note which instrument caught it:
needle recall passed cleanly, so retrieval alone would have shipped this — it
is necessary evidence, not sufficient.

Kept in-tree rather than deleted: the kernel and launcher stay, exercised by the
drift test, dispatch-disabled with the numbers recorded at the call site. If
someone runs the real quality gate (wikitext ppl + top-1 vs reference) and
decides a different-but-equal selection is acceptable, wiring it back is a
one-line change to the ladder.

Also adds the long-context gate this needed, which did not exist:

  scripts/lc_subset.py   captures greedy output + top-20 logprobs on prompts
                         PAST the 2051-token inert bound, with needles planted
                         at known depths (dense region / mid / tail / chunk
                         boundary). st_subset.py's prompts are short, so a
                         capture taken with it can be byte-identical while every
                         line of the selective-attention path is broken.
  scripts/lc_check.py    needle recall, and a diff against a baseline capture.
  scripts/lc_needles.py  a depth x length sweep for when recall is the metric
                         under test rather than a sanity check.

Random filler is not enough on its own: a prompt whose answer does not depend on
any particular block cannot detect a wrong choice of blocks. The needles are the
load-bearing part.

(cherry picked from commit 00178c1)
…l, 3.0 s

00178c1 built a tiled-GEMM scorer worth 3.2 s at 30k and rejected it: summing
`d` serially per thread is a different FP addition tree, and these scores feed a
top-k, so near-ties around the 512th block flip (4.2e-7 score drift -> 69.3%
top-1 agreement, against a >=98% bar). The conclusion drawn there was that
efficiency and bit-identity are in direct tension, because efficiency wants one
thread per output and one thread cannot run a 128-thread reduction.

That conclusion was wrong, and Qwen3.8-Max supplied the correction: bit-identity
does not require a 128-thread block-wide reduction, only the same FP addition
DAG. One thread can evaluate the reference's `__shfl_down_sync` tree locally.

`qsa_score_rows_exact` does exactly that. At blockDim.x = hd = 128 the reference
leaves, in lane 0 of each warp:

    b[i] = (x[i] + x[i+16]) + (x[i+8] + x[i+24])   i = 0..7
    c[i] = b[i] + b[i+4]                           i = 0..3
    e[i] = c[i] + c[i+2]                           i = 0..1
    p    = e[0] + e[1]

then thread 0 folds the four warp partials from 0.0f, and the caller folds
`fmaxf(dot, 0)` over `hh` from 0.0f. All of that is replayed in order, per
thread, with the same 8x32 tiling and shared staging the GEMM variant used —
and with every block-wide reduction and every `__syncthreads` gone.

`__fmul_rn`/`__fadd_rn` are load-bearing, not decoration: with plain `*` and `+`
nvcc contracts `q*k + t` into an FMA, which skips the product's rounding and
breaks identity. The reference cannot contract, because its addend comes from a
shuffle of the already-rounded product.

VERIFIED as bit-identity, not as "close": `qsa_score_rows_exact_is_bitwise_
identical` compares every score against `qsa_score_rows` and requires equal
BITS — 46412 scores, zero differences. A cosine or epsilon check would not
catch an FMA contraction. End-to-end, the three ~12.6k-token logprob
fingerprints are unchanged to the last decimal, and sanity.py is 7/8 as before.

Measured, scripts/curve2.py, prefix caching off, max-seq-len 34000, 3 reps:

  ctx 30244   29.523 s -> 26.484 s   1.88x -> 1.69x
  ctx 11062    9.527 s ->  9.052 s   1.69x -> 1.61x
  ctx  2850    1.976 s ->  1.951 s   1.38x -> 1.37x

That is 95% of the rejected GEMM's win (26.314 s) with none of its risk. The
GEMM kernel and its drift test stay in-tree, now clearly superseded: there is no
longer a reason to trade numerics for this speed.

(cherry picked from commit cbc2181)
`qsa_prefill_attn_g` reduced each dot with five `__shfl_down_sync` steps and
then a sixth `__shfl_sync(..., 0)` to broadcast lane 0 to the warp. The
butterfly form is bit-identical for lane 0 -- at every step the partner index is
the same (0^16 == 16, 0^8 == 8, 0^4 == 4, ...) so the additions and their order
are unchanged -- and it leaves the total in EVERY lane, which retires the
broadcast. Six shuffles per dot become five.

Bit-identity is policed, not assumed: `qsa_prefill_attn_g_matches_single_head_
bitwise` compares against `qsa_prefill_attn`, which still uses the down-shift
form, and it passes on all 30720 elements. The three ~12.6k-token logprob
fingerprints are unchanged.

  ctx 30237   26.484 s -> 26.201 s   1.69x -> 1.67x
  ctx 11066    9.052 s ->  8.978 s   1.61x -> 1.59x

~1%, which is about what one shuffle in six is worth in a kernel that is not
purely shuffle-bound. Taken because it is free; the kernel's real headroom needs
either ncu or a reassociating rewrite behind the perplexity gate.

(cherry picked from commit d78e1d8)
`qsa_prefill_attn_g`'s inner loop read `krow[lane*vec + e]` for e in 0..7, and
the same for V — sixteen scalar 2-byte loads per lane per key, on a loop that
runs ~2048 times per (row, head-group). Lane `l` wants elements
[l*vec, l*vec+vec), which is contiguous, and `off` is a multiple of `hd`, so at
vec == 8 that is a 16-byte aligned 16-byte span: one 128-bit load each for K and
V. Bit-identical — same bytes, same `(float)` widening, same order — and the
existing `qsa_prefill_attn_g_matches_single_head_bitwise` test confirms it on
all 30720 elements. The scalar path stays for other `vec`.

  ctx 30240   26.201 s -> 25.624 s   1.67x -> 1.63x
  ctx 11059    8.978 s ->  8.794 s   1.59x -> 1.56x

ALSO REVERTED HERE, as a measured negative worth recording. All 32 lanes compute
the same two `__expf` in that loop, because `dot` is broadcast and `m[g]` is
warp-uniform — 64 SFU ops per warp per key where 2 would do. Computing them once
in lane 0 and broadcasting is BIT-IDENTICAL and SLOWER: 26.201 s -> 26.846 s at
30k. The redundant SFU work hides under the rest of the loop; two extra shuffles
do not.

That, with d78e1d8's butterfly (one shuffle removed, -0.28 s), prices a shuffle
in this kernel at roughly 0.3 s and puts the five per dot at ~20% of it. So the
limiter is not bandwidth (a 4x K/V traffic cut in 0a5853f bought only 1.47x),
not SFU (above), and not principally shuffles. By elimination it is the load and
FMA stream, which is what this commit attacks and why it worked.

(cherry picked from commit fd4d7df)
Four integer divisions ran per lane per key in `qsa_prefill_attn_g`'s inner
loop -- `t / ratio`, `t % ratio`, `tok / block_size`, `tok % block_size` -- on a
loop that runs ~2048 times per (row, head-group). Both divisors are runtime
kernel arguments, so nvcc cannot strength-reduce them and emits a full division
sequence each time, which is tens of cycles against one for a shift.

`ratio` and `block_size` are powers of two in every shipped configuration (4 and
16). Decompose once before the loop and shift inside it; keep the divide as a
fallback so a non-power-of-two configuration stays correct rather than silently
wrong. Exact integer arithmetic either way, and
`qsa_prefill_attn_g_matches_single_head_bitwise` still passes on all 30720
elements -- the one-head kernel keeps the divides, so it remains an independent
reference.

  ctx 30238   25.624 s -> 24.916 s   1.63x -> 1.59x
  ctx 11064    8.794 s ->  8.611 s   1.56x -> 1.53x

Together with fd4d7df (vectorised loads) and d78e1d8 (butterfly), this kernel
has gone 26.484 -> 24.916 s of end-to-end 30k TTFT without moving a single
output bit.

(cherry picked from commit cf7bbae)
Three limiters have now been measured OUT of `qsa_prefill_attn_g`: K/V bandwidth
(a 4x traffic cut in 0a5853f bought only 1.47x), SFU (hoisting the redundant
per-lane `__expf` was bit-identical and SLOWER), and shuffles as the principal
cost (one removed is worth ~0.28 s of ~6.3 s). That leaves load latency, and
after fd4d7df there are exactly two loads per key to hide.

So issue key `t + QSA_PA_WARPS`'s K/V while key `t` is still being reduced. The
address computation is factored into `qsa_key_off` so the next key's offset can
be formed before the current key's data is touched, and the raw `uint4`s are
carried rather than the widened floats — 8 registers instead of 16, with the
bf16->float converts left next to their use.

The online softmax stays strictly sequential in `t`: only the loads move
earlier, no arithmetic is reordered. `qsa_prefill_attn_g_matches_single_head_
bitwise` passes on all 30720 elements and the three ~12.6k-token logprob
fingerprints are unchanged.

  ctx 30242   24.916 s -> 24.593 s   1.59x -> 1.57x
  ctx 11065    8.611 s ->  8.482 s   1.53x -> 1.51x

Across cbc2181, d78e1d8, fd4d7df, cf7bbae and this commit, 30k TTFT has gone
29.523 -> 24.593 s (1.88x -> 1.57x) and the kernel itself 7493 -> ~6000 ms,
without moving an output bit.

(cherry picked from commit a6bfe5d)
TTFT_GAP.md 19b priced `qsa_prefill_attn_g` against a "bandwidth-intensity
ceiling" of 5.1 TFLOP/s, and 19c used the same reasoning to price the split-head
restructure at under 10%. Both rested on the G=2 vs G=4 comparison, and that
comparison is CONFOUNDED: changing G moves K/V traffic and the register count
together (G=4 -> 125 registers -> 16 warps/SM; G=2 -> 80 -> 25.6). Its 2% net is
a bandwidth win cancelling an occupancy loss and cannot price either one.

This probe separates them. Masking the computed K/V offset with 0xFF00 collapses
the working set into a 128 KB window so every load hits cache, while every
instruction above still executes -- block_table and my_list are still read, the
index math is unchanged, registers and occupancy are untouched. Only WHICH bytes
are fetched changes. It produces wrong output, so it is an instrument and never a
candidate; it is off unless built with -DQSA_PA_PROBE_LOCALITY, the same shape as
the existing -DATLAS_FAST_SOFTMAX_EXP bisection hook that build.rs documents.

  ctx 31481   25.866 s -> 25.255 s

Making K/V traffic entirely free is worth 0.611 s (2.4%) of a ~6.1 s kernel. So
19b is refuted -- this kernel is not bandwidth-bound -- and the shared-K/V-staging
redesign is worth <= 0.6 s rather than the ~5 s 19a hoped for. 19c reached the
right verdict by the wrong route.

Also measured and NOT shipped, recorded in 22b: eliding the no-op accumulator
rescale. When the running max does not move, `scale` is `__expf(0.0f)`, exactly
1.0f, and `x*1.0f + y` is bitwise `fma`; the branch is warp-uniform and taken
~99.6% of 2048 keys, removing 32 of ~150 instructions per lane per warp-key.
Bit-identical (the one-head kernel keeps the unconditional rescale, and
`qsa_prefill_attn_g_matches_single_head_bitwise` passes on all 30720 elements)
and worth exactly nothing: 25.908 s vs 25.866 s, 125 registers and 0 spills
either way.

Free memory buys 2.4%; 24% fewer ALU ops buys 0%. With SFU, bulk shuffles, grid
shape and register-driven occupancy already excluded, the only model consistent
with all six is latency-bound at 16 of 64 warps -- which is also why the
instruction-count price on the "8 lanes per head" restructure should not be
trusted: that one shortens the reduction chain from 5 levels to 3.

(cherry picked from commit 59aece1)
TTFT_GAP.md 22 left one item with a measured basis -- the "8 lanes per head"
restructure, whose 11% instruction-count price should not have been trusted
because the instruction-count model had just failed to predict anything. This
builds it, and its opposite, and both lose.

qsa_prefill_attn_l8 splits each warp into four 8-lane groups; group `lane>>3`
owns one head and lane `lane&7` owns 32 contiguous elements of it. Since
__shfl_xor_sync with an offset below 8 never crosses a group, all four heads
reduce in the SAME three warp instructions: twenty shuffles per lane per warp-key
become three, and the chain goes from five levels to three. K/V traffic is
unchanged -- all four groups request the same 512-byte row in one instruction and
the coalescer merges it, so only the number of load INSTRUCTIONS rises, 2 -> 8.

  registers 125 -> 92, no spills
  shuffles/warp-key 20 -> 3, chain 5 deep -> 3
  ctx 31481   25.753 s -> 27.888 s   (+8.3%)

Correct, not broken: needle recall at ctx 11212, past the 2051 inert bound,
returns the planted code. Everything the latency model said to improve did
improve, and it still lost; the one thing that got worse was load-instruction
count. Kept in-tree behind ATLAS_QSA_ATTN_L8, dispatch-disabled, with the numbers
at the call site -- the disposition 16a used for the GEMM scorer, so the next
person does not rebuild it.

So the opposite trade was measured too. G=6 serves six heads from the same two
loads (33% fewer load instructions for the same work) and is BIT-IDENTICAL --
each head still walks the same warp-striped `t` sequence, keeps its own softmax
state, and merges across the same 8 warps in the same order, which
qsa_prefill_attn_g_matches_single_head_bitwise confirms. It needs 166 registers,
which puts ONE CTA on an SM instead of two:

  ctx 31481   25.753 s -> 28.702 s   (+11.4%)

Halving occupancy costs far more than a third of the loads gains. Reverted to
G=4; the l8 kernel and the corrected guard stay.

That guard is the one durable fix here. `qsa_prefill_attn_grouped_ok` capped the
merge buffer at 48 KB, but registry.rs already sets
CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES on any launch above 48 KB, so the
cap was self-imposed rather than a hardware limit. Raised to 96 KB.

Four experiments now bracket this kernel: free K/V traffic is worth -2.4%, 24%
fewer ALU ops is worth 0%, -85% shuffles at +4x loads is +8.3%, and -33% loads at
-50% occupancy is +11.4%. Registers per SM are 65536 over a 256-thread CTA, so
125 registers means 2 CTAs and 16 of 64 warps; every route to fewer registers
adds memory instructions and every route to fewer memory instructions costs
registers. This is a local optimum, and escaping it needs a different algorithm
rather than a different schedule.

(cherry picked from commit 384a19c)
TTFT_GAP.md 27a measured inferspark_prefill_64 at 30.1 TFLOP/s against
qsa_prefill_attn_g's 3.1 -- same box, same head_dim=256, same model, same
request. The four experiments in 22 and 23 bracketed the scalar kernel and found
a real local optimum; what none of them tried was tensor cores, which is where
the 9.7x was. 19b had priced this away with an arithmetic-intensity ceiling that
22a's locality probe already refuted, and that refutation was never carried back
to the conclusion it invalidated.

Derived from inferspark_prefill.cu's BR=32 arm rather than written fresh, so
every mma fragment index, the online softmax, the cp.async staging and the
documented SM121 ldmatrix workaround come from a kernel already correct on this
hardware. Four addressing sites change: Q rows become the row's q-heads rather
than tokens; the three K/V loads gather through the selection list; O strides by
head_dim inside one row. The causal mask, the sliding-window path and the causal
KV-block trim are DELETED rather than disabled -- every selected key is at or
below this row's position by construction, so they are dead by definition.

THE MAPPING IS NOT THE OBVIOUS ONE. The natural tensor-core shape is to tile
query ROWS and attend the union of their selections, which needs neighbouring
rows to agree. ATLAS_QSA_UNION_DIAG (added here, and kept -- it documents a
measured property) says they do not: the union over 16 adjacent rows is 4.7-5.3x
topk, over 64 rows 8.5-10.5x. A row-tiled kernel would compute ~5x the necessary
work. So hold the row fixed and tile the HEADS instead -- every q-head of a row
attends the identical selected set, the same property QSA_PA_G already exploits
-- and there is no union, no extra blocks and no semantic change.

  ctx 31481   24.917 s -> 22.128 s   (-11.2%, same binary, 3 reps)
  ctx 11066    8.164 s ->  7.387 s   1.45x -> 1.31x
  ctx 32242   25.636 s -> 22.704 s   1.54x -> 1.37x

GATED, AND IT IS NOT FREE. The PV GEMM reads P from shared as BF16 where the
scalar kernel kept FP32, so this reduces precision as well as reassociating.
scripts/ppl.py, corpus of 8 windows:

  below-bound ppl  8.10097 -> 8.10097   0.000%   dense, CONTROL
  above-bound ppl  4.60664 -> 4.62238  +0.342%   QSA, under test

The control being exactly unchanged is the part that matters: the change is
confined to the QSA path. lc_needles.py, a depth x length grid to 24k, is 21/21
(100%), so retrieval is intact and the 0.342% is diffuse numerical cost rather
than a lost block.

+0.342% is a real regression and is recorded as one. It is defensible because
the dense region of this same model ALREADY runs this kernel with BF16 P
(inferspark_prefill_64 on every row below 2051) -- this extends numerics the
tree already ships rather than introducing a new precision class -- and because
the reference being chased uses tensor-core attention with BF16 P too.

Ships OFF. ATLAS_QSA_ATTN_TC=1 enables it: a measurable quality change should be
a deliberate choice, not a silent default. M waste is 2.67x purely to keep the
inherited warp mapping; packing both kv heads into one BR=32 tile would cut it
to 1.33x, worth roughly another second, and is not attempted here.

(cherry picked from commit 589ab4b)
qsa_prefill_attn_tc puts one kv head's 12 q-heads in a BR=32 M tile and wastes
2.67x. This fills the second half: rows 0..11 are kv head 0's heads and rows
16..27 kv head 1's, which is exactly the split (warp_id & 1) * 16 already makes,
so the warp mapping is again untouched and the waste falls to 32/24 = 1.33x.

Both halves are the SAME row, so they share one block list and the two gathers
differ only by a constant kvh * head_dim inside each cached token -- the
double-fill is nearly free. BC drops 32 -> 16 to pay for the second K/V buffer:
smem_K[2][2][16][264] and smem_V[2][16][264] keep shared at 69,376 B, against
the 118 KB a second buffer at BC=32 would need, which would have cost a CTA per
SM and handed the padding win straight back.

FIXES A LATENT BUG on the way. `float acc_s[BC / 8][4]` was initialised by a
hardcoded `for (int i = 0; i < 4; i++)`. That is BC/8 and correct at BC=32; at
BC=16 the array has two entries and the loop writes two past the end. The file
already warns about BC=16 in two other places, so this was a known-shaped hazard
nobody had swept for.

  ctx 31481   22.128 s -> 21.578 s      (and 24.917 s on the scalar spine)
  ctx 11063    7.387 s ->  7.181 s      1.31x -> 1.27x
  ctx 32244   22.704 s -> 22.193 s      1.37x -> 1.34x

FASTER AND BETTER. scripts/ppl.py against the scalar baseline:

  below-bound ppl  8.10097 -> 8.10097    0.000%   dense, CONTROL
  above-bound ppl  4.60664 -> 4.59924   -0.161%   QSA, under test

So this is better than the SCALAR spine on perplexity, not merely better than
tc1's +0.342% -- which removes the one reservation 28b recorded. lc_needles.py
is 21/21 (100%) on a depth x length grid to 24k. The control being exactly
unchanged across tc1, tc2 and the baseline is what says these changes are
confined to the QSA path.

The plausible mechanism for the accuracy improvement is BC itself: at 16 the
online softmax rescales in smaller increments and each tile's f32 accumulator
sees less dynamic range, so the BF16 P rounding costs less than at BC=32. That
is a hypothesis; the measurement is the fact.

The gain is -0.55 s rather than the ~1.7 s the padding arithmetic alone
predicts, because halving BC doubles the KV iteration count and gives part of it
back.

Ships OFF, like tc1: ATLAS_QSA_ATTN_TC2=1. It is still a numerics change, and
the choice to take it should be deliberate.

(cherry picked from commit 5614cd6)
16a rejected qsa_score_rows_gemm on the project's >=98% top-1 agreement bar,
which it missed at 69.3%. 16b then built scripts/ppl.py explicitly because
"kl_drift measures agreement with our OWN previous build, and for the QSA scorer
that is the wrong question: the previous build's summation order is itself
arbitrary". The call site has said "dispatch-disabled until someone runs the real
quality gate" ever since. Nobody had. This wires it (ATLAS_QSA_SCORE_GEMM=1) and
runs it.

  below-bound ppl  8.10097 -> 8.10097   0.000%   dense, CONTROL
  above-bound ppl  4.59924 -> 4.60091  +0.036%   QSA, vs the tc2 build

So the change that scored 69.3% top-1 agreement costs 0.036% of the only
absolute measure available. 16a's verdict was not wrong about the number it
measured; the number does not track quality for this kernel, which is what
ppl.py's own docstring predicted. That pair -- 69.3% agreement against 0.036%
perplexity -- is the calibration to judge future QSA selection changes by.

The perplexity moving at all is also what proves the arm dispatched: had the _ok
guard silently rejected it, the figure would have been bit-identical to tc2.
This tree has shipped a silent fallback before (PR #296), so that check is not
ceremony.

IT STILL DOES NOT SHIP, for a different and simpler reason than the one on
record. The 3.2 s weighed against the risk in 16a was measured against the OLD
scorer; qsa_score_rows_exact has since taken that win BIT-IDENTICALLY and cut
the scorer to 924 ms. Against today's build the GEMM arm is:

  ctx 31481   21.590 s -> 21.529 s   (-0.06 s, inside run-to-run noise)

There is no speed left to trade for even a 0.036% regression. Kept wired and
default-off with both numbers at the call site, so the next reader inherits the
answer instead of the question.

(cherry picked from commit 297c109)
…lly costs

29a observed that tc2 is faster than tc1 only because it does less work: tc1 at
BC=32 achieved 14.3 TFLOP/s, tc2 at BC=16 only 8.4. tc3 keeps tc2's kv-head
packing (M waste 1.33x) and restores BC=32.

The blocker was shared memory, and the driver named it. At BC=32 with two kv
heads a double-buffered K is 67,584 B and the total 121,088 B, which JIT-fails
with CUDA_ERROR_INVALID_PTX: static shared per block caps at 101,376 B. This
file already documents that cap in its Gemma-4 note; I had read the line and not
applied it. Single-buffering K is 33,792 B and the total 87,296 B, which fits.
The __syncthreads() at the bottom of the loop makes overwriting the single
buffer safe -- every warp has finished reading smem_K in its QK pass by then.
K/compute overlap is the price; the V load still overlaps QK.

  five reps   tc2 21.676 s (spread 0.259)  ->  tc3 21.467 s (spread 0.092)

BC IS THE ACCURACY KNOB, NOT THE PACKING. scripts/ppl.py, above-bound:

  scalar _g   4.60664
  _tc    BC=32, 1 kv head, 2.67x waste   4.62238
  _tc2   BC=16, 2 kv heads, 1.33x waste  4.59924
  _tc3   BC=32, 2 kv heads, 1.33x waste  4.62238

tc3 and tc1 agree to the last digit despite differing in packing and M waste,
while tc2 -- which differs only in BC -- does not. So the kv-head packing is
numerically neutral, as it must be since it only fills unused M rows, and BC
alone moves the number. That is direct confirmation of 29a's guess: at BC=16 the
online softmax rescales in smaller increments and each tile's f32 accumulator
carries less dynamic range, so the BF16 P rounding costs less. below-bound ppl
is 8.10097 for every arm.

SO TC2 STAYS THE RECOMMENDATION. tc3 is 1.0% faster and 0.50 percentage points
worse: +0.342% against the scalar spine where tc2 is -0.161%. tc2 is the only
arm that beats the kernel it replaces on both axes, and trading a real accuracy
regression for 1% of TTFT is not a default. tc3 is kept behind
ATLAS_QSA_ATTN_TC3=1 with both numbers recorded, so anyone who wants that last
1% knows what it costs and that the cost is BC.

(cherry picked from commit 4e6ea7d)
qsa_score_rows_exact was the worst-performing kernel in a long-context prefill:
926 ms for 1.55 TFLOP = 1.67 TFLOP/s, against 26.6 for MoE and 30.1 for the
dense tensor-core attention on the same box. Its tile was swept in both
directions (31c) and moved 0.10 s, below the noise floor -- like the scalar
attention kernel before it, its time was in its INSTRUCTION CLASS, not its
schedule.

PRICED BEFORE BUILT. The stated objection was precision: a tensor-core scorer
needs BF16 Q where the reference uses F32, and 30a's "+0.036% for reassociation"
does not cover a perturbation ~1e4x larger. So the precision half was measured
on its own first -- QSA_SCORE_PROBE_BF16_Q (kept, ifdef, default off) rounds Q
inside the otherwise-exact scalar kernel, leaving the summation tree, the K
values and the ordering untouched:

  above-bound ppl  4.60664 (F32 Q)  ->  4.58049 (BF16 Q)

BF16 Q measures BETTER, not worse. block_keys was already BF16, so this makes
both operands the precision an MMA sees. That probe is what justified writing
this kernel.

THE KERNEL. One warp per indexer head (n_heads == 4 == warps), each computing a
full [BM=16, BN=32] tile with mma.sync.m16n8k16.row.col.f32.bf16.bf16.f32, then
a shared reduction summing the heads IN HEAD ORDER to match the reference's
acc = fadd(acc, fmaxf(dot, 0)) over h = 0..3. ReLU per head before the sum, and
the b >= complete mask at write time, both as the reference does. A/B fragments
are loaded manually because ldmatrix and ldmatrix.trans both return wrong
results on GB10, which inferspark_prefill.cu documents and this reuses.
71 registers, 0 spills, 34,304 B dynamic shared.

  ctx 31481   21.368 s -> 20.548 s   (5 reps, same binary)
  ctx 11063    7.240 s ->  7.162 s   1.29x -> 1.27x
  ctx 32243   21.997 s -> 21.218 s   1.33x -> 1.28x

GATE. scripts/ppl.py:

  below-bound ppl  8.10097 -> 8.10097   0.000%   dense, CONTROL
  above-bound vs tc2 (isolates this)   +0.016%
  above-bound vs the scalar spine      -0.145%   (better)

lc_needles.py is 21/21 (100%) on a depth x length grid to 24k. So the scorer
costs +0.016% and the stack as a whole is now BETTER than the scalar kernels it
replaces.

Ships OFF: ATLAS_QSA_SCORE_TC=1. Both remaining scalar kernels are now on tensor
cores, and both were blocked by an argument rather than a measurement -- 19b on
tensor cores, 16a on the agreement bar, 31c on BF16 Q. Three for three.

(cherry picked from commit d2ec582)
The last item of size in the prefill is mHC's elementwise traffic: hc_post
(1232 ms at 202 GB/s) and hc_pre_stage_bf16 (827 ms at 214 GB/s) move the
residual highway at 40 KB per token per layer per site -- ~363 GB -- because it
is F32 at 4x hidden width. Storing it BF16 halves that, worth ~0.6-0.85 s.

Priced first, the way 34 priced BF16 Q. HC_PROBE_BF16_STREAMS (kept, ifdef,
default off) rounds hc_post's output to BF16 precision while every buffer, dtype
and layout stays exactly as it is. hc_post writes the highway every layer, so
every later read then sees BF16-representable values -- what a BF16 highway
would deliver -- at zero speed change.

  below-bound ppl  8.10097 -> 8.08077   -0.249%
  above-bound ppl  4.59996 -> 4.62762   +0.601%

THE DENSE CONTROL MOVED, for the first time in this campaign, and that is the
finding as much as the number is. Every QSA change so far held below-bound at
exactly 8.10097 because it was confined to the selective path; mHC runs on every
layer and every token, so it HAS no control region and cannot be gated the way
28-35 were.

+0.601% above the bound is the largest regression measured here -- about 40x the
tensor-core scorer's +0.016% -- for a SMALLER win. Strictly worse than anything
shipped, so it is not built. One build cycle bought that answer and saved a
refactor across hc_post, hc_pre_stage, hc_pre_mix, the highway allocation and
every consumer, all of which would then have been rejected at the gate.

The probe stays in-tree behind the ifdef so the next person inherits the number
rather than the idea.

(cherry picked from commit 3205396)
ATLAS_GDN_FUSED_NORM=1 / --gdn-fused-norm produced fluent garbage on qwen4_exp:

  without:  'SEVEN-CORAL-NINE'
  with:     'SEINVRG下角 Trevrig?risamel/cofl Bryesh mang?rf timeipJsonValue...'

Byte-identical across independent server restarts -- deterministic, not a flake
-- with no warning and no model guard. TTFT is UNCHANGED with it on, so a
timing-only A/B reads it as "neutral, drop it"; only a generation check catches
it.

ROOT CAUSE. `gated_delta_rule_decode_f32_norm` and `..._conv_norm` fold the
gated RMS norm into the decode kernel, and both hard-code SiLU:

    common/gated_delta_rule.cu:  s = g / (1.0f + expf(-g));       // SiLU
    common/rms_norm.cu:          s = 1.0f / (1.0f + expf(-g));    // sigmoid

qwen4_exp declares output_gate_type = "sigmoid". rms_norm.cu says exactly what
that means, next to the sigmoid twin it already ships:

    Qwen3.5/3.6 gate with SiLU; qwen4_exp declares output_gate_type =
    "sigmoid" and gates with a plain sigmoid. That is a correctness switch,
    not a tuning knob -- the two differ most exactly where the gate is doing
    its job.

The tree already has the machinery: `kernel_select::gated_norm_kernel` appends
`_sigmoid`, and the separate-norm path uses it for gated_rms_norm,
_f32_input and _prefill. The two FUSED kernels were loaded by literal name,
bypassing it, so a sigmoid model silently got the SiLU gate.

THE FIX, and why it is a skipped lookup rather than a renamed one. Routing them
through `gated_norm_kernel` was the first attempt and it is wrong: no
`..._sigmoid` twin of either exists, so the lookups resolve to handle 0 and the
fail-closed startup audit refuses to boot --

  Error: 2 unresolved kernel lookup(s) ... Each one resolved to handle 0, so
  its dispatch site is on a silent fallback path

which is the audit doing its job, since relying on a missing kernel to fall back
is exactly what it exists to prevent. So SKIP the lookup for a gate this kernel
family does not implement, the same way `hc_kernel` skips for a model without
the highway: an un-issued lookup leaves no failed row. The existing
`gdn_f32_norm_k.0 != 0` guard in ssm_forward.rs then selects the correct
separate-norm path.

VERIFIED: with the fix, --gdn-fused-norm on qwen4_exp answers 'SEVEN-CORAL-NINE'
and the kernel audit passes. SiLU models are untouched -- they take the same
try_kernel call as before.

Adding a sigmoid twin of both fused kernels (duplicated, per rms_norm.cu's
stated convention) is the real fix and would make the flag useful rather than
merely safe; `fused_gated_norm_kernel` will pick one up with no further change.
Found by sweeping opt-in levers, and worth more than the two neutral ones it was
found beside.

(cherry picked from commit e283353)
Avarok atlas PR #698 (tbraun96) audited inferspark_prefill.cu for constants that
are really functions of BC and fixed four, so the kernel can be built at
BR=32/BC=16 for Gemma-4's 512-wide layers -- currently 16.5 s of an 18.1 s
prefill in a scalar fallback. Two survivors of the same shape remain, and the
first fires at exactly that shape.

  BR=32 entry.  The DECLARATION was parameterised by fix 3 --
  `float acc_s[BC / 8][4]` -- but the initialiser three lines below was left
  literal:

      float acc_s[BC / 8][4];
      for (int i = 0; i < 4; i++) { acc_s[i][0] = ...; }

  At BC=16 the array holds TWO entries and the loop writes FOUR. A stack OOB,
  in precisely the configuration #698 exists to enable.

  BR=64 entry.  Fix 3 reached only one of the two entry points: `float
  acc_s[4][4]` is still literal here while the MMA loop beside it indexes
  `acc_s[nt]` for `nt < BC/8`. Correct at the shipped BC=32 (4 == 4) and at
  BC=16, wrong at any BC > 32.

Found empirically, not by re-reading the file: this is what had to be fixed to
take qsa_attn_tc2 -- derived from this kernel's BR=32 arm -- to BC=16.

PROVABLY NO CHANGE AT THE SHIPPED SHAPE, the same standard #698 held itself to.
Rebuilt and diffed the emitted PTX for target 24 (qwen3.8-flash-next):

  4824 instructions -- BYTE-IDENTICAL
  124 regs / 90,112 B  and  122 regs / 70,400 B   (both entry points, unchanged)

At BC=32, BC/8 is 4 and both edits are no-ops; they only bite where the file is
currently unbuildable. Runtime unchanged: needle recall past the inert bound
still resolves, ctx 31480 still 20.644 s.

The point is not these two lines. #698's table is a PATTERN, and a pattern is
worth re-running over the file rather than trusting the list -- both survivors
are the same shape as the four it caught.

(cherry picked from commit 38bbea3)
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

GDN_PIPE default: 27B gate passes (job 252). main66, nvidia/Qwen3.8-27B-NVFP4, ATLAS_GDN_PIPE=0 (logged spine gated_delta_rule_chunk_delta_h_vfused) vs =1 (..._pipe): ppl 0.000 % in both regions, kl_drift top-1 100 % with JSD exactly 0, needles 11/11 of the cases the baseline passes (both arms 11/12). Output-identical on both Flash-Next (job 243) and the 27B, so 762d3bbe6's NVIDIA default stands.

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

QSA TC flag split (reiner job 258). Each flag alone on top of #68's defaults (B), 8 × 12k ppl windows + lc_subset needles + kl_drift:

arm dense ppl (control) above-bound ppl needles long-gen top-1 vs B
ATLAS_QSA_ATTN_TC2=1 alone 0.000 % −0.019 % 12/12 53.6 %
ATLAS_QSA_SCORE_TC=1 alone 0.000 % +0.222 % 12/12 62.6 %

Reading:

  • SCORE_TC is the one that costs quality. It moves QSA selection, so ppl rises 0.22 %.
  • TC2 is ppl-neutral: it changes only the attention reduction.
  • Neither flag alone loses a needle. The 11/12 in job 243 was the combination, or n=12 noise.
  • Top-1 on long generations is not discriminating here. Any reassociation in the QSA path diverges long greedy runs (QSA selection is chaotic; qwen4_exp: land the 2026-08-31 long-context TTFT campaign (QSA tensor cores, mHC grid fix, MoE CTA striding) #68's own defaults vs main read 46.9 %), so ppl and needles are the usable gates.

Next: job 263 measures TTFT for TC2 alone vs SCORE_TC alone at 160 / 2.6k / 10.2k / 31.5k. If TC2 alone keeps most of the 24.3 → 19.9 s, it becomes the candidate to switch on by default, and SCORE_TC stays opt-in.

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Drift bisect (reiner job 259). Dense-region ppl, below the QSA bound, where nothing should move vs main66. 8 × 12k windows.

build commits past main66 dense ppl vs main66 above-bound
X cfc6dae8e MoE transpose on all 48 layers, tier auto-pick +0.519 % +0.031 %
Y 379d741e0 X + 5 hc commits +0.036 % −0.014 %
#68 head (jobs 240/251/258) all +0.036 % —
main66 vs main66 — 0.000 % 0.000 % (lc 100 %)

Correction to my earlier framing. The dense drift is not introduced by the mHC series. The first campaign commit alone moves dense ppl +0.52 %, and something inside the five hc commits brings it back to +0.036 %.

Both X and Y picked the same MoE tier (UNIFIED, free 24.4 / 24.3 GB), so a different tier is not the cause. The hc alignment fix (d39aaf27e) guards a sticky fault, not a silent value change, so it is not an obvious candidate either.

That leaves an open correctness question: is X a transient defect that a later commit fixes, or does the head carry two offsetting errors?

Job 264 answers it: it builds each of 54e2bc82c, d39aaf27e, a2d4cefa7, 2df0972ed, measures dense ppl for each, and re-runs X to confirm the +0.52 % is reproducible. I would not merge #68 until this is resolved.

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Two results.

1. QSA TC flags, TTFT split (job 263). Each flag alone on #68's defaults, server TTFT, median of 3 (7 at short contexts):

arm 2.6k 10.2k 31.5k
B / B2 (defaults) 1.766 / 1.764 s 7.42 / 7.39 s 24.36 / 24.32 s
QSA_ATTN_TC2 alone 1.705 6.51 (−12 %) 20.97 (−13.8 %)
QSA_SCORE_TC alone 1.764 7.31 23.53 (−3.3 %)

Together with job 258 (TC2 alone: ppl −0.019 %, needles 12/12; SCORE_TC alone: ppl +0.222 %):

  • Turn ATLAS_QSA_ATTN_TC2 on by default. That takes 31.5k TTFT from 24.3 to 21.0 s.
  • Keep SCORE_TC opt-in. It is worth only 0.8 s and costs +0.22 % ppl.

2. Where the dense drift comes from (jobs 259 + 264). I built every commit in the first 6 and measured dense ppl vs main66:

commit dense ppl
cfc6dae8e MoE transpose (UNIFIED, all 48 layers) +0.519 %
54e2bc82c, d39aaf27e, a2d4cefa7, 2df0972ed +0.519 % (identical to 5 digits)
379d741e0 mHC collapse routing +0.036 %

There are two separate numeric effects that happen to cancel.

  • The MoE transpose moves dense ppl +0.52 %.
  • The mHC routing moves it about −0.48 %. Plausibly this is precision recovered: the tensor-core hc GEMM path rounds normed to BF16, per d39aaf27e's own comment.

Job 267 runs the #68 head with ATLAS_MOE_TRANSPOSE=0. If that lands near −0.48 %, the transposed MoE path loses precision and is worth fixing on its own, because the net +0.036 % currently hides it. Still not merge-ready until that is answered.

9ca70af shortened max_m_tiles to 2x the average expert whenever the
k64-stride marker kernel exists, and that one value then fed EVERY launch in
forward_prefill_routed. Only moe_w4a16_fused_gate_up_t_k64 and
moe_w4a16_grouped_gemm_ptrtable_t_k64 stride blockIdx.y over m-tiles; the
untransposed ptrtable fallbacks, the m128 / fp4 / e8m0 variants and the FP8
down all return past their first m-tile, so they silently dropped every hot
expert's rows past the short grid.

Reachable without any exotic flag: ATLAS_MOE_TRANSPOSE=0, or any boot/target
where the transpose pass does not run while the marker kernel is present
(the gfx1151 Flash-Next target logs no transpose pass). Measured on the #68
head, nvidia Flash-Next NVFP4, 8 x 12k ppl windows (reiner job 267):
  defaults                 dense +0.036 %   above-bound  -0.014 %
  ATLAS_MOE_TRANSPOSE=0    dense +14.9 %    above-bound  +174 %

Now max_m_tiles stays the hottest expert's count and grid_m_strided goes to
the two striding launches only; the default (transposed k64) path gets the
same grid it got before, so its output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Real bug found in this PR, and fixed: 1ea4e20ca, validation queued as reiner job 269.

What broke. 9ca70af11 (stride the prefill m-tiles) shortens max_m_tiles to 2x the average expert whenever the stride-marker kernel exists. That single value then fed every launch in forward_prefill_routed, but only two kernels stride blockIdx.y: moe_w4a16_fused_gate_up_t_k64 and moe_w4a16_grouped_gemm_ptrtable_t_k64. These all return past their first m-tile, so they silently dropped every hot expert's rows past the short grid:

  • the untransposed ptrtable fallbacks;
  • the m128, fp4 and e8m0 variants;
  • the FP8 down.

Measured (job 267). #68 head, nvidia Flash-Next, 8 × 12k windows:

dense ppl vs main66 above-bound ppl
defaults +0.036 % −0.014 %
ATLAS_MOE_TRANSPOSE=0 (the documented escape hatch) +14.9 % +174 %

Why this matters beyond the hatch. Any boot or target where the transpose pass does not run while the marker kernel exists hits the same path. The gfx1151 Flash-Next target logs no transpose pass on Windows today. Had this merged, Flash-Next on the HIP targets would have produced wrong output.

The fix. max_m_tiles stays the hottest expert's count, and a separate grid_m_strided goes only to the two striding launches. The default (transposed k64) path gets the same grid it got before.

Job 269 checks three things:

  • greedy output of the fixed head is byte-identical to the old head on defaults;
  • ATLAS_MOE_TRANSPOSE=0 ppl is sane again;
  • fixed-hatch vs main66 measures the transposed-MoE numerics on their own (the +0.52 % seen in 259/264).

GB10 jobs 258 + 263 (nvidia Flash-Next, tc2 alone on this branch's
defaults): dense-region ppl 0.000 %, above-bound ppl -0.019 %, needles
12/12; server cold TTFT 31.5k 24.36 -> 20.97 s, 10.2k 7.42 -> 6.51 s.
Not bit-identical to the grouped kernel (QSA selection is chaotic, so long
greedy generations diverge; ppl + needles are the gate). One helper,
qsa_attn_tc2_enabled(), answers the default: an explicit
ATLAS_QSA_ATTN_TC/L8 opt-in keeps its kernel, ATLAS_QSA_ATTN_TC2=0
restores the exact grouped kernel, gfx1151 stays off (unmeasured). A
once-per-process INFO line names the variant that dispatched so serve logs
prove what engaged.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

TC2 is the default now (7747b77b3), plus merge-train status

7747b77b3: tensor-core tc2 QSA prefill attention is the default on NVIDIA.

  • One helper, ops::qsa_attn_tc2_enabled(), decides it.
  • An explicit ATLAS_QSA_ATTN_TC=1 or ATLAS_QSA_ATTN_L8=1 still selects its own kernel. ATLAS_QSA_ATTN_TC3=1 still wins because it is checked first.
  • ATLAS_QSA_ATTN_TC2=0 restores the exact grouped kernel. gfx1151 stays off (unmeasured there).
  • A one-time INFO line names the variant that dispatched, so a serve log shows what engaged.
  • Evidence is jobs 258 and 263: TC2 alone gives ppl −0.019 % above the bound and 0.000 % dense, needles 12/12, and 31.5k TTFT 24.36 → 20.97 s.

Job 272, engagement and identity. Run on the merge-train tree b84fb333b (main + #78 + #67 + this PR). Serve profile is lib.sh's (8 × 12k ppl windows, util 0.88, no MTP).

arm compared with dense ppl above-bound ppl windows that differ variant logged
D, defaults job 258, ATLAS_QSA_ATTN_TC2=1 on c8bbd90f8 7.71124 = 7.71124 4.38413 = 4.38413 0 / 8 tc2
D0, ATLAS_QSA_ATTN_TC2=0 job 269 arm F (1ea4e20ca defaults) 7.71124 = 7.71124 4.38496 = 4.38496 0 / 8 grouped

I cancelled job 270. Its serve used the lib.sh profile, which passes --disable-thinking. That is not the recipe's tool-serving profile. The recipe documents --disable-thinking as an accuracy cliff on BFCL for this checkpoint (76.95 vs 81.74 on the same n=334 draw). So 270's score could not be compared with job 225 (85.73 / 85.96, recipe self-serve). The gate now runs the recipe self-serve (--pull-request-gate) exactly as 225 did.

Job 271: memory under the recipe profile. Setup: thinking on, MTP K=2, prefix caching on, util 0.90; BFCL traffic, 28 min per arm; client in its own process.

arm server RssAnon MemAvailable client RSS
main66 +20.6 MB/req −20.8 MB/req flat
this PR (1ea4e20ca) +24.6 MB/req −24.7 MB/req flat
main66, no --speculative +28.0 MB/req −28.2 MB/req flat
  • The growth is all in the server's anonymous heap, and it is not MTP.
  • Neither harness separates this PR from main: jobs 265/268 (thinking off) measured 4.22 / 4.18 MB/req, and job 271 (thinking on) measured 20.6 / 24.6.
  • The problem is pre-existing ([job] Per-request host-memory growth: attribute and stop it #73), and it is large enough that no main-lineage build can finish a 995-question gate at the recipe's util 0.90. The watchdog would stop it around request 300; job 245 got to about 388.
  • Job 225 (lane head c8b88c6) did finish, and job 273 checks whether the lane grows less. Job 273 also takes a jemalloc heap profile of the growth.

Merge gate, as the maintainer defined it. ST-995 (bfcl-subset --pull-request-gate) plus the 2.5 h agentic perf leg (endpoints, 1007 turns), run on the exact tree main will become (main + #78 + #67 + #68). The three PRs merge once both pass. The #73 fix goes in first, because without it the ST leg cannot finish.

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Merge-train ST-995: PASS (reiner job 280).

Fingerprint:

overall normalized
job 280, merge-train tree 84.72 84.68
committed bars 82.72 81.65
job 225, lane head c8b88c6 (not a one-variable comparison) 85.73 85.96
  • The serve log confirms QSA prefill attention: tc2 was engaged, and that thinking was not forced off.
  • Memory held over the full run: MemAvailable 9.8 GB at the end, and server RssAnon flat at ~1.76 GB from request ~500 to 995. Before Stop the per-request host heap growth (#73): share xgrammar's TokenizerInfo, dedupe the kernel audit #82, main-lineage builds hit the watchdog around request 300.
  • vs job 225, per category:
    • hallucination 92.80 → 90.72;
    • live 81.76 → 81.76;
    • non_live 83.30 → 81.55.
    • The −1.0 overall gap is inside one standard error for n=995 (≈1.1 pt). The trees differ in more than this PR, so this is not attributed.
  • Record: .benchmarks/bfcl-subset/2026-09-26-53f4a3d3ad-nvidia-qwen3.8-flash-next-nvfp4.json on reiner (wt-train2).

Still to run before merging:

  • a support-matrix check for the MoE-transpose default on the other MoE models on the box (job 297: Nemotron-3.5-Lightning-30B-A3B and Qwen3.6-35B-A3B, main66 vs train);
  • the 2.5 h agentic perf leg (job 298).

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Merge-train agentic perf leg: VALID, 1007 of 1007 turns (reiner job 298 plus the Mac-side endpoints driver).

Fingerprint:

  • tree 53f4a3d3a (same as job 280), binary sha256 29906e48…566c;
  • serve = the shipped Flash-Next recipe line with --disable-thinking (MLPerf edge rules: reasoning off, ctx 32768), MTP K=2, prefix caching on, util 0.90, TC2 engaged;
  • harness: endpoints agentic-coding-perf-2.5h (20 trajectories), single stream, temp 0, seed 42.
turns 1007 issued, 1007 completed, 0 failed; scorer: 1006 scored, 0 missing
wall 5355 s (89 min)
TTFT median 1.16 s · p90 1.65 s · p99 2.76 s · max 16.1 s
TPOT median 63 ms
action-IoU score 0.4899
server 0 KV-exhausted · 0 prompt-too-long · 0 ERROR lines · 0 watchdog
multi-turn cache 98 % warm hits (938 of 960 lookups), mean recompute on a hit 16 tokens
memory MemAvailable 10.7 → 8.3 GB. Server RssAnon rose 0.94 → 2.71 GB in the first 58 turns, then only +0.5 MB per turn to 3.22 GB at turn 1003.

Compliance. Every config-lock check passes (temperature 0, seed 42, single stream), and so does no_dropped_turns (missing=0). all_turns_observed fails as observed=1006 == issued=1007. That is a checker defect, not a dropped turn:

  • the scorer excludes one dataset turn that has no ground truth (astropy__astropy-12907 turn 18, exclude_reason: "no ground truth");
  • so observed is capped at expected = 1006, while the check compares it with issued = 1007;
  • on this dataset the check cannot pass for any server.

The manual attestation (reasoning off, ctx 32768) is covered by the serve flags above; the log shows thinking is forced OFF.

Both halves of the merge gate are now in: ST-995 PASS (job 280) and this perf leg. The last pre-merge item is the MoE support-matrix check (job 306, running).

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Support-matrix check (reiner job 306) found a regression in this PR. I'm holding the merge until it's fixed.

The job compares main66 against the merge-train tree. Both builds include the #89 and #90 boot fixes, so the models can boot at all.

  • Nemotron-3.5-Lightning-30B-A3B NVFP4: boots on both trees with no unresolved kernel lookups. On the train tree, greedy output is identical on the short / ~2k / ~10k probes (mean |Δlogprob| 0.0000), and 10k TTFT is 4.59 → 4.58 s. This PR's MoE transpose is inert on this model.
    • The tier log line claims selected FULL … cost 52.2 GB → RUNNING, but free memory is unchanged (75.8 GB before and after) and pre-KV grows only 0.2 GB. That log line is misleading for models whose MoE layers don't take the transpose. Cosmetic; noted for later.
  • Qwen3.6-35B-A3B NVFP4 and FP8 are refused by the boot kernel gate on both trees.

Fix in progress: declare the marker [expected_absent] on every MoeLayer target except flash-next, and add a fleet test, following the #438 gated_delta_rule_snap precedent. The handle-0 fallback (full m-tile grid) is already the correct behaviour on those targets. The change is TOML-only and doesn't touch Flash-Next's code paths, so the ST-995 and perf-leg results stay valid for this model.

…r target

This PR added a lookup to MoeLayer::new:
moe_persist_marker::moe_w4a16_k64_strides_m_tiles. It is a capability
marker, and only qwen3.8-flash-next ships it. On every other MoeLayer
target the lookup resolved to handle 0, and the boot kernel gate refused
the checkpoint (reiner job 306: Qwen3.6-35B-A3B had 6 unresolved lookups
on the merge-train tree against 5 on main).

The handle-0 fallback (full m-tile grid) is already correct there, so the
lookup is declared expected_absent on the 16 targets whose model_types
construct MoeLayer, following the #438 gated_delta_rule_snap precedent.
Nemotron (NemotronMoeLayer), the dense qwen3_5 targets and flash-next
are excluded. A new ignored fleet test, like its #438 sibling, pins
ship-or-declare for every MoE-issuing target. TOML and tests only;
flash-next behaviour is unchanged.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@AzeezIsh
AzeezIsh marked this pull request as ready for review September 26, 2026 11:18
@AzeezIsh
AzeezIsh merged commit b6862ff into main Sep 26, 2026
25 of 26 checks passed
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Merged as part of the GB10 merge train (main 1ab38536b). The train was #78, #67, #68, #82, #83, then #89 and #90.

Gates on the combined tree:

  • ST-995 (job 280): PASS, 84.72 / 84.68 against bars of 82.72 / 81.65.
  • Agentic perf leg (job 298): VALID. 1007 of 1007 turns, 0 failed, 0 missing, 89 min.
  • Support matrix (job 346): green. Nemotron-3.5-Lightning NVFP4, Qwen3.6-35B-A3B NVFP4 and Qwen3.6-35B-A3B FP8 each boot with 0 unresolved lookups on main66 + fixes and on the train tree. Greedy probes are identical between the two trees (mean |Δlogprob| 0.0000), and 10k TTFT is equal or slightly faster.

Tree check: main has the same tree as the job-346 build (f8a04db1f): git diff is empty. main also differs from the tree the gates ran on (53f4a3d3a) only by the marker [expected_absent] declarations (f261446bd), which are TOML and tests only.

@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Cross-platform note on cfc6dae8e (the UNIFIED MoE transpose tier), from the Windows Strix Halo port (#80).

I cherry-picked cfc6dae8e onto the Windows Flash-Next branch. As on GB10, only the UNIFIED tier fits there: costs hybrid 126.6 / full 63.3 / gate_up 42.2 GB, free 17-19 GB -> selected UNIFIED. On gfx1151/WDDM it then failed 3 boots out of 3 with a sticky hipErrorLaunchFailure (719) somewhere around the 2nd-7th MoE layer.

Diagnosis:

  • Not a use-after-free. An allocation audit found no source pointer that had been freed earlier.
  • Memory churn. Each transpose_for_prefill_unified_inner call allocates 3 × (400 + 50 MB) slabs and then frees about 3 × 512 × 2 small per-expert originals. A 1 s sampler of WDDM's GPU process-memory counters shows committed memory climbing about 1.4-1.5 GB per call and never dropping at the Phase B/D frees, until a launch faults.

Fix, on the Windows branch as 46dd64ca6:

  • Per expert, the transposed buffer is exactly the same size as the original. So UNIFIED now transposes into one grow-only scratch per call, copies the result back over each expert's own weight/weight_scale, and points the _t tables at those same allocations.
  • There are no per-layer slab allocations and no expert frees. The fields are NULLed so no untransposed path can read them.
  • Committed memory stays flat through the whole pass.

Measured on winbox (observed, single harness, same binary with ATLAS_MOE_TRANSPOSE=0 as control):

  • Perplexity: 8 × 6000-token windows via ppl.py. Dense below-bound 8.5728 → 8.5625 (−0.12 %), above-bound 4.5946 → 4.5849 (−0.21 %), 6 of 8 windows better.
  • ~1.85k-token TTFT: about 19 s → about 10 s serial, and about 18.8 → 8.2-9.6 s with MTP.
  • ~7.2k-token TTFT: about 75 → 44 s serial, and 73 → 38-43 s with MTP.
  • Decode: MTP decode is within about 2 %. Greedy output is identical to the control under MTP. Serial greedy diverges late (a summation-order tie; the ppl result above covers quality).

GB10 may not show the WDDM symptom, but the in-place variant is memory-neutral and does about 3K fewer allocator calls per layer on every backend. It may be worth taking into this PR. I have not measured it on GB10.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants