Skip to content

[fly][qsa] extend QSA prefill to support 1M context - #62

Merged
luocheng25 merged 7 commits into
tingqli:devfrom
luocheng25:luocheng/qsa-1m
Nov 4, 2026
Merged

luocheng25 merged 7 commits into
tingqli:devfrom
luocheng25:luocheng/qsa-1m

Conversation

@luocheng25

@luocheng25 luocheng25 commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Extends the QSA prefill (attention + indexer) from #57 to 1M-token contexts (MAX_COMPRESSED_KEYS 65536 → 262144 compressed keys), on top of the ROCm/aiter#6576 kernel structure.

SGLang integration: qwen38-flash-next/qsa-1m (e1eb8a6...b1abbb0): passes the layer's K/V pool and slot table to attention (kv_slots), lets graph decode use decode_indexer up to MAX_COMPRESSED_KEYS, keeps the PyHIP indexer with YaRN MRoPE, and, with SGLANG_OPT_PYHIP_QSA_SPLIT_INDEXER=1 (off by default), splits long prefill indexer chunks across attention-TP ranks through prefill_indexer(row_range, out).

Changes

  • Sync with [FlyDSL] Add QSA sparse prefill attention for MI308 ROCm/aiter#6576 (2544b2927): AITER's sparse_prefill_* replace attention_{prepare,union,direct,direct_packed}.py; its op test runs as tests/ops/qsa/sparse_prefill_op_test.py.
  • Attention
    • K2 builds each tile's union in LDS (65536-block windows beyond the LDS budget); K1's dense-bitmap scatter and the dense scratch (1.6/1.0/0.5 GiB at 1M for TP2/4/8) are gone.
    • kv_slots: reads K/V in place from a paged token pool instead of a per-layer index_select copy; pools over 4 GiB use 64-bit loads. out must not overlap the slot table, and a slot table over 2³² − 2²⁰ bytes raises ValueError (the pack kernel reads it through unsigned 32-bit offsets).
    • Direct packs K/V for contexts up to 32× the query rows (PK+PV ≤ 1 GiB); batches whose packed K/V reach 2 GiB run as groups of consecutive requests instead of raising.
    • Gated raw direct runs only the row groups K3 lists, so mixed union/direct selections no longer leave CTAs idle.
  • Indexer (up to 262144 compressed keys = 1M tokens)
    • Top-k: int32 chosen block ids for rows over 65536 keys; prefill rows of ≥ 16384 keys share a CTA's 4 waves; decode rows over 32768 keys split over up to 32 CTAs. Selections stay bit-identical.
    • Top-k takes its output as [rows, 2051]: FlyDSL passes dynamic dims as int32, so the flattened output of a 1M-row prefill (2,150,629,376 elements) failed at launch.
    • Prefill logits are stored key-block-major (512-key blocks, 544-float pitch), in chunks of up to 512 MiB / at least 1024 rows (≈ 1.1 GiB at 1M).
    • prefill_indexer(..., row_range=(first, end), out=...): the prep still runs for every row (it writes the pending ring and the compressed pool, so every caller keeps complete caches); logits and top-k run only for the range and write those rows of a caller-provided [rows, 2051] output. The kernels are unchanged.
    • decode_indexer requires (rows · width + 512) · 4 < 2 GiB.
  • Tests and docs: slot-table, > 4 GiB pool, pack-rule, > 2 GiB packed K/V, 1M indexer, BQ21/BQ42 wide-tile and row-range cases. The op test's released() now counts a pointer missing from the allocator snapshot as released, so the graph-replay check cannot pass on a freed captured pointer. Readmes re-measured.

Performance (MI308X, per layer)

Case (CUDA-event timing of whole calls) Before This PR
Prefill indexer, last 16384-row chunk of 1M 176.9 ms¹ 47.0 ms
Prefill indexer, prefix 245760 + 16384 rows 13.31 ms 9.59 ms
Prefill indexer, 12k 423.7 µs 423.8 µs
Decode indexer 1M, B1 / B8 (graph replay) 142.8 / 302.6 µs² 50.4 / 197.3 µs
Attention, last 16384 rows of 1M, union, H12/H6/H3 4.28 / 2.50 / 1.55 ms³ 3.46 / 1.89 / 1.14 ms
Attention, same, direct, H12/H6/H3 11.89 / 11.48 / 10.66 ms³ 10.56 / 10.36 / 10.06 ms

