Skip to content

[FlyDSL] Fuse decode SWA cache-write into qk_norm_rope_quant - #3776

Merged
valarLip merged 2 commits into
mainfrom
feat/flydsl-qknorm-fused-swa-write
Jun 17, 2026
Merged

valarLip merged 2 commits into
mainfrom
feat/flydsl-qknorm-fused-swa-write

Conversation

@valarLip

Copy link
Copy Markdown
Collaborator

Summary

  • Add an optional fused SWA ring scatter to flydsl_qk_norm_rope_quant. When swa_kv is provided, each token's post-norm/rope bf16 KV row is also written into swa_kv[slot, pos % cache_size, :] in the same launch, where slot = state_slot_mapping[batch_id_per_token[t]].
  • This replaces the standalone swa_write Triton launch + a full [T, D] KV HBM round-trip per layer per decode step — the row is already in registers right before the kv_out store, so the scatter is a second _store_bf16_vec_g of the same data.

Details

  • New constexpr kv_write flag on _build_kernel / compile_flydsl_qk_norm_rope_quant; gets its own disk-cache dir via the "kvw" kernel-name suffix.
  • Kernel gains 6 params (swa_kv, state_slot_mapping, batch_id_per_token, swa_slot_stride, swa_pos_stride, swa_cache_size). batch_id is loaded i64 and clamped for an OOB-safe slot load; the store is predicated on batch_id >= 0 so CG-pad tokens (-1 sentinel) are skipped.
  • BF16 only — raises if combined with quant. Passing no swa_kv reproduces the existing kernel exactly (dummy pointers bound, kv_write=False).

Test plan

  • New bit-exact unit test test_flydsl_qk_norm_rope_quant_kv_write — MTP-1 (token→seq not identity), distinct per-seq slots, -1 pad-sentinel skip; asserts the fused ring == gather of kv_out and that kv_out/q_out are unchanged vs the no-swa_kv path.
  • Independent cross-check vs the real standalone swa_write Triton kernel across 24 configs (bs∈{1,2,4,8} × MTP∈{0,1,3} × pad∈{0,3}): all max_diff=0.

Add an optional fused SWA ring scatter to the flydsl qk_norm+rope kernel:
when swa_kv is provided, each token's post-norm/rope bf16 KV row is also
written into swa_kv[slot, pos % cache_size, :] in the same launch, where
slot = state_slot_mapping[batch_id_per_token[t]]. This replaces a separate
swa_write Triton launch + a full [T, D] KV HBM round-trip per layer per
decode step.

The scatter reuses the existing _store_bf16_vec_g store of the row already
held in registers, gated on a new constexpr kv_write flag (distinct disk-
cache dir via the "kvw" name suffix). batch_id is loaded as i64 and clamped
for an OOB-safe slot load; the store is predicated on batch_id >= 0 so
CG-pad tokens (-1 sentinel) are skipped. BF16 only (rejected with quant).
Passing no swa_kv reproduces the existing kernel exactly.

Adds a bit-exact unit test (test_flydsl_qk_norm_rope_quant_kv_write)
covering the MTP-1, distinct-slot, and -1 pad-sentinel cases.
@valarLip
valarLip requested review from a team and Copilot June 17, 2026 08:44
@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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
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 3776 --add-label <label>

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.

Pull request overview

This PR extends the FlyDSL flydsl_qk_norm_rope_quant decode kernel to optionally fuse an SWA ring-buffer KV cache write into the same launch (BF16-only), avoiding an extra swa_write launch and an additional KV round-trip through HBM.

Changes:

  • Add a kv_write compile-time flag and kernel-name suffix (kvw) to build/cache a variant that also scatters KV rows into swa_kv[slot, pos % cache_size, :].
  • Extend the kernel + launcher signature with SWA ring pointers/strides and token→batch/slot mapping inputs, plus Python wrapper plumbing and validation for the new feature.
  • Add a new unit test + smoke invocation to validate bit-exactness of the fused scatter and correct skipping of -1 pad sentinels.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
op_tests/test_flydsl_qk_norm_rope_quant.py Adds a bit-exact unit test for the fused SWA KV scatter path and runs it as a pre-sweep smoke test.
aiter/ops/flydsl/kernels/qk_norm_rope_quant.py Implements the fused SWA cache-write path behind a kv_write constexpr, adds wrapper args/validation, and updates kernel naming/caching.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +1094 to +1103
if swa_kv.dim() != 3 or swa_kv.shape[2] != D:
raise ValueError(f"swa_kv must be [S, C, D={D}], got {tuple(swa_kv.shape)}")
if swa_kv.dtype != torch.bfloat16:
raise TypeError(f"swa_kv must be bf16, got {swa_kv.dtype}")
if not swa_kv.is_contiguous():
raise ValueError("swa_kv must be contiguous")
if state_slot_mapping.dim() != 1 or state_slot_mapping.dtype != torch.int32:
raise TypeError("state_slot_mapping must be 1-D int32")
if batch_id_per_token.dim() != 1 or batch_id_per_token.dtype != torch.int64:
raise TypeError("batch_id_per_token must be 1-D int64")
swa_slot_stride = 0
swa_pos_stride = 0
swa_cache_size = 1
swa_kv_arg = kv_out # bf16 dummy
Comment on lines +748 to +752
if const_expr(kv_write):
bid_rsrc = _ptr_buffer_resource(batch_id_per_token)
bid_i64 = buffer_ops.buffer_load(
bid_rsrc, bid_t, vec_width=1, dtype=T.i64
)
@valarLip
valarLip merged commit 90c7585 into main Jun 17, 2026
42 of 43 checks passed
@valarLip
valarLip deleted the feat/flydsl-qknorm-fused-swa-write branch June 17, 2026 12:30
valarLip added a commit that referenced this pull request Jun 18, 2026
The fused decode SWA scatter (added in #3776) hardcoded an int64
buffer_load for batch_id_per_token. The V4 decode producers are not
uniformly int64 though: the MTP-draft path reuses the int32
cu_seqlens_q slice as the per-token batch id. Feeding that int32 tensor
tripped the wrapper's "batch_id_per_token must be 1-D int64" check, so
DeepSeek-V4-Pro MTP decode raised a TypeError before the first token —
the server never came up and the accuracy job timed out.

batch_id values are bounded by the batch size, far below 2^31, so int32
is always sufficient. Standardize on int32: the kernel loads batch_id at
i32 width (dropping the trunc), the wrapper validates int32, the dummy
is int32, and the smoke test now builds an int32 batch_id.

Validated end-to-end: DeepSeek-V4-Pro MTP3 GSM8K (3-shot) flexible
0.9477 / strict 0.9484, above the 0.94 CI threshold; decode drained
cleanly with no TypeError.
valarLip added a commit to ROCm/ATOM that referenced this pull request Jun 18, 2026
…1272)

* feat: fuse V4 decode SWA cache-write into qk_norm_rope_maybe_quant

Thread the SWA ring scatter through the qk_norm+rope bridge so the V4
decode path no longer launches a standalone swa_write per layer. When
swa_kv is provided, the post-norm/rope KV row is written into
swa_kv[slot, pos % cache_size, :] (slot = state_slot_mapping[
batch_id_per_token[t]]) inside the same kernel:

- flydsl path: fuses the scatter into the qk_norm launch (no extra
  kernel, no [T, D] KV HBM round-trip), via the new swa_kv /
  state_slot_mapping / batch_id_per_token args on flydsl_qk_norm_rope_quant.
- Triton fallback: emits the existing swa_write as a separate launch
  (driven by swa_cu_seqlens_q + state_slot_mapping) so both backends have
  identical side effects.

deepseek_v4.py decode deletes its standalone swa_write call and passes
the SWA args through the bridge instead; prefill is unchanged (still
writes its in-chunk SWA tail via swa_write after sparse_attn). BF16 only.

Requires the matching aiter change (ROCm/aiter#3776) for the flydsl
fused-scatter kernel support.

* ci: drop GLM-5-FP8 from benchmark matrix to stay under 256 cells

The nightly atom-benchmark grid had grown to 264 fully-expanded matrix
cells, exceeding GitHub Actions' hard limit of 256 configurations per
job. Remove the GLM-5-FP8 benchmark variant (superseded by GLM-5.2-FP8,
which is retained) and its workflow_dispatch checkbox (keeping it in sync
with the catalog prefixes). Matrix now resolves to 250 cells.

Accuracy validation (models_accuracy.json) and the dashboard color map
are left unchanged — GLM-5-FP8 stays covered there.

* fix: standardize V4 batch_id_per_token on int32 for fused SWA scatter

The fused decode SWA scatter loads batch_id_per_token at int32 width
(see ROCm/aiter#3793). The producers were int64, which raised
"batch_id_per_token must be 1-D int64" on the V4-Pro MTP decode path
(server failed to start -> accuracy job timed out).

Make all batch_id_per_token producers int32:
- v4_batch_id_per_token CpuGpuBuffer (model_runner path) int64 -> int32
- batch_id numpy sources (per-fwd + MTP draft) int64 -> int32
- sglang / vllm plugin bridge batch_id buffers + numpy sources -> int32

int32 indices are accepted by torch advanced-indexing (indexer meta) and
by the triton kernels (tl.load is dtype-agnostic); the explicit
.to(torch.int64) casts in csa_translate_pack / sglang remain and tolerate
int32 input. batch_id values are bounded by batch size, far below 2^31.

Validated end-to-end: DeepSeek-V4-Pro MTP3 GSM8K (3-shot) flexible
0.9477 / strict 0.9484, above the 0.94 CI threshold; decode drained
cleanly with no TypeError.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants