Skip to content

[FlyDSL] Add QSA sparse prefill attention for MI308 - #6576

Merged
coderfeli merged 19 commits into
ROCm:mainfrom
luocheng25:luocheng/qsa-attn-308
Nov 4, 2026
Merged

coderfeli merged 19 commits into
ROCm:mainfrom
luocheng25:luocheng/qsa-attn-308

Conversation

@luocheng25

@luocheng25 luocheng25 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

aiter.ops.qsa.qsa_sparse_prefill: FlyDSL QSA sparse prefill/extend attention for Qwen3.8-Flash-Next
on gfx942 (MI308X), a drop-in for SGLang's native Triton sparse_gqa_fwd_interface_triton[_ck].

Reviewed revision

8df6bdb69a967291aceb91d3cf13e05436792cbf

Behavior and intent

This is a new op; existing ops are unchanged (aiter/ops/qsa.py only gains the wrapper). aiter has no
QSA prefill on gfx942 (the FlyDSL QSA decode is gfx950-only), and SGLang's Triton prefill is 2.9-11x
slower at serving shapes.

  • Each query row selects T = 256/512/768/1024 four-token blocks plus its causal tail (int32
    [M, 4T+3]). K1-K3 recover the blocks and route each query tile to one of two kernels:
    • union: the rows of a tile share the union of their blocks, with exact per-query masks;
    • direct: one query per wave, over packed four-token K/V, or over raw K/V when packing would copy
      too much.
  • K/V are either the requests' packed K/V, or a paged token pool read in place through kv_slots
    (packed token -> pool row). Reading in place removes the per-layer index_select copy (1 GiB and
    ~1.5 ms at 1M context).
  • Contexts reach 1M tokens and beyond: union tiles are built in LDS, so no scratch grows with
    tiles x KV blocks, and pools above 4 GiB are read with 64-bit addressing.

Limitations

  • gfx942 only, calibrated on the 80-CU MI308X (other CU counts use the nearest entry with a warning).
    Inference only; one GPU per process.
  • BF16 Q/K/V with head dim 256, contiguous and 16-byte aligned; at most 16 Q heads per KV head.
  • indices must be trusted indexer output: K1-K3 recover the selected blocks but do not validate
    them, and a selection outside the layout above gives wrong results, also in later calls on the
    same stream. K/V must be finite.
  • Q and each request's packed K/V may span at most 4 GiB - 1 MiB (~8.39M context tokens at HK1, ~4.19M
    at HK2); larger spans raise ValueError. The packed total and a kv_slots pool are unbounded.
  • kv_slots (int32 [N], at most 4 GiB - 1 MiB) needs each four-token block, the final partial one
    included, on four consecutive pool rows starting at a multiple of 4 (paged pools with pages a
    multiple of 4 tokens satisfy this). Slot values are not validated.
  • out must not overlap any input.
  • Graph capture needs a prior call on the same stream and layout. Captured graphs share that stream's
    scratch and must not replay concurrently.
  • Not a decode kernel: one row is slower than Triton (11.9 vs 7.5 us), and a few rows over a long
    context gain little (1.0-1.4x).

Validation and unverified scope

python op_tests/test_flydsl_qsa_sparse_prefill.py at 8df6bdb on MI308X (gfx942, 80 CUs), PyTorch
2.12.0+rocm7.14.0, FlyDSL 0.4.0:

  • 99 rows (functional, graph, kv_slots, span limit, performance) pass. Every FlyDSL output has err 0
    against an FP32 torch reference, and a request one token over either span limit raises ValueError.
  • Every kv_slots output equals the gathered packed call bit for bit (checkAllclose with
    rtol = atol = 0).

FlyDSL vs SGLang Triton, us per call including K1-K3:

Prefill tokens H12 (TP2) H6 (TP4) H3 (TP8)
1024 89 vs 284 (3.2x) 87 vs 277 (3.2x) 82 vs 276 (3.3x)
2048 199 vs 980 (4.9x) 138 vs 931 (6.8x) 138 vs 929 (6.7x)
4096 679 vs 2752 (4.1x) 336 vs 2723 (8.1x) 246 vs 2718 (11.0x)
8192 1605 vs 6440 (4.0x) 997 vs 6380 (6.4x) 631 vs 6373 (10.1x)
12000 2474 vs 9960 (4.0x) 1850 vs 9871 (5.3x) 1071 vs 9864 (9.2x)
16384 4231 vs 13959 (3.3x) 2834 vs 13829 (4.9x) 1956 vs 13825 (7.1x)
32768 9915 vs 29050 (2.9x) 8477 vs 28783 (3.4x) 7100 vs 28749 (4.0x)

Other shapes (H12/H6/H3 where three values are given):

  • Chunked prefill over 31k-132k context: 3.1-13.4x faster than Triton; ragged batches: 4.5-6.4x;
    HK16 (4096 queries over a 12k context): 2.4-3.2x.
  • Nine 1M-token requests (eight with 2 queries, then a 1024-query chunk whose K/V start at 4 GiB;
    packed K and V 4.5 GiB each): 415/298/299 us vs 1069/1066/1058 us.
  • One request whose K and V each span the 4 GiB - 1 MiB limit (8,386,560 tokens): 64 queries by raw
    direct 146/145/144 us vs 415/415/416 us; 768 queries by union 473/390/419 us vs 799/797/789 us.
  • 1M context, 16384-row chunk, event-timed whole call:
    • 3.36/1.87/1.11 ms when rows share most blocks (union);
    • 10.71/10.00/9.86 ms when blocks are spread over the context (direct);
    • reading the pool through kv_slots instead of index_select plus the call saves 1.44-1.66 ms.
  • A 1024-query chunk over a 132k context in a pool above 4 GiB: 284/144/144 us in place vs
    463/318/316 us with the gather.

Unverified:

  • Other gfx942 parts (MI300X/MI325X).

PR-specific question

The op test is new: before this PR aiter.ops.qsa.qsa_sparse_prefill does not exist, so every case
fails at import. The existing QSA tests cover gfx950 decode (test_flydsl_qsa_sparse_decode.py) and
indexer logits (test_flydsl_qsa_paged_mqa_logits.py), not gfx942 prefill.

Changed op tests

op_tests/test_flydsl_qsa_sparse_prefill.py is new and is this op's only test:

  • Functional layouts grouped by route: direct only; union with packed direct; union with gated raw
    direct; nine 1M-token requests whose packed K/V exceed 4 GiB; one request at the 4 GiB - 1 MiB K/V
    limit (raw direct and union); HK 2/16 (HK16 with over 4096 tasks to order); T 256-1024; large logits.
  • CUDA graph replay, including after the scratch arena grows.
  • kv_slots pools (NaN-filled, three above 4 GiB, one with T = 1024), checked bit for bit against
    the gathered packed call.
  • Span limits: a request whose K/V, or whose int32 slot table, is one token over 4 GiB - 1 MiB must
    raise ValueError.
  • Full-prefill performance at TP2/4/8 shapes.
  • Cases needing more free device memory than is available (up to ~22 GiB) are skipped with a warning.

@luocheng25
luocheng25 requested a balanced review from Copilot October 15, 2026 12:03
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
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 gfx1201 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 6576 --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.

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

Unresolved resource and numerical-correctness concerns require changes, native MI308 validation, and final human review.

2 open findings
What changed in this PR

Adds FlyDSL BF16 D256 QSA sparse prefill/extend attention for MI308, with adaptive union and direct execution paths.

Changes:

  • Adds selection validation, routing, and cached per-stream workspaces.
  • Implements union, packed-direct, and raw-direct attention kernels.
  • Adds reference correctness checks and SGLang Triton benchmarks.
File Description
op_tests/​test_flydsl_qsa_attention.py Correctness cases and performance comparisons.
aiter/​ops/​flydsl/​kernels/​qsa/​attention.py Public entry point and workspace management.
aiter/​ops/​flydsl/​kernels/​qsa/​attention_union.py Shared-union attention kernel.
aiter/​ops/​flydsl/​kernels/​qsa/​attention_prepare.py Selection validation, routing, and masks.
aiter/​ops/​flydsl/​kernels/​qsa/​attention_direct.py Direct dispatch and raw-KV fallback.
aiter/​ops/​flydsl/​kernels/​qsa/​attention_direct_packed.py KV packing and packed-direct attention.
aiter/​ops/​flydsl/​kernels/​qsa/​attention_common.py Calibration and shared kernel helpers.
aiter/​ops/​flydsl/​kernels/​qsa/​__init__.py Initializes the QSA package.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread aiter/ops/flydsl/qsa_sparse_prefill.py Resolved

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

The fallback synchronization risk and incorrect NaN handling in the test reference need correction.

1 open finding
2 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Unmasked padded V entries let NaNs contaminate the reference

op_tests/​test_flydsl_qsa_attention.py:220

Zero padded V entries before the reference's probability–value multiplication. Each -1 currently gathers the request's V[0], so a NaN there contributes 0 * NaN even when token 0 is unselected. For a one-row request with prefix=2052, T=512, blocks 1–512 and tail token 2052, the two padding entries make the reference NaN although selected values of 1 should produce 1. Masking only scores does not prevent this and can make the test reject correct output.

🧠 Review effort: Balanced

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 low-level GPU pipelines, synchronization, and graph-shared scratch require native gfx942 validation and final human review.

0 open findings

1 resolved since last review

🧠 Review effort: Balanced

… P pack

- set -packed-fp32-ops via llvm.target_features; passthrough was dropped
- compute K/V DMA rows on the SALU, removing VALU address math in stage A
- _pack_bf16: one v_perm_b32 per pair (5 instructions instead of 6)
- P uses _pack_bf16 (RNE) like O
- _maximum, _center_one, _cross, LDS writes, the mask prefetch and the union
  K/V DMA use fx/rocdl ops instead of inline asm
- pin the centered scores so LLVM keeps their FMAs inside the stage
- unroll the union phase loop by two: the running max alternates registers,
  so no copy lands in a memory stage and _advance_max goes away
- _read_address stays asm (reasons in its comment); outputs are bitwise identical
- union: H12 unchanged, H6/H3 up to +0.5%/+0.9%
- split the union's 64 KB LDS into K and V variables: the module LDS
  lowering gives each its own alias scope, so a read no longer waits on
  in-flight DMAs into the other buffer
- read K/V and the O tiles with volatile LLVM loads through the LDS
  variables (_load_lds); volatile keeps the hand-written read/DMA order.
  _read_address and its inline asm are gone
- _keep_vgpr: an empty asm that only reads the loaded words keeps them in
  VGPRs (MFMA-only uses leave them AV-class and the scheduler reverts the
  QK interleave) without the s_nop a tied pin's def costs
- sched_barrier(0) after both cross() calls, so the ds_bpermutes issue
  before the reads that the hand-written lgkmcnt counts
- the shared _output (union and both direct kernels) takes the LDS
  variables; the V half's +32768 folds into the ds_read offset
- V DMA offsets are relative to the V buffer; for HK > 1, packets 1-3
  put the step in VOFFSET as K already does
- outputs bitwise identical; vs HEAD: prefill 0.1-1.2% faster (4096
  0.6-0.9%; 12000 H12/H6/H3 0.3/0.7/0.9%; 32768 H3 1.0-1.2%, H12 0.1%),
  chunk_1024 unchanged; the union phase loop takes 1.2-1.4% fewer cycles
@luocheng25
luocheng25 marked this pull request as ready for review October 22, 2026 03:10
@luocheng25
luocheng25 requested review from a team and a balanced review from Copilot October 22, 2026 03:10

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 hand-scheduled kernels, numerical edge case, and graph-lifetime and large-offset contracts need native gfx942 validation and human review.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 22, 2026 04:07

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

Hand-scheduled gfx942 synchronization and graph-shared scratch require head-matched native GPU correctness and performance evidence, which this source-only review cannot independently verify from author-reported results.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@zovonoir

zovonoir commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@valar-cop
This PR has had an approve but why it cannot automatically merge?

@valar-cop

Copy link
Copy Markdown

@zovonoir the approve is gone. ZLkanyo009's review shows as DISMISSED in the timeline (stale after the 8df6bdb push), so head has 0 approvals and auto-merge has nothing to fire on. the branch is also 164 commits behind main now, so if the repo requires an up-to-date branch you have to merge main first. i don't see a real conflict on your files (aiter/ops/qsa.py and kernels/qsa/* weren't touched on main since the merge base). get one approve on 8df6bdb and it should go.

@madhang

madhang commented Nov 2, 2026

Copy link
Copy Markdown

A few clarifications:

  1. It seems @fsx950223 has already approved the current HEAD, 8df6bdb. The approval
    ([FlyDSL] Add QSA sparse prefill attention for MI308 #6576 (review)) was submitted on November 2 at 07:07 UTC and should be still valid, so the request to “get one approve on 8df6bdb” appears to be satisfied.

  2. Does this review thread ([FlyDSL] Add QSA sparse prefill attention for MI308 #6576 (comment)) need to be marked as resolved?
    It is currently outdated but unresolved. The author’s reply says the boundary and over-limit tests were added in 8df6bdb,
    and the repository requires all review threads to be resolved before merging.

  3. For perf(sglang): aiter FlyDSL QSA sparse attention for Qwen3.8-Flash-Next eager prefill ATOM#2653, the suggestion to replace the index_select gathers with the KV pools and kv_slots for chunks with a cached prefix has not yet been implemented. This remains a useful follow-up optimization, especially at long contexts; End-to-end validation, including validation with a long context (1M-token input), still needs to be completed.

luocheng25 added a commit to tingqli/pyhip that referenced this pull request Nov 4, 2026
* sync with ROCm/aiter#6576 (2544b2927)

Port aiter/ops/flydsl/kernels/qsa/sparse_prefill_*.py and
aiter/ops/flydsl/qsa_sparse_prefill.py into pyhip.ops.qsa.flydsl, replacing
attention_{prepare,union,direct,direct_packed}.py. Only imports and the entry
name change: the entry is attention.attention, and get_gfx_runtime/get_cu_num
come from torch in sparse_prefill_common. op_tests/test_flydsl_qsa_sparse_prefill.py
becomes tests/ops/qsa/sparse_prefill_op_test.py, run by pytest through
tests/ops/qsa/test_attention.py.

* [fly][qsa] 1M context and in-place K/V pools on the AITER#6576 attention

Re-applies the QSA work on top of the AITER#6576 structure (sparse_prefill_*):
- attention: K1 drops the dense-bitmap scatter; K2 builds each tile's union in
  LDS (one membership word per block within a 32 KiB budget, 65536-block
  windows beyond), so the dense scratch is gone.
- attention: optional kv_slots reads K/V in place from a paged token pool
  (slotted K3, per-block union/pack descriptors, raw-direct LDS block table);
  pools over 4 GiB - 1 MiB take 64-bit global loads in raw direct (WIDE).
- attention: direct also packs a context of at most 32 tokens per query row
  (PK+PV <= 1 GiB).
- indexer: up to 262144 compressed keys (1M tokens): int32 top-k block ids,
  key-block-major prefill logits, multi-CTA decode top-k for long rows.
- tests: slot-table, >4 GiB pool, pack-rule and >2 GiB packed K/V cases;
  op-test cases follow QSA_REPLAY_GPU.
- docs: readmes re-measured (12k/1M kernels, op test vs SGLang Triton,
  slot-table pools, TP2/TP4 service, TP2/4/8 validation).

* [fly][qsa] gated raw direct runs the row groups K3 lists

When union and direct rows alternate in 16-32 row windows, the gated raw grid
(one CTA per 4-row group, in row order) left the CTAs with work on part of the
GPU, so raw direct took about as long as with every row direct.

K3 now adds one list CTA per 256 raw row groups (only for raw direct with a
union plan). It applies the route threshold, appends the groups holding a
direct row to direct_list and counts them in direct_flag[1] with one atomic add
per CTA; K2 clears both flag words. The gated raw grid keeps its size: CTA b
runs group direct_list[b // HK] while b // HK < direct_flag[1], the rest exit.

Same-process event timing against ffae4db, outputs bit-identical:
mixed union/direct selections at 128k (forced raw), 1M and the last 1696-row
chunk of a 100k request are 5.8-37.5% faster (H12/H6/H3), other selections
-1.7%..+0.3%; slot-table and >4 GiB (WIDE) pools 13-37% faster when mixed.
138 non-raw cases median +0.04%; 12k benchmark unchanged.

Scattering the group order on the host instead (bit-reversed, random or
16-slot orders) was evaluated and not adopted; see readme section 5.
QSA tests 112 passed, SGLang test_pyhip_qsa 6 passed.

* [fly][qsa] address PR #62 review: kv_slots overlap, 2-D top-k output

- attention: out must not overlap kv_slots either (the kernels read the slot table while
  out is written).
- indexer top-k: out is passed as [rows, 2051]. FlyDSL packs dynamic tensor dims as int32,
  so a 1M-row prefill's flattened output (2,150,629,376 elements) failed at launch, after
  the prep kernels had already updated the caches.
- tests: an out aliasing kv_slots raises; top-k rows land correctly in an output of more
  than 2**31 - 1 elements; a prefill split over many logits chunks (chunks starting inside
  a request or spanning two) is checked row by row against the reference.
- readme: record the stale FlyDSL K2 cache seen after 38e0d93. Every QSA launcher wraps
  its launches in a zero-work runtime `if`, so FlyDSL 0.4.0's key covers only the
  launcher's own source; a default cache filled before 38e0d93 kept serving the old K2,
  and gated raw tests faulted in K3. Compiled fresh, the code is correct.

Co-authored-by: Copilot <[email protected]>

* [fly][qsa] address PR #62 review round 2: kv_slots span check, BQ21/BQ42 tests

- attention: a kv_slots table of more than 2**32 - 2**20 bytes raises ValueError. The
  pack kernel reads the slot table through unsigned 32-bit buffer offsets and each
  request's start in it is uploaded as int32, so a larger table failed at launch or
  read wrong rows.
- tests: a 4 GiB slot table is rejected before any launch; full single-request H6/H3
  prefills take the BQ21/BQ42 union tiles (BQ42 with 64-bit membership) and sampled rows
  match the reference. The H3 BQ42 regression was dropped with the AITER sync.
- readme: the kv_slots limit and the review notes (the packing budget and the top-k
  output are left unchanged).

Co-authored-by: Copilot <[email protected]>

* [fly][qsa] prefill_indexer: select a row range into a shared output

A long prefill chunk's indexer work can now be split across tensor-parallel
ranks: every rank runs the full prep (the q prep also writes the pending
ring and the k compress the compressed pool, so each rank keeps complete
caches), then logits and top-k only for row_range=(first, end), written at
their own rows of a caller-provided out. _Layout clips the request tiles to
the range and recomputes each clipped tile's causal bound; the kernels are
unchanged.

At 1M (last 16384-row chunk) the indexer takes 45.3 ms per layer on one
GPU: logits 25.7 ms, top-k 19.2 ms, prep 0.4 ms. With SGLang splitting the
rows over TP2 and all-gathering the selections, the 999648-token TTFT drops
from 86.1 s to 76.2 s.

Tests: row ranges (2/3/7 shares cutting requests, tiles and logits chunks,
including empty shares) are bit-identical to the full call, write no other
rows and leave the caches as the reference prep does. QSA tests 120 passed.

Co-authored-by: Copilot <[email protected]>

* [fly][qsa] FlyDSL 0.3.2 LDS load fallback, cross-window union test

PR #62 review:
- _load_lds: without fx.generic_load (FlyDSL 0.3.2, pinned by AITER
  qwen38-flash-next-dev) emit the same volatile, 16-byte-aligned llvm.load;
  FlyDSL 0.4.0 keeps generic_load.
- test_union_across_windows: union tiles spanning two K2 windows
  (300000-token prefix) check each tile's block count, blocks and per-row
  membership against its rows' selections.

QSA tests: 123 passed on FlyDSL 0.4.0 and 0.3.2.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>

@zhiding512 zhiding512 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.

Non-blocking review notes. I didn't find correctness bugs, so these can be follow-ups after merge:

  1. softmax scale is a compile-time constant. SCALE is fx.Constexpr[float] in the kernels, so every new softmax_scale recompiles all of them (several seconds each), and under graph capture an unseen scale raises ("Warm ... before graph capture"). It would be better as a runtime argument.
  2. Duplicated code. _qk / _pv exist in three variants and _rescale in two, and the main loops of the direct and direct-packed kernels are roughly 80% the same.
  3. Low-level dependencies. The kernels still use the flydsl._mlir ir/llvm APIs, empty inline asm to pin registers, and hand-counted lgkmcnt waits for cross-wave LDS sync. The earlier review comment on sparse_prefill_common.py asked to avoid the llvm/ir APIs, and that was only partly addressed. These are the kind of things that can silently miscompute after a FlyDSL or LLVM upgrade instead of failing loudly.
  4. Tuning is tied to MI308X (80 CUs) and Qwen3.8 shapes. Other gfx942 parts such as MI300X only log a warning and reuse the 80-CU entry. The interface accepts up to 16 Q heads per KV head, but the tests only cover groups of 3, 6 and 12.
  5. Batch-dependent rounding. Whether a launch takes the union or the direct path is decided by a cost model over the whole batch, and the two paths round differently. From reading the code, the low bits of a given row can therefore change with the other requests in the same batch.
  6. License notice. op_tests/test_flydsl_qsa_sparse_prefill.py copies SGLang's Triton QSA code unchanged (sparse_attn.py L9-L267), but the file only carries AMD's MIT header. SGLang's Apache-2.0 notice should be kept for that part.

@coderfeli
coderfeli merged commit 082468a into ROCm:main Nov 4, 2026
yhl-amd pushed a commit to ROCm/ATOM that referenced this pull request Nov 4, 2026
…t eager prefill (#2653)

* perf(sglang): run Qwen3.8-Flash-Next eager prefill QSA attention with aiter FlyDSL

Behind ATOM_QSA_FLYDSL_ATTN=1 (default off), SGLang-ATOM eager prefill calls
aiter's qsa_sparse_attention_flydsl (ROCm/aiter#6576) instead of
qsa_sparse_paged_gqa. The plugin records host query/seq lengths, and for
prefixed requests the flat cache rows of each full context, which are gathered
into contiguous K/V. Selections are padded with -1 to the next width the kernel
accepts. Decode, verify, draft and graph capture keep the native kernel.
ATOM_QSA_FLYDSL_ATTN_CHECK=1 also runs the native kernel and logs the
per-layer difference.

* chore(qwen4_exp): drop the ATOM_QSA_FLYDSL_ATTN_CHECK numerics check

The check mode ran the native QSA kernel next to the FlyDSL one and logged
the per-layer difference. It was used to validate the FlyDSL path and is not
meant to land; feddb03 keeps it for reference.

Co-authored-by: Cursor <[email protected]>

* fix(qwen4_exp): keep the native QSA kernel for budgets, FP8 KV and archs FlyDSL cannot serve

- Take the FlyDSL path only for compression ratio 4 and a budget of
  1024 / 2048 / 3072 / 4096. Padding a selection laid out for another
  budget moves the causal tail, and the kernel reads it at the wrong column.
- Fall back when the KV cache is quantized: the prefixed path gathers raw
  cache rows and the kernel accepts BF16 only.
- Fall back on anything but gfx942, where aiter's entry raises.

Addresses the review threads on #2653.

Co-authored-by: Cursor <[email protected]>

* fix(qwen4_exp): fall back before aiter's 2**31-byte selection limit; tighten FlyDSL gate tests

- A padded selection of 2**31 bytes or more (e.g. a 131072-row eager
  prefill at budget 4096) makes aiter raise; keep the native kernel there.
- Gate tests no longer reach the real CUDA capture query, exercise padding
  with a genuinely short selection (width 11 -> 1027, -1 fill checked),
  and cover the byte limit.

Co-authored-by: Cursor <[email protected]>

* test(qwen4_exp): cover the FlyDSL prefill context gather and its batch fallbacks

- test_mixed_prefix_batch_gathers_full_contexts: a prefixed / fresh / prefixed
  batch with unequal lengths on non-consecutive pages crossing page
  boundaries. _flydsl_prefill_layout must return every request's full context
  rows in request-major order, and _flydsl_attention must hand the kernel
  exactly those K/V rows with the per-request query and prefix lengths.
- tests/plugin/test_sglang_qwen4_exp_graph_padding.py: _flydsl_prefill_layout
  returns no context rows for an unprefixed batch, and (None, None) for padded
  tokens, partial batches, missing host lengths and an extend longer than its
  sequence.

* fix(qwen4_exp): import FlyDSL QSA prefill from aiter.ops.qsa

ROCm/aiter#6576 renamed the prefill attention
(aiter.ops.flydsl.kernels.qsa.attention.qsa_sparse_attention_flydsl ->
aiter.ops.flydsl.qsa_sparse_prefill.flydsl_qsa_sparse_prefill) and added
aiter.ops.qsa.qsa_sparse_prefill as the entry for consumers, same
signature. With ATOM_QSA_FLYDSL_ATTN=1 the old import raised
ModuleNotFoundError at the first eager prefill, so a server on aiter with
the current #6576 could not start. Import the aiter.ops.qsa entry.

---------

Co-authored-by: Cursor <[email protected]>
ZLkanyo009 added a commit that referenced this pull request Nov 5, 2026
Resolve the aiter/ops/qsa.py conflict by keeping both new exports:
qsa_sparse_prefill (#6576) and qsa_store_quantized_rows (this PR).

Co-authored-by: Cursor <[email protected]>
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 9, 2026
…yDSL QSA, row-sharded indexer selection, sequence-parallel drafter (#2847)

* perf(sglang): run Qwen3.8-Flash-Next eager prefill QSA attention with aiter FlyDSL

Behind ATOM_QSA_FLYDSL_ATTN=1 (default off), SGLang-ATOM eager prefill calls
aiter's qsa_sparse_attention_flydsl (ROCm/aiter#6576) instead of
qsa_sparse_paged_gqa. The plugin records host query/seq lengths, and for
prefixed requests the flat cache rows of each full context, which are gathered
into contiguous K/V. Selections are padded with -1 to the next width the kernel
accepts. Decode, verify, draft and graph capture keep the native kernel.
ATOM_QSA_FLYDSL_ATTN_CHECK=1 also runs the native kernel and logs the
per-layer difference.

* chore(qwen4_exp): drop the ATOM_QSA_FLYDSL_ATTN_CHECK numerics check

The check mode ran the native QSA kernel next to the FlyDSL one and logged
the per-layer difference. It was used to validate the FlyDSL path and is not
meant to land; feddb03 keeps it for reference.

Co-authored-by: Cursor <[email protected]>

* fix(qwen4_exp): keep the native QSA kernel for budgets, FP8 KV and archs FlyDSL cannot serve

- Take the FlyDSL path only for compression ratio 4 and a budget of
  1024 / 2048 / 3072 / 4096. Padding a selection laid out for another
  budget moves the causal tail, and the kernel reads it at the wrong column.
- Fall back when the KV cache is quantized: the prefixed path gathers raw
  cache rows and the kernel accepts BF16 only.
- Fall back on anything but gfx942, where aiter's entry raises.

Addresses the review threads on #2653.

Co-authored-by: Cursor <[email protected]>

* fix(qwen4_exp): fall back before aiter's 2**31-byte selection limit; tighten FlyDSL gate tests

- A padded selection of 2**31 bytes or more (e.g. a 131072-row eager
  prefill at budget 4096) makes aiter raise; keep the native kernel there.
- Gate tests no longer reach the real CUDA capture query, exercise padding
  with a genuinely short selection (width 11 -> 1027, -1 fill checked),
  and cover the byte limit.

Co-authored-by: Cursor <[email protected]>

* test(qwen4_exp): cover the FlyDSL prefill context gather and its batch fallbacks

- test_mixed_prefix_batch_gathers_full_contexts: a prefixed / fresh / prefixed
  batch with unequal lengths on non-consecutive pages crossing page
  boundaries. _flydsl_prefill_layout must return every request's full context
  rows in request-major order, and _flydsl_attention must hand the kernel
  exactly those K/V rows with the per-request query and prefix lengths.
- tests/plugin/test_sglang_qwen4_exp_graph_padding.py: _flydsl_prefill_layout
  returns no context rows for an unprefixed batch, and (None, None) for padded
  tokens, partial batches, missing host lengths and an extend longer than its
  sequence.

* fix(qwen4_exp): import FlyDSL QSA prefill from aiter.ops.qsa

ROCm/aiter#6576 renamed the prefill attention
(aiter.ops.flydsl.kernels.qsa.attention.qsa_sparse_attention_flydsl ->
aiter.ops.flydsl.qsa_sparse_prefill.flydsl_qsa_sparse_prefill) and added
aiter.ops.qsa.qsa_sparse_prefill as the entry for consumers, same
signature. With ATOM_QSA_FLYDSL_ATTN=1 the old import raised
ModuleNotFoundError at the first eager prefill, so a server on aiter with
the current #6576 could not start. Import the aiter.ops.qsa entry.

* perf(qwen4_exp): sequence-parallel HC residual streams for TP prefill

Under TP the 4-stream hyper-connection residual (grouped norm, the two
low-rank GEMMs, gated mean) is per-token and replicated, so every rank
repeated it on all tokens (~30% of TP4 prefill GPU time). For forwards with
>= ATOM_QWEN4_EXP_SP_MIN_TOKENS tokens (default 1024, eager prefill only;
never under graph capture), keep the streams token-sharded after the PLE
layer: sub-layer inputs are all-gathered, sub-layer partial sums
reduce-scattered (same bytes as the all-reduce they replace), and the HC
work is split TP ways.

Sharded layers skip mix_fused_quant: the FP8 attention-input projection
quantizes the gathered BF16 rows itself, as the unsharded path already does
above HC_QUANT_ROWS_MAX rows.

* fix(qwen4_exp): keep SP off when no layer follows PLE; CPU tests for the token sharding

With PLE on the last decoder layer the loop never sharded the streams, yet
both output paths still all-gathered them, returning tp x the rows. SP now
stays off when sp_start_layer >= end_layer.

tests/test_qwen4_exp_sequence_parallel.py runs _SequenceParallel and
Qwen4ExpModel.forward on simulated TP ranks (threads meeting in mocked
all_gather / reduce_scatter_tensor): shard/gather round trips and
reduce-scatter sums for even and uneven token counts, and a sharded forward
against the unsharded one in both output modes, including PLE on the last
layer (fails without the fix).

* perf(qwen4_exp): pad only the local rows in _SequenceParallel.shard

For token counts not divisible by TP, shard() padded the whole replicated
[T, 10240] stream tensor before slicing, an extra full-size allocation and
copy per rank that the returned view kept alive. Slice this rank's rows
first and pad only that slice; unpadded shards stay views.

* perf(sglang): FlyDSL QSA attention for the drafter's eager prefill extend

The eager prefill draft extend runs the drafter's QSA layer over the same
tokens as the target prefill but was excluded from the FlyDSL path, so it
used qsa_sparse_paged_gqa (16 ms per 16K-token step at TP4, a third of the
draft step). Packed draft steps (decode / draft-extend-v2) return before this
point and keep the native kernel.

* perf(qwen4_exp): split the replicated QSA indexer selection across TP ranks

The QSA indexer (scoring every compressed key group and the per-row top-k)
is replicated under TP, and at long context it is the fastest-growing part
of prefill (~25% of a 16K-token chunk at ~80K context on TP4). Under the
sequence-parallel prefill each rank now scores and selects only its own
query rows and all-gathers the [rows, block_topk] group ids before the
expansion. Every row's selection depends only on its own query, request and
position, so the result is bit-identical; the gather moves 2 KB per token.

qsa_select_paged_tokens is split into qsa_select_paged_groups (score +
top-k) and the existing expansion; the combined call is unchanged.

* perf(qwen4_exp): sequence-parallel MTP drafter prefill extend

The drafter's single layer, its pre-fc norms and fc projections (including
fc_hidden over all four streams, [4T,2560]x[2560,2560]) and its unfused
hyper-connections ran replicated over every prefill token on every TP rank.
Large draft extends now use the same token sharding as the target: per-token
work on the local shard, attention / MoE inputs all-gathered, their partial
sums reduce-scattered, and the streams gathered once at the end.

_SequenceParallel.maybe() replaces the model-private helper so the target and
the drafter share one gating rule (TP > 1, >= ATOM_QWEN4_EXP_SP_MIN_TOKENS,
not under graph capture).

* fix(qwen4_exp): shard only above HC_QUANT_ROWS_MAX tokens

At up to HC_QUANT_ROWS_MAX (1024) tokens the unsharded attention HC emits the
FP8 projection input itself (mix_fused_quant -> hc_gated_mean_quant), while a
sharded layer skips that and lets the projection quantize the gathered BF16
rows, which the unsharded path only does above 1024 tokens. With the default
ATOM_QWEN4_EXP_SP_MIN_TOKENS=1024, an eager TP>1 forward of exactly 1024
tokens (or any count down to a lower env threshold) therefore took a different
FP8 activation-quant path depending on whether it was sharded.

_SequenceParallel.maybe() now also requires num_tokens > HC_QUANT_ROWS_MAX,
whatever the env value (0 still disables), so a sharded forward always uses
the same quantization as the unsharded one. tests: the forward-equivalence
cases now use 1026 / 1027 / 1032 tokens, and a gate test pins the boundary.

* test(qwen4_exp): row-sharded selection on the serving prefill scorer

test_qsa_row_sharded_selection_matches_whole_batch only ran with
allow_flydsl=False. It now covers allow_flydsl False and True (FlyDSL, as
serving prefill uses on gfx942), TP2 / TP4 / TP8, and two batches: 2503 rows,
and 1025 rows, the smallest sharded forward (TP4 -> 257-row shards, TP8 ->
129-row shards). It also runs each case with shard-sized and 200-row scoring
calls, so rows cross the 256-row switch between the >256-row scorer
(FlyDSL / Triton MFMA) and the stacked scorer. All 24 cases select exactly
what the whole batch selects.

test_qsa_index_scorers_agree_on_visible_logits pins the reason the switch is
harmless: on every visible column the stacked scorer agrees with the FlyDSL
and the Triton MFMA scorers to atol 1e-5. Measured max differences are
1.9e-6 to 2.9e-6, at |logit| up to about 12.

* test(qwen4_exp): drafter prefill extend matches its replicated forward under SP

test_drafter_forward_matches_unsharded runs the real
Qwen4ExpMultiTokenPredictor.forward and Qwen4ExpDecoderLayer._forward_unfused
on simulated TP2 / TP4 ranks, at 1026 and 1027 tokens (uneven splits above
the SP threshold). Stand-in sub-layers return per-rank partial sums: a causal
token-mixing attention and a per-token MoE. The test covers the pre-fc
sharding, the attention / MoE all-gathers and reduce-scatters, and the final
stream gather. It compares against the unsharded forward and checks that both
sub-layers saw all rows and took the sharded path. It fails if the final
gather or the MoE input gather is dropped.

* fix(qwen4_exp): fused-quant floor for the target only; test _select_tokens(rows=)

The HC_QUANT_ROWS_MAX floor only matters to the target model, whose fused
attention HC emits the FP8 projection input up to 1024 tokens. The drafter's
unfused HC never quantizes, so the floor there only kept 1024-token extends
replicated. It moves out of _SequenceParallel.maybe() into
Qwen4ExpModel._sequence_parallel(); the drafter now shards from
ATOM_QWEN4_EXP_SP_MIN_TOKENS alone.

tests/test_qwen4_exp_sequence_parallel.py:
- test_sp_gates: target vs drafter gate across env values (1024 boundary,
  lower / higher / disabled thresholds, TP=1).
- test_drafter_forward_matches_unsharded also runs 1024 tokens.
- test_select_tokens_row_sharded_matches_replicated drives the real
  Qwen4ExpAttention._select_tokens(rows=_SequenceParallel) on simulated
  TP2 / TP4 / TP8 ranks for a prefixed + fresh 1500-row prefill. It runs on
  the Triton scorer and on the FlyDSL scorer serving prefill uses (gfx942).
  Every rank must end with the replicated selection and index caches; the
  test fails if a shard scores the wrong positions.

* docs(env): ATOM_QWEN4_EXP_SP_MIN_TOKENS and ATOM_QSA_FLYDSL_ATTN

* test(qwen4_exp): half-shard scoring calls in the row-sharded selection test

Adds a "half-shard" case that chunks each shard's scoring into two calls.
TP2 / TP4 at 2503 rows and TP2 at 1025 rows stay above 256 rows per call, so
chunking is exercised on the same scorer as the whole batch. The 200-row
case stays as the deliberate cross-scorer comparison. The scored width now
uses the same bound as qsa_select_paged_groups.

* perf(sglang): build the FlyDSL QSA layout only when the kernel can run

With ATOM_QSA_FLYDSL_ATTN=1, build_qsa_metadata built the FlyDSL host
layout for every eager unpacked extend: host lengths, plus an H2D of the
context rows when prefixed (0.2-0.9 ms per forward). It did so even when
every QSA layer would then fall back: a non-gfx942 GPU, an FP8 KV pool, or
a ratio / budget the kernel does not serve. _flydsl_layout_needed() now
gates it on the flag, compression ratio 4 with a supported budget, a BF16
SGLang KV pool and gfx942, reusing the layer's own _FLYDSL_WIDTHS and
_flydsl_arch_supported. An FP8 SGLang pool binds no scale planes, so the
layer could not detect it; without host lengths it now keeps the native
kernel.

* fix(sglang): FlyDSL layout context rows on device; KV dtype from the bound pool

- _flydsl_prefill_layout built the request / token index arrays on the host
  and staged them through a fresh pin_memory() every prefixed forward
  (16 B per context token, MBs past the 512 KB pageable limit in
  atom/utils). It now uploads only the per-request lengths (upload_numpy)
  and builds the indices on the device with repeat_interleave(output_size=),
  which needs no host sync. The rows are identical.
- The FP8 guard read the KV dtype only from forward_batch.token_to_kv_pool.
  _token_to_kv_pool() now resolves the pool the way bind_qsa_caches does
  (forward batch, then attention backend, then its full_attn_backend), and
  both share it. A pool whose dtype cannot be read keeps the native kernel.

tests/plugin/test_sglang_qwen4_exp_graph_padding.py: backend-resolved pool
dtypes, an unresolved pool, and the mixed prefixed / fresh context rows on
CPU tensors, which no longer needs pinned memory.

* test(qwen4_exp): FlyDSL QSA attention vs the native kernel on short contexts

A short prefill shrinks the selection with max_seq_len, so
_flydsl_attention pads it with -1 to the next FlyDSL width, past the
budget's own layout. aiter's contract is per row: min(v // 4, T) complete
blocks, then the v % 4 tail tokens, left-aligned, -1 after. A short
context selects every complete block followed by its tail, so the padded
row keeps that layout; only a smaller budget (fewer blocks than the
width's T) breaks it, which the budget gate already rejects.

test_short_context_matches_native_kernel runs the real kernel against
qsa_sparse_paged_gqa on the same selection: one request of 7, 300 and 512
tokens (selection widths 11, 323, 515, padded to 1027), a 200-token
prefix + 300, three mixed requests, and an unpadded 1000-token control.
It skips without a GPU, off gfx942, or without ROCm/aiter#6576.

The gate and padding comments now state that contract instead of a moved
causal tail.

* fix(env): parse ATOM_QWEN4_EXP_SP_MIN_TOKENS with _nonnegative_int_env

A bare int() raised on a malformed value at the first forward that read
it. Like the other integer knobs in envs.py, a malformed or negative value
now logs a warning and keeps the default (1024). test_sp_gates covers both.

* refactor(qwen4_exp): one FlyDSL QSA support predicate for the layer and the bridge

Qwen4ExpAttention._flydsl_attention and the SGLang bridge's
_flydsl_layout_needed each spelled out the forward-invariant FlyDSL
conditions (flag, gfx942, BF16 KV, compression ratio 4 with a served
budget). qsa_attention.flydsl_attention_supported now owns them: the layer
passes kv_bf16 from its scale planes, the bridge from the dtype of the pool
the QSA caches are bound from. The per-call conditions (selection byte span,
graph capture, head shape) stay with the layer. No behaviour change.

* fix(qwen4_exp): _SequenceParallel pads rows on dim 0 for any rank

shard() and scatter() padded with nn.functional.pad(x, (0, 0, 0, n)),
which only appends rows for a 2-D tensor; a [T, ...] input of higher rank
would have been padded on dim 1. Every current caller passes 2-D tensors.
_pad_rows builds the pad spec from x.dim(). The shard / gather round trip
and the reduce-scatter tests now also run on 3-D inputs.

* perf(qwen4_exp): head shape in the shared FlyDSL predicate; log its fallbacks

qsa_attention.flydsl_fallback_reason replaces flydsl_attention_supported and
also takes the per-rank head shape, so the bridge stops building the host
layout where the layer would reject the shape anyway (TP1: 24 q / 2 KV
heads per rank). qsa_rank_heads now holds the per-rank head split that
Qwen4ExpAttention.__init__ used inline; the bridge applies it to the model
config and the TP size. It returns a reason, or None when FlyDSL can run.

With ATOM_QSA_FLYDSL_ATTN=1 the first FlyDSL call logs an INFO line and each
distinct fallback reason a WARNING, once per process; forwards the bridge
did not lay out (target verify, warmup) are not fallbacks and stay quiet.
On TP4 the log shows the INFO line on every rank and no fallback.

test_eager_prefill_max_seq_len_ignores_stale_decode_graph_flag pins the
flag off: its config has no head shape, and the image sets the flag.

* perf(qwen4_exp): run QSA prefill attention on FlyDSL by default

ATOM_QSA_FLYDSL_ATTN now defaults to on (read with _flag_env, so 0 / false /
off / empty disables). Images built from main pull aiter main, which carries
the FlyDSL QSA prefill kernel once ROCm/aiter#6576 lands, so Qwen3.8-Flash-Next
eager prefill on SGLang-ATOM gets it without a deployment flag. Every
unsupported case (non-gfx942, FP8 KV, budget / ratio / head shape, graph
capture, selection span) still falls back to the native kernel and logs why
once. An aiter without the kernel raises at the first FlyDSL prefill, as with
the flag set before.

* fix(qwen4_exp): FlyDSL fallback warning states the state, not a setting

With ATOM_QSA_FLYDSL_ATTN on by default, "ATOM_QSA_FLYDSL_ATTN=1, but ..."
named a setting the operator may never have made. The warning now reads
"FlyDSL QSA prefill attention is enabled, but QSA attention uses the
native kernel: <reason>".

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: JiaoliangYu <[email protected]>
@luocheng25
luocheng25 deleted the luocheng/qsa-attn-308 branch November 18, 2026 08:19
ZLkanyo009 added a commit to ROCm/ATOM that referenced this pull request Nov 18, 2026
…83 query

aiter.ops.qsa is imported at module level now, so the lazy
_flydsl_attention_op() wrapper has no reason left: qsa_sparse_prefill joins
that import and the layer calls it; the tests patch that name.

The ATOM_QSA_FLYDSL_ATTN row described the old mirrored rules (non-gfx942,
fixed budgets, a padded selection's 2**31 bytes) and ROCm/aiter#6576. It now
says the layer falls back where aiter reports no widths, has none for the
budget, or rejects the selection, and that every import needs ROCm/aiter#8083.
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
* add qsa attention support

* relax kvcache 4G restrictions to single request(TP1 4M  tokens, TP2/4/8 8M tokens)

* apply review comments

* revert non-exist nan case

* simplify attention_prepare interface

* qsa union: use SALU for DMA addresses, effective target-features, RNE P pack
- set -packed-fp32-ops via llvm.target_features; passthrough was dropped
- compute K/V DMA rows on the SALU, removing VALU address math in stage A
- _pack_bf16: one v_perm_b32 per pair (5 instructions instead of 6)
- P uses _pack_bf16 (RNE) like O

* qsa: drop most inline asm, unroll the union phase loop by two

- _maximum, _center_one, _cross, LDS writes, the mask prefetch and the union
  K/V DMA use fx/rocdl ops instead of inline asm
- pin the centered scores so LLVM keeps their FMAs inside the stage
- unroll the union phase loop by two: the running max alternates registers,
  so no copy lands in a memory stage and _advance_max goes away
- _read_address stays asm (reasons in its comment); outputs are bitwise identical
- union: H12 unchanged, H6/H3 up to +0.5%/+0.9%

* qsa: split the union K/V LDS, read LDS with LLVM loads, drop ds_read asm

- split the union's 64 KB LDS into K and V variables: the module LDS
  lowering gives each its own alias scope, so a read no longer waits on
  in-flight DMAs into the other buffer
- read K/V and the O tiles with volatile LLVM loads through the LDS
  variables (_load_lds); volatile keeps the hand-written read/DMA order.
  _read_address and its inline asm are gone
- _keep_vgpr: an empty asm that only reads the loaded words keeps them in
  VGPRs (MFMA-only uses leave them AV-class and the scheduler reverts the
  QK interleave) without the s_nop a tied pin's def costs
- sched_barrier(0) after both cross() calls, so the ds_bpermutes issue
  before the reads that the hand-written lgkmcnt counts
- the shared _output (union and both direct kernels) takes the LDS
  variables; the V half's +32768 folds into the ds_read offset
- V DMA offsets are relative to the V buffer; for HK > 1, packets 1-3
  put the step in VOFFSET as K already does
- outputs bitwise identical; vs HEAD: prefill 0.1-1.2% faster (4096
  0.6-0.9%; 12000 H12/H6/H3 0.3/0.7/0.9%; 32768 H3 1.0-1.2%, H12 0.1%),
  chunk_1024 unchanged; the union phase loop takes 1.2-1.4% fewer cycles

* qsa union: restructure the pipeline body

* use float MAX_FLOOR instead of hard code -1e30

* fix ci checks

* apply review comments

* apply review comments: 1, check scaled range 2, avoid not release non-cached workspace 3, wait stream before execution new kernel

* use fx.generic_load for LDS reads, centralize target features, trim pins

* rename prefill attention to sparse_prefill, add aiter.ops.qsa entry

* qsa sparse prefill: kv_slots, 1M-token contexts, >4 GiB coverage

- kv_slots: read K/V in place from a paged token pool (four-token blocks
  on four rows starting at a multiple of 4; table <= 4 GiB - 1 MiB).
- K2 builds unions in LDS, so 1M-token contexts need no dense scratch;
  K3 maps pool blocks and lists the raw direct groups to run.
- Direct packs only while PK/PV fit 32-bit offsets.
- Op test: >4 GiB packed K/V, per-request limit, kv_slots pools,
  over-limit rejection, skips on low free memory.
ZLkanyo009 added a commit to ROCm/ATOM that referenced this pull request Nov 18, 2026
…rd's selection wiring

The envs.py comment still said gfx942 and ROCm/aiter#6576. aiter reports where
the kernel runs (qsa_sparse_prefill_widths()), and qsa_attention imports its
queries at module level, so every import needs ROCm/aiter#8083, flag on or off.

test_forward_selects_into_the_kernel_buffer runs Qwen4ExpAttention.forward on
a prefill with spies for the selection ops and the kernel, whole and
sequence-parallel: the layout is made, the selection is written into its
kernel-width buffer (out=, out[:, :width] when sharded), and the kernel reads
that buffer.
zufayu pushed a commit that referenced this pull request Nov 19, 2026
…ed helpers, opt-in batch invariance (#8148)

* [FlyDSL] [QSA] Sparse prefill follow-ups: runtime softmax scale, shared helpers, opt-in batch invariance

Follow-ups to the review of #6576.

- The softmax scale is a kernel argument (FP32 softmax_scale * log2(e)): a new
  scale compiles nothing and can be graph-captured directly.
- The QK, PV and rescale code and the direct key loop are defined once in
  sparse_prefill_common.py and shared by the union and both direct kernels.
- The kernels use FlyDSL's stable API; what has no stable equivalent (empty-asm
  register pins, the target-features attribute, unexported ROCDL operations,
  volatile LDS reads and the lgkmcnt ledger) is gathered in one section of
  sparse_prefill_common.py with the reason it stays.
- qsa_sparse_prefill gains a trailing keyword-only batch_invariant=False. The
  default keeps the call-wide union/direct decisions, with main's bits. With
  batch_invariant=True they are made per request (union planning rows, tile
  rows, no K3 routing by the others), so a request gives the same bits alone
  as in any batch. The workspace key includes the mode.
- The non-MI308X warning says what is reused, and group 16 is tested.
- The SGLang Triton code copied into the op test keeps SGLang's Apache-2.0 notice.

Co-authored-by: Copilot <[email protected]>

* [FlyDSL] [QSA] Test: offer only --case names a suite runs

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 19, 2026
…ot table and select at the kernel width (#3450)

* perf(sglang/qwen4-exp): QSA FlyDSL prefill reads K/V in place and selects at kernel width

Under SGLang (page 64) each QSA layer of an eager prefill took the aiter
FlyDSL sparse attention through a host path that repeated per layer what
is the same for the whole forward, and copied data the kernel can read
where it is:

- K/V: with a prefix, each layer index_selected the whole context's K and
  V rows out of its paged pool. aiter's qsa_sparse_prefill reads a token
  pool in place through a slot table (kv_slots) when every four-token
  block of a request sits in four consecutive pool rows starting at a
  multiple of four, which a page size divisible by four guarantees (the
  bridge already requires the page to be divisible by the compress
  ratio, 4). The bridge now emits the context rows as int32, the slot
  table's type; the layer passes the pool and the table. aiter documents
  the result as the same as for the packed rows.
- Selection: each layer padded its selection with -1 to the kernel width
  (a copy, also when the width already matched). The first layer of the
  forward now allocates one kernel-width buffer filled with -1, and every
  layer's selection writes its leading columns in place; the columns past
  the selection are never written, so they stay -1.
- Checks: the flag, the layer support check, the per-call checks, the
  width and the per-request prefix lengths are made once per forward
  (_FlyDSLPrefill, kept on the forward's QSA metadata, keyed by
  everything they read from the layer and its inputs).

Native ATOM, whose metadata has no FlyDSL layout, keeps its path.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): QSA FlyDSL prefill layout, in-place reads and kernel-width selection

- One layout per forward (checks and prefix lengths made once), a new one
  for another row count.
- The kernel-width selection buffer reaches the kernel as is, -1 past the
  selection, reused by a second layer.
- With a prefix the pool and the bridge's int32 slot table go to the
  kernel; int64 rows or a strided pool are gathered as before.
- GPU: the real kernel on the slot table and the in-place selection gives
  the same bits as gathered rows and a padded copy (hit, second chunk,
  mixed unaligned prefixes, short, no prefix).
- The bridge's context rows are int32 and contiguous.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): sharded QSA selection written into the kernel-width buffer

The sequence-parallel path expands the all-gathered groups itself; into a
column prefix of the kernel-width buffer it writes the same columns as
into a fresh tensor and leaves -1 past them (GPU).

Co-authored-by: Cursor <[email protected]>

* perf(qwen4-exp): QSA FlyDSL prefill always reads K/V through the slot table

Review of #3433. The bridge is the only producer of `context_slots`, always
as int32, and already requires a page size divisible by the compress ratio,
so `kv_slots` is passed whenever there are context rows; aiter validates the
slot table itself. The gather branch and the hand copy of aiter's slot-table
rule go away. So does the pad fallback: `forward` builds the layout before
the selection and writes it into the kernel-width buffer, which is what the
kernel gets.

The layout is now looked up once per layer in `forward` (no second lookup in
`_flydsl_attention`), computes the selection width itself (once per forward
instead of once per layer), reads `qsa.flydsl_prefill` directly, and no
longer keys on the index size, which is always int32. The metadata comment
now says what `for_tokens` does with the layout.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): run the QSA FlyDSL host cases in the CPU job

The CPU cases of `tests/test_qwen4_exp_qsa_flydsl_gate.py` were skipped by
its module-level `importorskip("aiter.ops.enum")`. They move to
`tests/model_ops/test_qsa_flydsl_prefill_host.py`, which imports the model
code through `atom_without_aiter` and builds a real `Qwen4ExpQSAMetadata`
per forward. The int64 / strided gather cases go with the branch they
covered. The gate module keeps the GPU cases; its bit-for-bit reference is
now the kernel called directly on gathered rows and a padded selection.

Co-authored-by: Cursor <[email protected]>

* test: stand in einops for model code imported without AITER

The CPU job installs no einops (ATOM does not depend on it), and
`qwen4_exp_attn` reaches it through `gdn_attn` -> `attention_gdn`, so the new
QSA host cases errored at setup there. `stubbed_external_kernel_modules` now
serves it like aiter and triton, only where it is not installed, so a host
with einops keeps the real one.

Co-authored-by: Cursor <[email protected]>

* build: declare einops; drop its test stand-in

Review of #3450. Model code imports einops at module level (`attention_gdn`,
`fla_ops/chunk`, `qwen3_next`, `kimi_k3/model`, ...), but it was not a
declared dependency, so the CPU job, which installs ATOM through pip, had
none. Declare it (the image ships 0.8.2) and drop the einops branch that
844a485 added to `tests/aiter_stub.py`, which is back to its earlier form.

Co-authored-by: Cursor <[email protected]>

* refactor(qwen4-exp): reference aiter's support query at the QSA mirrors

Review of #3450. The FlyDSL selection widths and the 2**31-byte check
mirror aiter's `qsa_sparse_prefill`; each mirror now points to
ROCm/aiter#8083, which exposes them as `qsa_sparse_prefill_widths()` and
`qsa_sparse_prefill_supports_selection()`, and goes once it lands.

`_FlyDSLPrefill` keeps its row count as `rows` instead of reading it back
from the key, and its docstring says why the host lengths may stay out of
the key: the layout lives on one forward's metadata, which the bridge builds
anew each forward, and a trimming `for_tokens` drops it.

Co-authored-by: Cursor <[email protected]>

* refactor(qwen4-exp): make the selection-width helper public for the QSA layout

Self-review of #3450. `qsa_attention` imported the private
`_selection_widths` from `qwen4_exp/ops/qsa.py` to size the kernel-width
selection buffer before selecting. It is now `qsa_selection_widths`; its two
callers in `ops/qsa.py` and the host test's spy follow, and nothing else
used it.

`_FlyDSLPrefill`'s docstring now names everything the layout reads from the
forward's metadata and keeps out of the key (the host lengths, plus the block
table width and longest sequence behind the selection width), and the comment
in `forward` no longer describes the code this PR replaced. No behavior
change.

Co-authored-by: Cursor <[email protected]>

* docs: ATOM_QSA_FLYDSL_ATTN reads prefixed K/V in place

Self-review of #3450. The variable's row still said prefixed chunks gather
their requests' full-context K/V from the paged cache once per layer; with
this PR they read it in place through the bridge's slot table.

Co-authored-by: Cursor <[email protected]>

* qwen4_exp: QSA FlyDSL prefill asks aiter for its widths, selection limit and GPU

aiter.ops.qsa answers the selection widths, the selection byte limit and
whether the kernel runs on this GPU (ROCm/aiter#8083), so the layer and the
SGLang bridge ask it instead of mirroring them: _FLYDSL_WIDTHS, the 2**31-byte
check and the gfx942 check go.

* qwen4_exp: name the QSA selection width; correct the 67-column test docstring

The selection's own width is selection_width, not columns. A 40-token context
reaches 10 groups, rounded up to a power of two: 16, so 67 columns.

* qwen4_exp: call aiter's qsa_sparse_prefill directly; document the #8083 query

aiter.ops.qsa is imported at module level now, so the lazy
_flydsl_attention_op() wrapper has no reason left: qsa_sparse_prefill joins
that import and the layer calls it; the tests patch that name.

The ATOM_QSA_FLYDSL_ATTN row described the old mirrored rules (non-gfx942,
fixed budgets, a padded selection's 2**31 bytes) and ROCm/aiter#6576. It now
says the layer falls back where aiter reports no widths, has none for the
budget, or rejects the selection, and that every import needs ROCm/aiter#8083.

* qwen4_exp: ATOM_QSA_FLYDSL_ATTN names ROCm/aiter#8083; test the forward's selection wiring

The envs.py comment still said gfx942 and ROCm/aiter#6576. aiter reports where
the kernel runs (qsa_sparse_prefill_widths()), and qsa_attention imports its
queries at module level, so every import needs ROCm/aiter#8083, flag on or off.

test_forward_selects_into_the_kernel_buffer runs Qwen4ExpAttention.forward on
a prefill with spies for the selection ops and the kernel, whole and
sequence-parallel: the layout is made, the selection is written into its
kernel-width buffer (out=, out[:, :width] when sharded), and the kernel reads
that buffer.

---------

Co-authored-by: root <[email protected]>
Co-authored-by: Cursor <[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.

10 participants