¹ edde17b's logits layout (edde17b itself stops at 65536 keys). ² Single-CTA int32 top-k. ³ The AITER#6576 sync commit 14592cb.

Reading K/V in place saves 1.3–1.7 ms and 1 GiB of scratch per layer at 1M versus SGLang's index_select copy; 38e0d93 makes mixed union/direct selections 5.8–37.5% faster.

In the last 16384-row chunk of a 1M prefill, logits and top-k are 57% and 42% of the indexer time, and without the split every TP rank repeats them. With the split, each attention-TP rank selects an equal share of the rows and an in-place all_gather_into_tensor completes the selections (TP2: 1.43 ms for 16384 rows). SGLang splits only chunks of ≥ 2048 rows averaging ≥ 32768 compressed keys per row, about twice the measured TP2 break-even.

SGLang TP2 (Qwen3.8-Flash-Next-PTPC-FP8, --context-length 1000000 with YaRN, C1, 350 output tokens, mean of 2 runs):

Input tokens 131072 262144 524288 999648
TTFT (s) 8.45 17.48 38.06 86.06
TTFT, split indexer (s) 8.46⁴ 17.25 (−1.3%) 36.17 (−5.0%) 76.18 (−11.5%)
TPOT (ms) 7.11 7.15 7.29 7.43

⁴ No chunk reaches the split threshold. Decode is unchanged; TPOT with the split is within 0.2 ms.

With SGLang's native indexer, the ~1M request took 229.1 s TTFT and 13.61 ms TPOT. At 12000/350 (C1–C8), PyHIP QSA gives +32–40% (TP2) and +40–52% (TP4) output throughput over native QSA (benchmarks/qsa/readme.md §3).

Validation

  • QSA tests at 3b90a93: QSA_REPLAY_GPU=6 python -m pytest -q -p no:cacheprovider tests/ops/qsa/test_attention.py tests/ops/qsa/test_indexer.py → 120 passed.
  • SGLang qwen38-flash-next/qsa-1m (b1abbb0) with this PR: test/registered/kernels/test_pyhip_qsa.py → 8 passed (17 subtests).
  • A TP2 service with SGLANG_TEST_PYHIP_QSA=1 (YaRN, 1M context, 37 requests including a 999648-token prompt) checks attention and the prefill/graph-decode indexer against native in all 12 QSA layers of both ranks; all checks pass with the split indexer off (010b0e2) and on (b1abbb0: per rank, 93 prefill and 309 graph-decode indexer checks per layer and 1116 attention checks).

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.
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).
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.
Copilot AI balanced review requested due to automatic review settings October 31, 2026 09:15

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 critical defects allow output aliasing to corrupt slot IDs and cause full-size prefills to exceed FlyDSL’s signed-int32 tensor-dimension limit.

4 open issues
What changed in this PR

Extends the QSA attention and indexer work from #57 to support 1M-token contexts, using the AITER sparse-prefill kernel structure.

Changes:

  • Adds in-place paged K/V access, wider addressing, and revised attention scratch and packing policies.
  • Raises indexer capacity to 262144 compressed keys and reorganizes logits storage and decode statistics.
  • Expands long-context, paged-pool, graph-replay, and numerical validation coverage.
File Description
tests/​ops/​qsa/​test_indexer.py Adds wide-key and 1M-context indexer cases.
tests/​ops/​qsa/​test_attention.py Integrates op tests and adds paged-pool and packing checks.
tests/​ops/​qsa/​sparse_prefill_op_test.py Adds reference, functional, graph, and performance cases.
tests/​ops/​qsa/​_benchmark.py Recognizes renamed attention and split top-k kernels.
tests/​ops/​qsa/​_attention.py Adds paged K/V construction and invocation helpers.
src/​pyhip/​ops/​qsa/​flydsl/​sparse_prefill_direct_packed.py Implements packed direct attention with slot-table support.
src/​pyhip/​ops/​qsa/​flydsl/​sparse_prefill_common.py Centralizes platform settings and shared kernel helpers.
src/​pyhip/​ops/​qsa/​flydsl/​indexer.py Raises context limits and revises logits chunk planning.
src/​pyhip/​ops/​qsa/​flydsl/​indexer_logits.py Writes prefill logits in key-block-major order.
src/​pyhip/​ops/​qsa/​flydsl/​indexer_decode.py Accumulates statistics for split decode selection.
src/​pyhip/​ops/​qsa/​flydsl/​attention.py Updates dispatch, scratch management, and paged-input handling.
src/​pyhip/​ops/​qsa/​flydsl/​attention_union.py Removes the superseded union implementation.
src/​pyhip/​ops/​qsa/​flydsl/​attention_prepare.py Removes the superseded preparation implementation.
src/​pyhip/​ops/​qsa/​flydsl/​attention_direct.py Removes the superseded direct implementation.
src/​pyhip/​ops/​qsa/​flydsl/​attention_direct_packed.py Removes the superseded packed-direct implementation.

Review effort: Balanced

Comment thread src/pyhip/ops/qsa/flydsl/attention.py Resolved
Comment thread src/pyhip/ops/qsa/flydsl/indexer.py Resolved
Comment thread src/pyhip/ops/qsa/flydsl/attention.py Resolved
Comment thread tests/ops/qsa/test_indexer.py Resolved
…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]>

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 packed-buffer address overflow can corrupt data, oversized slot tables can fail launches, and BQ21/BQ42 variants lack pytest correctness coverage.

2 open issues
2 previously missed issues

In code that hasn't changed since last review

Medium severity Guard slot-table dimensions and request bases against int32 overflow

src/​pyhip/​ops/​qsa/​flydsl/​attention.py:276

A slot table for 2,049 one-row requests with 1,048,576-token contexts passes these guards but exceeds FlyDSL's signed-int32 dimension limit, causing the launch to fail. The last request's slot-table base also overflows the int32 metadata upload. Require kv_slots.numel() < 2**31 before creating the workspace, or partition the table and widen the request bases.

Medium severity Add correctness coverage for BQ21/BQ42 full-prefill variants

tests/​ops/​qsa/​test_attention.py:34

This matrix excludes the full-prefill cases that exercise BQ21/BQ42 for H6/H3; its largest full prefill has only 768 rows, below both thresholds on MI308X. With the former BQ42 regression removed and sparse_prefill_op_test.py excluded by python_files = test_*.py, these production variants lose pytest correctness coverage. Add platform-sized full-prefill cases that assert tiles 21/42 are selected and compare outputs with the reference.

3 resolved since last review

Review effort: Balanced

… 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]>

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 graph replay test can pass with a freed captured pointer because the memory-snapshot fallback incorrectly treats a missing allocator segment as still allocated.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Treat missing allocator segments as released scratch

tests/​ops/​qsa/​sparse_prefill_op_test.py:640

If the caching allocator returns the old segment to HIP, its address disappears from memory_snapshot() and this fallback reports that the scratch was not released. The assertion in test_qsa_graph_replay then passes even though the captured pointer is no longer allocated. These pointers come from PyTorch allocations, so treat a missing segment as released (or explicitly require a matching active allocation).

2 resolved since last review

Review effort: Balanced

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]>

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 because regression tests leave cross-window union block counts and membership unverified, a coverage gap omitted from the published review.

No open issues 🎉

Review effort: Balanced

PR tingqli#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]>

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

Independent gfx942 execution was unavailable, so the kernel’s synchronization, wide-buffer addressing, and scratch-lifetime changes still require numerical, boundary-safety, and graph-replay validation against the final revision.

No open issues 🎉

Review effort: Balanced

@luocheng25
luocheng25 merged commit 8027faa into tingqli:dev Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants