Skip to content

[FlyDSL] [QSA] Add FP8 K/V to the sparse prefill - #8149

Merged
coderfeli merged 6 commits into
ROCm:mainfrom
luocheng25:luocheng/qsa-fp8-v2
Nov 23, 2026
Merged

coderfeli merged 6 commits into
ROCm:mainfrom
luocheng25:luocheng/qsa-fp8-v2

Conversation

@luocheng25

@luocheng25 luocheng25 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds FP8 K/V to aiter.ops.qsa.qsa_sparse_prefill on MI308X (gfx942).

  • Data types. K/V can be torch.float8_e4m3fnuz (gfx942's dtypes.fp8) with FP32 dequantization scales, either per token and KV head ([N, HK], or [P, HK] with kv_slots) or per tensor ([1]). Both packed K/V and token pools read through kv_slots are supported, also past 4 GiB.
  • compute="fp8" (the default) runs FP8 MFMA kernels. Q is quantized per (row, head) in the pack launch, and the probabilities in FP8.
  • compute="bf16" dequantizes the request tokens to BF16 and runs the BF16 kernels.
  • Packed or raw K/V, as for BF16. The union kernel reads the raw K/V. Direct rows read the context packed per call while it fits the platform's budget, else the raw K/V, so a long context is not packed whole on every call.
  • BF16 benefits too. K1 now skips sorting the rows whose blocks already ascend.

Follows #8148 (the #6576 follow-ups, now in main) and is built to the same rules:

Motivation

SGLang serves Qwen3.8-Flash-Next with an FP8 KV cache. In the customer TP2 configuration, the FP8 KV cache holds 89% more tokens (151040 → 285312) with GSM8K unchanged.

aiter's QSA sparse prefill takes BF16 K/V only. This PR gives aiter's consumers (SGLang's aiter attention path, ATOM) FP8 QSA prefill. aiter's Triton QSA path (#7008) already reads FP8 K/V, but it converts them to BF16 in the kernel, which corresponds to compute="bf16" here.

KV caches past 4 GiB per layer are common at TP8 with long contexts, so FP8 pools must not be limited to 32-bit offsets, and a prefill chunk or extend after a long context must not repack that context on every call.

Changes

  • Entry. qsa_sparse_prefill(..., kv_slots=None, batch_invariant=False, k_scale=None, v_scale=None, compute="fp8"). The new arguments are trailing and keyword-only.
    • FP8 K/V need both scales in the same layout.
    • FP8 K/V and pools may exceed 4 GiB; each request's K/V keeps the BF16 span limit.
    • Invalid FP8 arguments are rejected before any launch: dtype (float8_e4m3fn), scale dtype, device, shape and contiguity, mixed scale layouts, and compute values.
    • With compute="fp8", per-token V scales are clamped to [2**-60, 2**60], as the docstrings state: they join the probabilities, and the bounds keep a row's row-sum terms within FP32's range.
    • The workspace cache key includes the FP8 mode and scale layout.
  • Kernels. New sparse_prefill_union_fp8.py (union) and sparse_prefill_direct_fp8.py (direct, plus the K/V pack with Q quantization).
    • Stable FlyDSL operations only: the PV MFMA through the public MFMA atom, the rescale as plain FP32 multiplies, hazard padding left to LLVM. The few FP8 primitives without a stable equivalent (empty-asm holds and fences, DPP row broadcasts, v_cvt_pk_fp8_f32, bare log2 and reciprocal) join the low-level section of sparse_prefill_common.py.
    • Union. Each four-token block is read through its own buffer, based at the block's 64-bit address, so K/V and pools may exceed 4 GiB. Its records end at the request's last token and are 0 past the block list; tiles before a task's last three use constant records. A K load reads one block whole, and a wave reads the same four blocks for K and V. V is read raw (a dword of one token per lane) and transposed in registers into the V^T LDS tile, so the union kernel never reads the pack.
    • Direct. Packed or raw. Raw loads 16-byte K quarters (swapped between lanes by ds_swizzle) and the V rows (transposed as the pack does), and computes the per-token scale terms as the pack does, so raw and packed give the same bits. Through a pool past 4 GiB, raw uses 64-bit loads.
    • The pack reads each block from its own 64-bit base and stores K token-minor, so each 4-lane quad of a direct K load reads 64 contiguous bytes.
    • Q rows of amax below 2**-118 quantize as if their amax were 2**-118: 240 / amax overflows FP32 below about 2**-120, and 2**-118 / 240 is still a normal FP32 scale. Such rows keep fewer FP8 bits, but no nonzero row quantizes to 0.
    • Per-token scores take S * (k_scale * c): S, the FP8 dot product, is up to about 2**24, so S * k_scale would overflow FP32 for K scales past 2**104.
    • FP32-to-BF16 output conversion rounds to nearest even (bits + 0x7FFF + lsb, as _pack_bf16 does), without asm.
    • Byte offsets past 2 GiB use unsigned shifts (per-token scale records, and the residual merge's union LSE found from the row's out offset), and the FP8 pack buffer is a [blocks * HK, 1024] byte scratch.
  • Plans and routing.
    • Pack or raw. BF16's rule, with the FP8 pack's bytes: pack while PK+PV fit the platform's budget (64 MiB on MI308X), or while the context has at most pack_tokens_per_row tokens per query row. FP8 sets that to 320 (BF16: 32): raw FP8 direct costs more per row, and random selections with 65–257 tokens per row run up to 1.8× slower raw than packed. With a union plan the pack runs only when K3 routes some tile to direct.
    • FP8 route calibrations; core/residual union tiles (H12/H6), whose residual blocks the direct kernel merges by log-sum-exp.
    • With fewer union tasks than CUs (a short prefill leaves CUs idle while its longest causal tiles run), K3 splits the longest tasks' key ranges into two parts on separate CTAs; the part finishing last merges their partial O, m and l.
    • With batch_invariant=True, FP8 follows [FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance #8148's per-request rules and does not split, since a split depends on the whole call's load. Core/residual stays: it is a per-tile decision.
    • With more union task entries than one K3 order CTA sorts (4096), K3 places every chunk's runnable entries before all idle ones, since the FP8 union kernel ends a CTA's task loop at its first idle entry. Plans with one order CTA compile the same K3 as before.
    • K1 skips the sort of rows whose blocks already ascend (complete causal prefixes, the indexer's ascending top-k). This also speeds up BF16 long-context chunks.

Performance (if applicable)

GPU time of one qsa_sparse_prefill call: the profiler's span from the first kernel's start to the last kernel's end, with the GPU kept busy while the call is queued (host time hidden). MI308X (gfx942, 80 CUs), FlyDSL 0.5.0, one KV head, T = 512; identical CPU-generated inputs. Each tree and mode runs in its own process and repeats the call (warm caches): median of 20 samples per process and of 3 alternating rounds. FP8 K/V are the same BF16 K/V quantized to E4M3FNUZ with scale amax / 240, per tensor or per (token, KV head), with compute="fp8". Changes are relative to main's BF16.

Hardware Workload/configuration main BF16 (µs) This PR, BF16 (µs) This PR, FP8 per tensor (µs) This PR, FP8 per token (µs)
MI308X prefill 4096, H12 669.7 669.5 (−0.0%) 398.8 (−40.5%) 444.5 (−33.6%)
MI308X prefill 12000, H12 2461.7 2463.7 (+0.1%) 1512.6 (−38.6%) 1640.6 (−33.4%)
MI308X prefill 12000, H3 1063.1 1061.4 (−0.2%) 696.6 (−34.5%) 778.3 (−26.8%)
MI308X prefill 32768, H6 6560.7 6575.0 (+0.2%) 3558.9 (−45.8%) 3839.4 (−41.5%)
MI308X 1024-row chunk after 131072 tokens, H12 287.0 278.8 (−2.9%) 173.1 (−39.7%) 191.4 (−33.3%)
MI308X 4096-row chunk after 126976 tokens, H6 493.6 472.6 (−4.3%) 319.9 (−35.2%) 356.1 (−27.9%)
MI308X one 256-row extend after 8192 tokens, H3 113.8 113.1 (−0.7%) 82.8 (−27.3%) 85.5 (−24.8%)
MI308X one 256-row extend after 8192 tokens, H12 115.8 116.6 (+0.8%) 77.9 (−32.7%) 84.8 (−26.7%)
MI308X one 128-row extend after 16384 tokens, H6 105.1 105.6 (+0.5%) 77.9 (−25.9%) 80.9 (−23.1%)
MI308X 5 requests (300/1024/0/64/1001 rows), H12 135.2 135.0 (−0.1%) 100.0 (−26.0%) 108.0 (−20.1%)
MI308X 12000-row prefill + 64- and 128-row extends, H3 1398.4 1395.5 (−0.2%) 890.1 (−36.3%) 1003.2 (−28.3%)
MI308X two 2048-row prefills, H6 228.4 228.0 (−0.2%) 161.2 (−29.4%) 177.2 (−22.4%)
MI308X 8 × 256-row extends after 2k–16k tokens, H3 142.9 132.3 (−7.4%) 113.4 (−20.6%) 123.7 (−13.4%)
MI308X one 64-row extend after 131072 tokens, H12 150.5 151.1 (+0.3%) 72.0 (−52.2%) 80.2 (−46.7%)
MI308X one 64-row extend after 524288 tokens, H3 153.8 152.0 (−1.2%) 72.6 (−52.8%) 81.2 (−47.2%)
MI308X one 256-row extend after 1048576 tokens, H6 157.7 156.7 (−0.7%) 122.3 (−22.4%) 129.2 (−18.1%)
MI308X 16 × 64-row extends after 65536 tokens, H3 140.0 133.3 (−4.8%) 77.3 (−44.8%) 82.7 (−40.9%)
  • FP8 vs BF16. Against this PR's BF16, FP8 takes 14–52% less GPU time per tensor and 6.5–47% less per token on every layout.
  • Against an earlier revision of this change (dca8eb2e8, which packed every request's context on every call and read the pack's V^T in the union kernel), FP8 in the default mode:
    • long-context extends are 1.5–6× faster (one 64-row extend after 524288 tokens: 299.4 → 72.6 µs per tensor; 16 × 64-row extends after 65536 tokens: 464.8 → 77.3 µs);
    • long-context chunks are 7–15% faster and the batch of eight short extends 13–14% faster, since union tiles no longer need the pack;
    • prefills are 0.2–1.0% slower per tensor and 0.8–2.3% per token (a buffer per block in the union kernel);
    • every other layout is within −2.9% to +2.3%.
  • BF16 vs main. Outputs are bitwise equal to main's ([FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance #8148). K1's sort skip makes long-context chunks 3–4%, the batch of short extends 7% and 16 short extends 5% faster; the other layouts are within −1.2% to +0.8%.
  • batch_invariant=True with FP8 (opt-in), FP8 per tensor relative to the default mode. Short prefills that split their key ranges by default lose the split; batches with a full prefill gain per-request tile rows; short requests below the union planning rows run direct.
Hardware Workload/configuration Default (µs) batch_invariant=True (µs) Change
MI308X the single requests above (prefills, chunks, extends) — — −2.0% to +0.2%
MI308X prefill 1024, H3 (split by default) 55.1 61.4 +11.3%
MI308X prefill 1024, H6 (split by default) 56.4 60.0 +6.4%
MI308X prefill 2048, H3 (split by default) 72.2 90.8 +25.7%
MI308X 12000-row prefill + 64- and 128-row extends, H3 878.0 746.5 −15.0%
MI308X two 2048-row prefills, H6 159.3 141.7 −11.0%
MI308X 5 requests (300/1024/0/64/1001 rows), H12 99.6 110.8 +11.2%
MI308X 8 × 256-row extends after 2k–16k tokens, H3 112.9 328.9 +191.2%

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI300X

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

None. The new arguments are trailing, keyword-only and optional, and BF16 calls give the same bits as main.

PR Self-Review

Reviewed revision

dbfc4bf978507b64c5018e22e709fab7a7d5f0d8

Behavior and intent

qsa_sparse_prefill accepts FP8 K/V with per-token or per-tensor scales, packed or through kv_slots and past 4 GiB, in two compute modes:

  • compute="fp8": FP8 MFMA. The relative output error is a few percent on random data, dominated by the FP8 quantization of Q.
  • compute="bf16": BF16 accuracy, at the cost of a temporary BF16 copy of the request tokens.

As for BF16 K/V, direct rows read the packed context only while the pack is cheap, and raw and packed direct give the same bits. With batch_invariant=True, FP8 results are batch-invariant like BF16 ones. BF16 calls give the same bits as main, and long-context chunks run faster.

Validation and unverified scope

MI308X (gfx942, 80 CUs), FlyDSL 0.5.0.

  • python op_tests/test_flydsl_qsa_sparse_prefill.py: all rows pass, 295 checkAllclose comparisons, none skipped. With CU_NUM=304 (the plans of a 304-CU gfx942 such as MI300X) all rows pass too; route expectations are asserted only on 80 CUs.
    • FP8 batch invariance: in fp8_batch_invariance_token (H3; a 768-row prefill, a 2048-row chunk after 30000 tokens and a 64-row extend, mixing union tiles and direct rows), every request alone with batch_invariant=True is bitwise equal to its rows in the batch.
  • FP8 against the previous head (b2b1ab22a): 54 outputs: every FP8 row's inputs, packed and through a NaN-filled pool, the 4 GiB and HK16 rows, and five long-context batches, per tensor and per token. The 30 with per-tensor scales or compute="bf16" are bitwise equal, and so are the two of fp8_large_logits_prefill_768_token. The other 22, per-token FP8, change only by the rounding of S * (k_scale * c): 0.007–0.094% of the elements, in 1.4–5.4% of the (row, head) vectors; per output, the changed vectors move by under 0.06% on average (norm-relative) and at most 9.5%. On the changed vectors of two long-context batches, the error against the FP32 reference stays the same (mean 0.0465 → 0.0466 and 0.0452 → 0.0452, worst 0.1318 → 0.1318 and 0.0924 → 0.0925), and of the op test's 221 reported error values, 217 are unchanged and the other 4 (per-token FP8) move by at most 5e-5. All 54 stay equal with every direct row forced raw, and the 46 smaller ones also with raw direct's 64-bit loads forced on every pool.
  • Masked raw V offsets: the review's pool (HK 1536, P 10920, one query over 2045 tokens, unused rows NaN) gives no NaN and the bits of the packed call (b2b1ab22a: 131328 NaN elements), as do HK 1393 and HK 1366 (64-bit loads).
  • Tiny Q and large K scales: the review's repro (one query, Q = 2**-101, k_scale = 2**100, logits 0 and 8) gives 1.0, the FP32 reference 0.999665 rounded to BF16, per tensor and per token. So does Q = 2**e for every e from -101 to -133 (the smallest BF16 subnormal) with compensating K and softmax scales, and Q = 1 with K scales from 2**100 to 2**124 under a matching softmax scale. b2b1ab22a gives 0.5 for every such tiny Q, and NaN for Q = 1 from per-token K scales of 2**113. On a 4096-row prefill (H12, union and residual direct), Q × 2**-g with K scales × 2**g gives Q's bits for every g up to 110 and stays within FP8_TOL for every g up to 126, for both scale layouts.
  • Performance against b2b1ab22a: FP8 call time is unchanged: geomean 0.996 for per-token and for per-tensor scales (13 layouts each, three alternating rounds, every layout within ±2%). The per-token union kernel's VGPRs go from 385 to 382; the other FP8 kernels' resources are unchanged.
  • K/V past 4 GiB: 16 union configurations (a 4096-row prefill at H12 and a mixed batch at H6; HK1/HK2, both scale layouts, pool pages above or straddling 4 GiB) and 5 direct-only batches (HK1/HK2, both scale layouts; raw by 64-bit loads), with the default rule and with every direct row forced raw, are bitwise equal to the same calls on packed K/V. With the earlier revision's union kernel and the rejection removed, the 16 union configurations gave NaN rows.
  • Hazards: out pre-filled with NaN, 10 quiet calls and 10 calls under concurrent GEMMs bitwise equal, and the FP32 reference on sample rows. 80 configurations (20 layouts, both scale layouts, packed and through kv_slots) pass with the default rule and 80 with every direct row raw.
  • Mutation check: with K3's chunked task order switched off at run time, fp8_hk16_k3_chunks_token fails (rows of out left unwritten: 2949120 elements differ between two calls). Without Q's amax floor, fp8_uniform_ragged_3_random_token fails: its tiny Q rows give NaN. With the per-token V scale clamp's upper bound lowered to 2**59, it fails too. With the FP8 direct launchers binding the arguments of the call that built them, fp8_workspace_key_ragged_4 fails: its workspaces keep that call's Q, K/V, scales, slot table and out alive. With Q rows of amax below 2**-100 quantized to 0 (b2b1ab22a), fp8_query_reference_prefill_4096_token fails: Q × 2**-104 differs from Q in 99.9% of the elements. With only that fixed, per-token scores taken as (S * k_scale) * c fail it at Q × 2**-124 (NaN).
  • BF16 against main ([FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance #8148): 34 outputs (17 layouts, each at the default and a new softmax scale) are bitwise equal.
  • Mode switching: default and batch_invariant=True calls interleaved on one stream (4 batch layouts, BF16 and FP8 per token, 3 calls each) give the same bits as each mode alone.
  • SGLang end to end: Qwen3.8-Flash-Next with an FP8 KV cache and MTP, TP2 on two MI308X. On every rank this entry serves the 12 target QSA layers (FP8 K/V, compute="fp8") and the MTP draft's (BF16 K/V).
    • Against the earlier revision (dca8eb2e8), two rounds each on fresh servers: GSM8K (1319 questions, 5-shot, T = 0) 0.9787 against 0.9783, accept length 3.132 against 3.130. The output throughput of the customer load (256 requests of 12000/350 tokens at concurrency 8) and of random 12000/350 requests at concurrency 1, 2, 4 and 8 changes by −0.5% to +0.8%, and by at most 1.8% in any pair of rounds.
    • In-server check at 1M context: requests of 9 to 999648 tokens, 32 concurrent requests of about 12k tokens, and a 999000-token request that reused 884736 cached tokens. Each distinct call layout this entry served (7878 per rank) was compared once with an FP32 reference on the dequantized K/V. Against the reference with the same FP8 Q, the FP8 layers' mean relative error averages 0.42% (max 1.03%), and their worst row's 3.45% (max 5.85%); the check's limits are 5% and 20%.
    • Deterministic inference (batch_invariant=True on every QSA layer): GSM8K's first 200 questions score 0.98.
  • Rebased onto main after [FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance #8148 and [FlyDSL] [QSA] qsa_sparse_prefill: public selection-width and byte-limit query #8083 merged: [FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance #8148's commit left the diff, and the other files equal the previous head 10a72a822 except for [FlyDSL] [QSA] qsa_sparse_prefill: public selection-width and byte-limit query #8083's selection-width queries in the entry and aiter/ops/qsa.py, merged unchanged. On the rebased head the op test passes again (131 rows, 294 checks, none skipped) and tests/test_qsa_sparse_prefill_support.py passes (10 tests).
  • Lint: black --check (26.10.1) and ruff check (0.16.0) on the changed files are clean.
  • Not verified:
    • MI300X and other gfx942 parts (no hardware): only their plans were emulated with CU_NUM. They log the tuning warning.
    • Pools past 4 GiB in SGLang: at TP2 even the 1M-context configuration's FP8 K pool is 0.87 GiB per layer (3663424 tokens), so they were verified at the op level only.
    • SGLang end to end on this head: its per-token FP8 outputs differ from the head measured above only by the rounding of S * (k_scale * c).

PR-specific question

What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test? (the question the self-review rules select for changes under op_tests/)

  • op_tests/test_flydsl_qsa_sparse_prefill.py (26 FP8 rows). Before this PR the entry took BF16 K/V only, so every FP8 row fails there, and no BF16 row runs the FP8 pack, the FP8 kernels or the scale paths. Beyond that, each special row targets one failure:
    • Q and out past 2 GiB (fp8_hk16_prefill_24576_token) fails with a signed shift in the residual merge (worst error 21.13).
    • More than 4096 union task entries (fp8_hk16_k3_chunks_token) fails without the K3 chunk ordering: rows of out are left unwritten.
    • K/V past 4 GiB (fp8_4g_packed_token, fp8_pool_4g_ragged_4_tensor) fail with 32-bit offsets over the K/V or the pool.
    • The rows in FP8_RAW_CHECKED fail if raw direct's operands or scale terms differ from the pack's by one bit.
    • The attention sink over a flat tail fails without the probability bias (E4M3 underflow).
    • Tiny Q rows (fp8_uniform_ragged_3_random_token, amax about 2**-121) give NaN without Q's amax floor, and its V scales up to 2**60 fail with a narrower V scale clamp.
    • Tiny Q under K scales that restore its scores (fp8_query_reference_prefill_4096_token) fails when Q rows below an absolute amax floor quantize to 0 (b2b1ab22a: 99.9% of the elements differ from Q's), and when per-token scores take (S * k_scale) * c (NaN).
    • The other special rows pin per-token V scale exactness, the FP8-Q reference, large logits, graph replay at an unseen scale, the workspace key, entry validation and the public signature, batch invariance, group 16 and BQ42's 64-bit membership.
    • The 8 pairwise rows cover all 56 value pairs of compute × scale layout × route × input × group. On MI308X's 80 CUs, routes() asserts the path each row takes.

Changed op tests

  • op_tests/test_flydsl_qsa_sparse_prefill.py: 26 FP8 rows, each run once at its own group.
    • Pairwise rows (8). Compute × scale layout × route (union, packed direct) × input (packed, kv_slots) × group: all 56 value pairs in 8 rows.
    • Special rows:
      • K/V past 4 GiB: packed, with a request crossing 4 GiB (its direct rows read raw), and a 4.5 GiB pool whose pages lie past 4 GiB;
      • raw direct: four rows also run every direct row raw (packed and pooled K/V, both scale layouts, HK2, group 16, and the 4.5 GiB pool by 64-bit loads) and must give the same bits;
      • an attention sink over a flat tail, which needs the probability bias to avoid E4M3 underflow (union and direct);
      • per-token V scale exactness up to the clamp bounds 2**-60 and 2**60, with zero Q rows and tiny ones (amax about 2**-121, where 240 / amax overflows FP32);
      • the FP8-Q reference with sharp scores, and tiny Q under K scales that restore its scores;
      • large logits;
      • graph replay with rewritten inputs and an unseen softmax scale;
      • workspace-key separation of FP8 modes, and workspaces that keep none of their first call's tensors alive;
      • entry validation (also K passed as the same tensor as Q) and the exact public signature;
      • batch invariance with batch_invariant=True: a batch mixing union and direct requests, each bitwise equal to its run alone (by default the first two requests alone split their key ranges);
      • group 16 (direct and union);
      • BQ42 with 64-bit membership;
      • Q and out past 2 GiB, which exercises the residual merge's unsigned offset;
      • more than 4096 union task entries (fp8_hk16_k3_chunks_token: H192/HK16, 2620 rows, 4192 entries).
    • No BF16 row covers any of these, and every FP8 row covers a value pair or a failure no other FP8 row does. Route expectations depend on the CU count, so they are asserted only on 80-CU parts (MI308X); elsewhere the numerical checks still run.

@luocheng25
luocheng25 requested review from a team and a balanced review from Copilot November 18, 2026 02:32
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 8149 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved issues can make empty-query calls allocate unnecessary BF16 K/V copies and exhaust memory, while per-token scale clamping can cause a 50% output error.

2 open issues
What changed in this PR

Adds FP8 K/V support to FlyDSL QSA sparse prefill on gfx942, enabling consumers to use FP8 KV caches with either FP8 computation or BF16 dequantization.

Changes:

  • Extends the public API with scale tensors and compute-mode selection.
  • Adds FP8 packing, query quantization, direct attention, and routing support for long contexts.
  • Builds on #8148’s shared helpers, runtime softmax scale, and opt-in batch invariance.
File Description
aiter/​ops/​qsa.py Exposes and forwards the new API options.
aiter/​ops/​flydsl/​qsa_sparse_prefill.py Validates FP8 inputs and manages computation and workspaces.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_union.py Uses runtime scaling and shared BF16 helpers.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_prepare.py Adds FP8 routing, task splitting, residual planning, and sort skipping.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_direct.py Adopts the shared BF16 direct-attention loop.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_direct_packed.py Shares direct-loop logic across packed and raw paths.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_direct_fp8.py Implements FP8 packing, quantization, and packed/raw direct attention.
aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_common.py Adds FP8 primitives and calibration; consolidates shared helpers.
aiter/​ops/​flydsl/​kernels/​qsa/​__init__.py Updates package documentation to mention FP8 K/V.

Review effort: Balanced

Comment thread aiter/ops/flydsl/qsa_sparse_prefill.py Resolved
Copilot AI balanced review requested due to automatic review settings November 18, 2026 03:14
@aiter-bot

aiter-bot commented Nov 18, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision dbfc4bf97850 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

`qsa_sparse_prefill` accepts FP8 K/V with per-token or per-tensor scales, packed or through `kv_slots` and past 4 GiB, in two compute modes:

- `compute="fp8"`: FP8 MFMA. The relative output error is a few percent on random data, dominated by the FP8 quantization of Q.
- `compute="bf16"`: BF16 accuracy, at the cost of a temporary BF16 copy of the request tokens.

As for BF16 K/V, direct rows read the packed context only while the pack is cheap, and raw and packed direct give the same bits. With `batch_invariant=True`, FP8 results are batch-invariant like BF16 ones. BF16 calls give the same bits as main, and long-context chunks run faster.

Validation and unverified scope

MI308X (gfx942, 80 CUs), FlyDSL 0.5.0.

- **`python op_tests/test_flydsl_qsa_sparse_prefill.py`:** all rows pass, 295 `checkAllclose` comparisons, none skipped. With `CU_NUM=304` (the plans of a 304-CU gfx942 such as MI300X) all rows pass too; route expectations are asserted only on 80 CUs.
  - FP8 batch invariance: in `fp8_batch_invariance_token` (H3; a 768-row prefill, a 2048-row chunk after 30000 tokens and a 64-row extend, mixing union tiles and direct rows), every request alone with `batch_invariant=True` is bitwise equal to its rows in the batch.
- **FP8 against the previous head (`b2b1ab22a`):** 54 outputs: every FP8 row's inputs, packed and through a NaN-filled pool, the 4 GiB and HK16 rows, and five long-context batches, per tensor and per token. The 30 with per-tensor scales or `compute="bf16"` are bitwise equal, and so are the two of `fp8_large_logits_prefill_768_token`. The other 22, per-token FP8, change only by the rounding of `S * (k_scale * c)`: 0.007–0.094% of the elements, in 1.4–5.4% of the (row, head) vectors; per output, the changed vectors move by under 0.06% on average (norm-relative) and at most 9.5%. On the changed vectors of two long-context batches, the error against the FP32 reference stays the same (mean 0.0465 → 0.0466 and 0.0452 → 0.0452, worst 0.1318 → 0.1318 and 0.0924 → 0.0925), and of the op test's 221 reported error values, 217 are unchanged and the other 4 (per-token FP8) move by at most 5e-5. All 54 stay equal with every direct row forced raw, and the 46 smaller ones also with raw direct's 64-bit loads forced on every pool.
- **Masked raw V offsets:** the review's pool (HK 1536, P 10920, one query over 2045 tokens, unused rows NaN) gives no NaN and the bits of the packed call (`b2b1ab22a`: 131328 NaN elements), as do HK 1393 and HK 1366 (64-bit loads).
- **Tiny Q and large K scales:** the review's repro (one query, Q = `2**-101`, k_scale = `2**100`, logits 0 and 8) gives 1.0, the FP32 reference 0.999665 rounded to BF16, per tensor and per token. So does Q = `2**e` for every e from -101 to -133 (the smallest BF16 subnormal) with compensating K and softmax scales, and Q = 1 with K scales from `2**100` to `2**124` under a matching softmax scale. `b2b1ab22a` gives 0.5 for every such tiny Q, and NaN for Q = 1 from per-token K scales of `2**113`. On a 4096-row prefill (H12, union and residual direct), Q × `2**-g` with K scales × `2**g` gives Q's bits for every g up to 110 and stays within `FP8_TOL` for every g up to 126, for both scale layouts.
- **Performance against `b2b1ab22a`:** FP8 call time is unchanged: geomean 0.996 for per-token and for per-tensor scales (13 layouts each, three alternating rounds, every layout within ±2%). The per-token union kernel's VGPRs go from 385 to 382; the other FP8 kernels' resources are unchanged.
- **K/V past 4 GiB:** 16 union configurations (a 4096-row prefill at H12 and a mixed batch at H6; HK1/HK2, both scale layouts, pool pages above or straddling 4 GiB) and 5 direct-only batches (HK1/HK2, both scale layouts; raw by 64-bit loads), with the default rule and with every direct row forced raw, are bitwise equal to the same calls on packed K/V. With the earlier revision's union kernel and the rejection removed, the 16 union configurations gave NaN rows.
- **Hazards:** `out` pre-filled with NaN, 10 quiet calls and 10 calls under concurrent GEMMs bitwise equal, and the FP32 reference on sample rows. 80 configurations (20 layouts, both scale layouts, packed and through `kv_slots`) pass with the default rule and 80 with every direct row raw.
- **Mutation check:** with K3's chunked task order switched off at run time, `fp8_hk16_k3_chunks_token` fails (rows of `out` left unwritten: 2949120 elements differ between two calls). Without Q's amax floor, `fp8_uniform_ragged_3_random_token` fails: its tiny Q rows give NaN. With the per-token V scale clamp's upper bound lowered to 2**59, it fails too. With the FP8 direct launchers binding the arguments of the call that buil

[truncated in readiness report; see the PR description for the full answer]

PR-specific question

*What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?* (the question the self-review rules select for changes under `op_tests/`)

- **`op_tests/test_flydsl_qsa_sparse_prefill.py`** (26 FP8 rows). Before this PR the entry took BF16 K/V only, so every FP8 row fails there, and no BF16 row runs the FP8 pack, the FP8 kernels or the scale paths. Beyond that, each special row targets one failure:
  - Q and out past 2 GiB (`fp8_hk16_prefill_24576_token`) fails with a signed shift in the residual merge (worst error 21.13).
  - More than 4096 union task entries (`fp8_hk16_k3_chunks_token`) fails without the K3 chunk ordering: rows of `out` are left unwritten.
  - K/V past 4 GiB (`fp8_4g_packed_token`, `fp8_pool_4g_ragged_4_tensor`) fail with 32-bit offsets over the K/V or the pool.
  - The rows in `FP8_RAW_CHECKED` fail if raw direct's operands or scale terms differ from the pack's by one bit.
  - The attention sink over a flat tail fails without the probability bias (E4M3 underflow).
  - Tiny Q rows (`fp8_uniform_ragged_3_random_token`, amax about 2**-121) give NaN without Q's amax floor, and its V scales up to 2**60 fail with a narrower V scale clamp.
  - Tiny Q under K scales that restore its scores (`fp8_query_reference_prefill_4096_token`) fails when Q rows below an absolute amax floor quantize to 0 (`b2b1ab22a`: 99.9% of the elements differ from Q's), and when per-token scores take `(S * k_scale) * c` (NaN).
  - The other special rows pin per-token V scale exactness, the FP8-Q reference, large logits, graph replay at an unseen scale, the workspace key, entry validation and the public signature, batch invariance, group 16 and BQ42's 64-bit membership.
  - The 8 pairwise rows cover all 56 value pairs of compute × scale layout × route × input × group. On MI308X's 80 CUs, `routes()` asserts the path each row takes.

Changed op tests

- **`op_tests/test_flydsl_qsa_sparse_prefill.py`:** 26 FP8 rows, each run once at its own group.
  - **Pairwise rows (8).** Compute × scale layout × route (union, packed direct) × input (packed, `kv_slots`) × group: all 56 value pairs in 8 rows.
  - **Special rows:**
    - K/V past 4 GiB: packed, with a request crossing 4 GiB (its direct rows read raw), and a 4.5 GiB pool whose pages lie past 4 GiB;
    - raw direct: four rows also run every direct row raw (packed and pooled K/V, both scale layouts, HK2, group 16, and the 4.5 GiB pool by 64-bit loads) and must give the same bits;
    - an attention sink over a flat tail, which needs the probability bias to avoid E4M3 underflow (union and direct);
    - per-token V scale exactness up to the clamp bounds `2**-60` and `2**60`, with zero Q rows and tiny ones (amax about `2**-121`, where 240 / amax overflows FP32);
    - the FP8-Q reference with sharp scores, and tiny Q under K scales that restore its scores;
    - large logits;
    - graph replay with rewritten inputs and an unseen softmax scale;
    - workspace-key separation of FP8 modes, and workspaces that keep none of their first call's tensors alive;
    - entry validation (also K passed as the same tensor as Q) and the exact public signature;
    - batch invariance with `batch_invariant=True`: a batch mixing union and direct requests, each bitwise equal to its run alone (by default the first two requests alone split their key ranges);
    - group 16 (direct and union);
    - BQ42 with 64-bit membership;
    - Q and out past 2 GiB, which exercises the residual merge's unsigned offset;
    - more than 4096 union task entries (`fp8_hk16_k3_chunks_token`: H192/HK16, 2620 rows, 4192 entries).
  - No BF16 row covers any of these, and every FP8 row covers a value pair or a failure no other FP8 row does. Route expectations depend on the CU count, so they are asserted only on 80-CU parts (MI308X); elsewhere the numerical checks still run.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Cached closures can indefinitely retain large caller-owned tensors, while the absolute Q floor can erase significant logits and produce incorrect attention outputs.

2 open issues
2 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 18, 2026 03:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Aliased Q/K inputs can bypass dtype validation and cause BF16 storage to be read as FP8, while scale handling can produce NaNs or erase significant logits.

1 open issue
2 previously missed issues

In code that hasn't changed since last review

High severity Validate K dtype by argument position, even when it aliases Q

aiter/​ops/​flydsl/​qsa_sparse_prefill.py:469

Using object identity to distinguish Q from K/V lets mixed dtypes bypass validation when K is the same tensor object as Q. With q=k as contiguous BF16 [2,1,256], FP8 V of the same shape, and valid scales, _fp8_layout selects FP8 through V, but both Q and K pass this check as BF16. The FP8 kernels then interpret BF16 K storage as FP8 instead of rejecting the call. Please select the expected dtype by argument position so K/V must both be FP8 even when inputs alias.

Medium severity Apply K scale after combining it with the query factor

aiter/​ops/​flydsl/​kernels/​qsa/​sparse_prefill_direct_fp8.py:788

Multiplying the FP8 dot by per-token k_scale first can overflow FP32 and produce NaNs even when the final logit is finite. For a single-token [1,1,256] call with Q=2**-10, K8=V8=1, k_scale=[[2**120]] and v_scale=[[1]], the dot is 61440 and this intermediate becomes infinity, although the scaled score is about 3e34 and the expected output is 1. Combine the query/softmax factor with the K scale before applying it to the dot, address the same ordering in sparse_prefill_union_fp8.py:399-400 and its prologue, and add a tensor/token scale-equivalence regression.

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 18, 2026 04:32
@luocheng25

Copy link
Copy Markdown
Contributor Author

On the two previously missed issues in the latest review:

  • K aliasing Q: fixed in 10a72a8. Dtypes are now checked by argument position, and fp8_input_errors covers the aliased call.
  • Per-token K scale order: not changing it. The product overflows only for per-token K scales above about 2**104 (K values above about 5e33), and SGLang passes k_scale = 1. Reordering would change the rounding of every per-token result.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new FP8 pipelines, cross-CTA merging, and >4 GiB addressing lack head-matched gfx942 correctness and paired performance validation, which cannot be run in this review environment.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

luocheng25 and others added 5 commits November 19, 2026 07:12
qsa_sparse_prefill accepts FP8 K/V (E4M3FNUZ, gfx942's dtypes.fp8) with FP32
scales per tensor ([1]) or per token and KV head ([N, HK]; [P, HK] with
kv_slots), packed or through kv_slots, also past 4 GiB (new keyword-only
k_scale, v_scale and compute):

- compute="fp8" (default) runs FP8 MFMA union and direct kernels: the pack
  launch quantizes Q per (row, head), rows of amax below 2**-100 to 0
  (240 / amax overflows FP32 below about 2**-120); probabilities are FP8.
- compute="bf16" dequantizes the request tokens to BF16 and runs the BF16
  kernels.

As with BF16 K/V, the union kernel reads the raw K/V, and direct rows read the
context packed per call while it fits the platform's budget (past it, FP8
still packs up to 320 tokens per query row), else the raw K/V; with a union
plan the pack runs only when some tile goes direct. Each four-token block is
read from its own 64-bit base (a buffer per block in the union kernel and the
pack, 64-bit loads for raw direct over a slot-table pool past 4 GiB), so K/V
and pools may exceed 4 GiB. Raw and packed direct give the same bits.

The FP8 kernels follow the BF16 kernels' rules: a runtime softmax scale, the
shared QK/PV/rescale helpers, no non-empty inline asm, and FlyDSL's stable API
outside the low-level section of sparse_prefill_common.py, which gains the FP8
primitives. FP8 plans add route calibrations, core/residual union tiles
(H12/H6) whose residual blocks the direct kernel merges by log-sum-exp, and,
with fewer union tasks than CUs, a split of the longest tasks' key ranges over
two CTAs. batch_invariant=True also covers FP8: per-request plans, no split.

- A union K load reads one block whole and a wave reads the same blocks for K
  and V; V is transposed in registers into the V^T LDS tile, and the buffer
  records of whole tiles are constant (the kernel is issue bound).
- Raw direct loads K quarters (swapped between lanes by ds_swizzle) and V rows
  (transposed as the pack does), and computes the per-token scale terms as
  the pack does.
- The pack stores K token-minor, so each 4-lane quad of a direct K load
  reads 64 contiguous bytes; FP32-to-BF16 output rounds to nearest even.
- Byte offsets past 2 GiB use unsigned shifts (per-token scale records, the
  residual merge's union LSE), and the FP8 pack buffer is a byte scratch.
- With more task entries than one K3 order CTA sorts, K3 places every
  chunk's runnable entries before all idle ones: the FP8 union kernel ends a
  CTA's task loop at its first idle entry.
- K1 skips the sort of rows whose blocks already ascend.

The op test adds 26 FP8 rows: 8 pairwise rows over compute, scale layout,
route, input and group, and rows for K/V past 4 GiB (packed, and a pool whose
pages lie past it), an attention sink, per-token V scale exactness (with zero
and tiny Q rows), the FP8-Q reference, large logits, graph replay, the
workspace key, entry validation, batch invariance, group 16, BQ42, Q and out
past 2 GiB, and K3's chunked task order. Four rows also run every direct row
on the raw K/V and must give the same bits. Route expectations are asserted
on MI308X's 80 CUs only, since
plans and routes follow the CU count.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 19, 2026 07:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical masked FP8 value-offset overflow can read unused pool rows and contaminate outputs with NaNs, while test synchronization and reference-comparison gaps weaken verification.

3 open issues

Review effort: Balanced

zhiding512
zhiding512 previously approved these changes Nov 19, 2026

@fsx950223 fsx950223 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head b2b1ab2. Eleven targeted gfx942 op cases and ten support-query tests passed, but two accepted-input correctness defects reproduce on MI308X with FlyDSL 0.5.0. Detailed commands and logs are preserved in validation.md, gfx942-tests.log, and gfx942-controls.log.

[P2] Apply the V token displacement before masking its offset — aiter/ops/flydsl/kernels/qsa/sparse_prefill_direct_fp8.py:547

In the non-WIDE pooled RAW path, adding the token displacement after selecting env.oob can wrap a masked address into the pool. Reproduced with HK=1536, P=10920, one query over 2045 tokens, per-tensor unit scales, and slots 4096..6140. For KV head 0, the sentinel 4293918720 plus 31536256 wraps to 131072. All selected K/V are finite, but NaNs in unused pool row 0 contaminate 131,328 output elements. Changing only that unused row to 1 produces the expected all-one output. Compute the full token offset before applying v_valid so masked loads retain the out-of-range sentinel.

[P2] Preserve tiny nonzero Q rows when scales amplify their logits — aiter/ops/flydsl/kernels/qsa/sparse_prefill_common.py:995

The absolute 2**-100 floor silently zeros representable Q rows even when their logits are significant. On gfx942, Q[1,1,256]=2**-101, two K8/V8 rows filled respectively with 0 and 1, k_scale=[2**100], v_scale=[1], and prefix_lens=(1,) produce logits [0,8] at the default softmax scale. The FP32 reference returns 0.999665 and compute="bf16" returns 1.0, while compute="fp8" returns 0.5 everywhere. These finite inputs and scales pass the public validation, and 240/amax is finite here. Use overflow-safe normalization that preserves nonzero rows rather than this absolute floor.

Validation:

  • PASS on local and hjbog-srdc-39.amd.com/sixifang_dev: git rev-parse HEAD
    Both isolated checkouts verified b2b1ab2. Container probe verified gfx942, MI308X, 80 CUs; imports resolved to the isolated source and FlyDSL 0.5.0.
  • PASS on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: ssh -o BatchMode=yes -o ConnectTimeout=10 -o RequestTTY=no -o ControlMaster=no -o ControlPath=none hjbog-srdc-39.amd.com 'docker exec -i sixifang_dev bash' < run-gfx942.sh
    Exit 0. Ten selected op cases passed, covering both compute modes, raw/packed equivalence, split merging, over-4096 task ordering, graph replay, workspace reuse, input validation, and batch invariance. Support pytest: 10 passed. No cases skipped. Complete environment, lock, timeout, and test commands are in run-gfx942.sh.
  • FAIL on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: flock -w 60 /workspace/codex-pr-review-8149-b2b1ab22/gpu.lock timeout 300 /workspace/codex-pr-review-8149-b2b1ab22/venv/bin/python /workspace/codex-pr-review-8149-b2b1ab22/repro-control.py
    Exit 1 from the regression assertion. Tiny Q: FP8 output 0.5 versus FP32 0.9996646643; BF16 control 1.0. Masked pool: 131,328 NaNs; changing only unused pool row 0 yields all 1.0 with zero NaNs. Recorded in gfx942-controls.log.
  • PASS on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: flock -w 60 /workspace/codex-pr-review-8149-b2b1ab22/gpu.lock timeout 300 /workspace/codex-pr-review-8149-b2b1ab22/venv/bin/python op_tests/test_flydsl_qsa_sparse_prefill.py -c fp8_pool_4g_ragged_4_tensor
    Exit 0. The 4.5 GiB pool matched packed K/V and forced-raw direct bitwise; repeated output matched bitwise. Mean reference error 0.043724, worst 0.126116. No skip.
  • SKIP on gfx950: GPU kernel validation
    This entry supports gfx942 only. The support-query tests passed their gfx950 rejection checks; no gfx950 kernel validation is claimed.

Remaining validation:

  • Did not independently run the full op sweep, Q/output past 2 GiB cases, other gfx942 hardware, end-to-end serving, or paired performance benchmarks.
  • The base does not implement FP8 K/V, so the reproductions use independent FP32 references and targeted controls rather than a base FP8 comparison.

Automated Codex review of commit b2b1ab22a911.

- Raw direct: add the V token offsets before masking, so masked loads stay out of range.
- FP8 Q rows of amax below Q_MIN (now 2**-118) quantize as if their amax were Q_MIN
  instead of to 0, and per-token scores take S * (k_scale * c), so K scales that restore
  tiny rows' logits no longer overflow S * k_scale.
- FP8 query test: tiny Q under K scales that restore its scores.
- FP8 graph test: wait for the growth inputs on the graph stream.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 03:46
@luocheng25

Copy link
Copy Markdown
Contributor Author

@fsx950223 Thanks for the review. Both reproduce on MI308X, and dbfc4bf fixes them:

  1. Masked raw V offsets. The V token offsets are now added before v_valid masks them, so masked loads keep the out-of-range sentinel. Your configuration (HK 1536, P 10920, slots 4096..6140) gives no NaN (before: 131328). It needs HK ≥ 1366, far above real models (HK is generally below 100), but the mask should not depend on that.
  2. Tiny Q rows. Rows of amax below 2**-118 now quantize as if their amax were 2**-118 (240 / amax overflows FP32 below about 2**-120, and 2**-118 / 240 is still a normal FP32 scale), so nonzero rows stay nonzero. Keeping them exposed an overflow on the per-token path: S, the FP8 dot product, is up to about 2**24, so S * k_scale overflows FP32 for K scales past 2**104. Per-token scores now take S * (k_scale * c). This also fixes a NaN that b2b1ab22a gave with ordinary Q, e.g. Q = 1 with per-token K scales from 2**113 under a matching small softmax scale.
    • Your repro gives 1.0 (the FP32 reference 0.999665 rounded to BF16), per tensor and per token, as does Q = 2**e for every e from -101 to -133 with compensating scales.
    • fp8_query_reference_prefill_4096_token now also checks Q × 2**-104 with K scales × 2**104 (Q's bits) and Q × 2**-124 with K scales × 2**124 (within FP8_TOL). b2b1ab22a fails the first, and the Q fix alone fails the second (NaN).
    • Apart from Q rows of amax below 2**-100, per-tensor outputs are bitwise unchanged, and per-token ones change only by rounding (under 0.1% of the elements): of the op test's 221 reported error values, 217 are unchanged and the other 4 move by at most 5e-5. Call time is unchanged (geomean 0.996).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate FP8 scaling underflow and overflow risks that can invalidate otherwise representable results, supported by scalar checks but not GPU verification.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

@luocheng25
luocheng25 requested a review from fsx950223 November 20, 2026 04:09

@fsx950223 fsx950223 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head dbfc4bf. Both earlier blocking findings are fixed and independently pass their gfx942 reproductions. Sixteen targeted op cases, ten support-query tests, and a BF16 base comparison passed. No remaining blocking defect found.

Validation:

  • PASS on local and hjbog-srdc-39.amd.com/sixifang_dev: git rev-parse HEAD
    Isolated local and remote source checkouts verified dbfc4bf. Container probe verified gfx942, MI308X, 80 CUs, FlyDSL 0.5.0, and imports from the intended checkout.
  • PASS on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: ssh -o BatchMode=yes -o ConnectTimeout=10 -o RequestTTY=no -o ControlMaster=no -o ControlPath=none hjbog-srdc-39.amd.com 'docker exec -i sixifang_dev bash' < run-gfx942.sh
    Exit 0. Both previous regressions passed: tiny Q returned 1.0 versus FP32 0.9996646643; the HK1536 masked pool produced zero NaNs and matched the clean-pool control bitwise. Twelve targeted op cases and ten support-query tests passed without skips. Commands and output are preserved in run-gfx942.sh and gfx942-validation.log.
  • PASS on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: ssh -o BatchMode=yes -o ConnectTimeout=10 -o RequestTTY=no -o ControlMaster=no -o ControlPath=none hjbog-srdc-39.amd.com 'docker exec -i sixifang_dev bash' < run-extra.sh
    Exit 0. Four additional cases passed without skips: BQ42 membership, pooled per-token BF16 compute, HK2/group16 raw/packed equivalence, and pooled FP8 graph replay after scratch growth. See gfx942-extra.log.
  • PASS on hjbog-srdc-39.amd.com/sixifang_dev, GPU 1: ssh -o BatchMode=yes -o ConnectTimeout=10 -o RequestTTY=no -o ControlMaster=no -o ControlPath=none hjbog-srdc-39.amd.com 'docker exec -i sixifang_dev bash' < run-bf16-compare.sh
    Exit 0. BF16 outputs matched base 2088358 bitwise at softmax scales 0.0625 and 0.11. Ascending and shuffled selections also matched bitwise on both commits. Separate source trees and compilation caches were used. See gfx942-bf16-compare.log.
  • SKIP on gfx950: GPU kernel validation
    This entry supports gfx942 only. Downloaded CI shard 6 explicitly skipped this op on gfx950; its green wrapper result is not counted as kernel validation. Support-query tests passed unsupported-architecture rejection checks.

Remaining validation:

  • Did not independently run the full op sweep, Q/output past 2 GiB cases, other gfx942 hardware, end-to-end serving, or paired performance benchmarks.
  • Random FP8 accuracy checks use the suite's norm-relative tolerances; exact comparisons cover paths expected to agree.
  • Initial virtual-environment probes lacked torch; this was resolved before GPU testing. Failure logs are retained.
  • Detailed commands and logs are preserved in the task directory and summarized in validation.md.

Automated Codex review of commit dbfc4bf97850.

@fsx950223
fsx950223 dismissed their stale review November 21, 2026 01:10

Superseded by validated approval of commit dbfc4bf: #8149 (review)

@coderfeli
coderfeli merged commit c21216d into ROCm:main Nov 23, 2026
5 checks passed
eppaneamd added a commit that referenced this pull request Nov 23, 2026
Brings in #8148 (runtime softmax scale, shared QK/PV/rescale helpers,
stable FlyDSL API, batch_invariant) and #8149 (FP8 K/V on gfx942, K3
runnable-first chunks, task splits, core tiles). gfx942 runs main's
kernels; gfx950 runs this PR's kernels in main's forms (runtime
SCALE_LOG2, the prim wrappers and counted LDS ledger of
sparse_prefill_common, kernel_attrs()).

- Raw direct (_Raw) takes K/V row bytes (KV_STRIDE * 2) where main
  passed KV heads; K3's route cost reads the first three terms of the
  5-term route model (main unpacked exactly four) and _route_choice
  loops over len(limits).
- K3 keeps the Int32 chunk-local sort key under main's CHUNKED, and
  both CHUNKED variants compile on a key's first compile.
- One operand rule list (_check_call): main's compute, FP8 scale and
  batch_invariant rules beside the scale, stride and row rules;
  qsa_sparse_prefill_problem and the qsa.py wrappers take
  batch_invariant, k_scale, v_scale and compute. FP8 K/V of any FP8
  dtype are rejected off gfx942, right after the device rule: #8149's
  kernels are E4M3FNUZ, and gfx950's dtypes.fp8 is E4M3FN. With
  compute="bf16" the per-request K span rule applies with a slot table
  too: the op then runs packed BF16 copies of the FP8 K/V, so
  qsa_sparse_prefill_problem reports what that call raises.
- batch_invariant=True on gfx950: packed direct compiles the K16 loop
  raw direct runs, so packed and raw K/V give the same bits; the
  default mode keeps the K32 packed loop.
- Platform: the gfx950 entry and route_all_or_none; FP8 routes on
  gfx942 only; overrides of a switch are written 0 or 1.
- Tests: the op test is main's with this PR's suites appended (their
  layouts seeded by name; FP8 suites on gfx942, a rejection case
  elsewhere); the CPU tests cover main's rules.

The warm-up does not compile main's batch-invariant and FP8 variants
yet; the next commit extends it.

Validated with FlyDSL 0.5.3: on gfx950 the op test, the output bits
against this branch's head and K1-K3 against main's prepare module; on
gfx942 compile-only, ISA and launch arguments against main's. On gfx950
an eager call takes 10 to 15 us more host time than on the head (main's
operand rules and launch arguments); graph replay and kernel times are
unchanged.

Signed-off-by: Rony Leppänen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants