Skip to content

[FlyDSL] [JIT] Add adaptive-blocked K5 prefill h-recurrence in GDN - #5732

Open
johannes-graner wants to merge 50 commits into
mainfrom
jograner/gdn-prefill-chunk-SILOTIGER-1112
Open

johannes-graner wants to merge 50 commits into
mainfrom
jograner/gdn-prefill-chunk-SILOTIGER-1112

Conversation

@johannes-graner

@johannes-graner johannes-graner commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The gated-delta-rule (GDN) prefill K5 hidden-state recurrence currently ships as a serial,
single-launch emit. A blocked parallel-scan implementation existed in the tree but was
reachable only from bench harnesses. A same-harness, cache-defeated A/B showed the blocked
path beats serial at every measured shape once its partitioning is made count-driven rather
than a fixed block size.

This PR adds the blocked path as a single unified FlyDSL K5 path, wired into
dispatch behind a regime gate, with the existing serial emit as the fallback.
There is no public API change: chunk_gated_delta_rule_fwd_h_flydsl_opt
keeps its signature and return contract, so any shape the gate rejects behaves exactly as before.

Technical Details

The K5 recurrence carries a [V, K] hidden state across chunks. The blocked path partitions
each sequence's chunks into segments (host-scheduled map) and runs three eager FlyDSL launches: build-map
(per-block local products), carry (fp32 carry checkpoints at block boundaries), and emit (re-seed from the block carry and emit outputs).

Partitioning is count-driven per sequence, not a fixed block size:

block_chunks = max(12, ceil(ceil(seq_len / 64) / target_segments))

target_segments = 8 which fills the emit grid at small T and self-limits to the saturating
block size at large T, so one default covers the shape range.

Regime gate. The blocked path is taken only when all of the following hold; any miss falls
through to the unchanged serial emit:

  • B == 1; gate g present (head-major, g_head_major), no gk; use_exp2; bf16_convert_trunc
  • K == V == 128, chunk size BT == 64
  • num_decodes == 0, num_decode_tokens == 0; no state-pool indices; not in-place
  • output_final_state=True, save_new_value=True, snapshot_bf16=True
  • bf16 k/w/u; SSM state cache fp32 or bf16; gfx950; not under stream capture
  • every sequence length > 0, and the longest sequence >= 96 chunks (_BLOCKED_MIN_CHUNKS)
  • work ratio: blocks * H <= 6 * max_chunks (_BLOCKED_MAX_WORK_PER_CHUNK), where blocks is the total over all sequences

During stream capture the dispatch always falls back to the serial emit. The blocked entry point raises on a zero-length sequence; the gate never routes one to it.

Numerics. The blocked path is a reassociated affine scan (fp32 carry checkpoints at block
boundaries), so it is ~1 BF16 ULP off the uninterrupted serial recurrence by construction. Its distance to the fp32
reference is of the same order as serial's.

AOT replay integration. Upstream #6956 moved FlyDSL AOT to replay-based
compilation. This PR extends that shared framework; review from the authors of #6956 is
requested on these changes:

  • XCD count is a replay device-profile field mirroring CU_NUM: job key num_xcds, env AITER_NUM_XCDS set by dry_run, and chip_info.get_num_xcds() honors it.
  • DEVICE_PARTS in replay.py lists the real (num_xcds, cu_num) parts per arch: gfx942 (8, 304) MI300X/MI325X, (6, 228) MI300A, (4, 80) MI308X; gfx950 (8, 256) MI350X/MI355X, (4, 128) MI350P.
  • Each AOT module declares XCD_VARIANTS as a tuple of arches to fork; _with_xcd_variants expands a job over those parts. A job with a cu_num (a tuned row) forks only to parts of its arch with that cu_num, and an unknown cu_num raises ValueError; a job without one (the blocked module) forks to every part of the arch. chunk_gdn_h uses ("gfx942", "gfx950"), chunk_gdn_blocked uses ("gfx950",). The chunk_gdn_h prebuild is 1344 jobs; the 368 shipped tuned rows are all gfx942 cu_num=80 (MI308X, 4 XCDs) and build only the 4-XCD variant.
  • chunk_gdn_blocked.py is a replay module enrolled in AOT_MODULES with gfx950 jobs; chunk_gdn_h.py adapted.
  • Runtime calls chip_info.get_num_xcds() (default 8, a prebuilt variant) instead of a local probe.
  • The dense wrapper passes lengths=(T_flat,), avoiding a device-to-host .tolist().

Test Plan

op_tests/test_flydsl_linear_attention_prefill.py: correctness is checked against the fp32 torch reference recurrence
ref_chunk_gated_delta_rule_fwd_h at rtol = atol = 2e-2, applied independently to the h
snapshots, v_new, and the final state (the bar the serial path already holds to), not
bit-exactness against the serial kernel, which the reassociated scan is not expected to match.

The blocked sweep is a 16-row CLI matrix, plus the existing Qwen3.5-35B sweep:

  • --context-lens: 8257, 8192,0, 8257,4097
  • --blocked-mode: dense, varlen (dense rows with more than one prompt are skipped)
  • --blocked-state-dtype: bf16, fp32
  • --init-state: 1, 0

Each row asserts the path taken: 12 rows take the blocked path; the 4 (8192, 0) rows fail the gate on the zero length and take the serial path. The (8192, 0) rows also check that the empty sequence's final state equals its initial state.

op_tests/test_gated_delta_rule.py covers the existing GDN prefill path.
tests/test_flydsl_aot_replay.py covers the blocked replay jobs, the part expansion through _with_xcd_variants (rows fork 1:1 to (4, 80), every shipped (gfx, cu_num) has a part, an unknown cu_num raises, DEVICE_PARTS CU counts equal GFX_CU_NUMS_MAP), and distinct kernel identities for 4 and 8 XCDs.

Test Result

  • test_flydsl_linear_attention_prefill.py passes (gfx950): 16/16 blocked-matrix rows and the 16-row Qwen3.5-35B sweep (flydsl, triton, hip), every error within 2e-2.
  • test_gated_delta_rule.py: 183 passed, 2 skipped.
  • tests/test_flydsl_aot_replay.py: 16 passed. AOT replay CLIs: chunk_gdn_blocked gfx950 64/64 ok; chunk_gdn_h gfx942 is 1344 jobs (was 2688 before forking by real parts).
  • flydsl versions: the reviewer re-ran the replay tests, the blocked matrix and the sweep on flydsl 0.4.2 (the version main pins) at f7313ce with all passing; the review-fix commits since then (through 362a0fc451) were run on flydsl 0.4.1.
  • tp1 L4096 T8192 varlen bf16: 208 µs.
  • Performance (gfx950, cache-defeated, vs serial emit; applies to calls with output_final_state=True that pass the gate):
Shape Stock (serial) µs Adaptive µs Difference Speedup
N=1 / 8k 260.0 165.4 −36.4% 1.57×
N=1 / 16k 487.5 262.4 −46.2% 1.86×
N=1 / 32k 954.4 483.2 −49.4% 1.98×
N=2 / 8k 296.5 255.6 −13.8% 1.16×
N=2 / 16k 595.1 421.7 −29.1% 1.41×
N=2 / 32k 1140.6 768.1 −32.7% 1.49×

Submission Checklist


Co-authored-by: Mikko Tukiainen ([email protected])

PR Self-Review

Reviewed revision

283f060

Behavior and intent

Adds an adaptive blocked scan for GDN K5 prefill on gfx950: build_map, an fp32 carry, then emit, replacing the serial chunk recurrence when the gate passes (longest sequence at least 96 chunks, bounded blocks-times-heads work ratio, positive lengths). Other batches keep the serial kernel. The blocked kernels are enrolled in replay-based AOT with an XCD-count device-profile field and a per-arch table of real (XCDs, CUs) parts.

Validation and unverified scope

python3 -m pytest tests/test_flydsl_aot_replay.py gave 16 passed and python3 op_tests/test_flydsl_linear_attention_prefill.py passed 16/16 blocked-matrix rows and the 16-row Qwen3.5-35B sweep on gfx950 (GPU 6, flydsl 0.4.1, FlyDSL runtime cache disabled), all revalidated at 362a0fc451. The AOT replay CLIs gave chunk_gdn_blocked gfx950 64/64 ok and chunk_gdn_h gfx942 1344 jobs. The reviewer validated f7313ce on flydsl 0.4.2. Unverified: the review-fix commits on flydsl 0.4.2, a gfx942 GPU run, and a full PREBUILD_KERNELS wheel build end to end. Main's replay_env sets HIP_VISIBLE_DEVICES=-1, which aborted HIP on our node; that is pre-existing and unchanged here. Merged origin/main and moved the blocked-gate constants into aiter/ops/flydsl/gdn_blocked_constants.py so AOT parse_csv no longer imports the Triton GDN package on GPU-less hosts; verified with GPUs hidden (32 jobs, identical job list).

PR-specific question

In op_tests/test_flydsl_linear_attention_prefill.py the blocked rows would fail before this PR because each row asserts the path taken (blocked for 12 rows, serial for the 4 (8192, 0) rows) and the blocked path did not exist, and no canonical GDN test covers the 96-chunk gate, the work-ratio limit, or both state dtypes with and without an initial state. The AOT part is checked by tests/test_flydsl_aot_replay.py, which asserts distinct kernels for 4 and 8 XCDs and the (arch, cu_num) part forking.

Changed op tests

op_tests/test_flydsl_linear_attention_prefill.py: adds the 16-row blocked matrix (dense and varlen, bf16 and fp32 state, with and without an initial state), each row asserting the path taken against the fp32 reference. Before this PR the blocked recurrence had no test in the canonical GDN prefill suite, so none of these cases would have run. tests/test_flydsl_aot_replay.py (not under op_tests) covers replay XCD expansion.

@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; main branch always runs both MI35X and MI300X
multigpu 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: 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 5732 --add-label <label>

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 opt this PR out.

The adaptive blocked-scan K5 prefill path previously excluded FlyDSL
run-only deployments from its fast path because its three kernel launches
(build-map, carry, blocked-emit) were not AOT-prebuilt, while the serial
emit fallback was. Under FLYDSL_RUNTIME_RUN_ONLY=1 the blocked path would
have hit a cache-miss RuntimeError, so the regime gate routed run-only to
the serial emit.

Enroll all three blocked kernels for AOT prebuild and drop the run-only
gate clause so run-only takes the fast path too:

- Carry (chunk_gdn_carry_gfx950): convert blocks/requests from
  compile-time ints to fx.Int32 runtime kernargs, so the builder cache
  key is partition-independent and AOT-enumerable (one variant per
  use_initial_state instead of one per (blocks,requests)). Bit-parity
  verified against the pre-conversion kernel.
- New chunk_gdn_blocked AOT family (build-map/carry/emit phases) deriving
  its (H,Hg) coverage from the serial K5 opt CSV, giving exact automatic
  parity with the serial-emit enrollment.
- Drop the not _flydsl_run_only() clause from the blocked-path regime
  gate; the helper is retained for its op_test consumer.
Accept fp32 or bf16 external initial_state/final_state at the blocked-path
boundary. Carry loads bf16 h0 via a 16-bit atom and promotes to fp32; emit
compiles its existing bf16 egress branch; final_state allocates in the
resolved dtype. All internal accumulation (maps, carry, entry, emit
recurrence) stays fp32. AOT enrolls bf16 emit+carry variants. Global
serial default is unchanged (still fp32); vLLM passes a bf16 tensor.
Double-buffer A in groups of eight K4 steps, issue all eight C loads before
the multiply loop, and prefetch the next block's first A group during the
current block's tail. Factor the step as _affine_step with the RHS width
as a compile-time parameter for a later log-depth scan.
- Carry kernel: specialize _affine_step to 16 columns.
- Prefill op test: plain candidate loop, shared ceildiv helper,
  inline blocked case; drop ragged refill variant.
- Shorten comments and docstrings.
@johannes-graner
johannes-graner requested a balanced review from Copilot September 30, 2026 08:08

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@johannes-graner
johannes-graner requested a balanced review from Copilot September 30, 2026 08:09

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

Copilot review overview

🔵 Needs a closer look

The new GPU recurrence needs human validation, and unresolved run-only deployment and blocked-path coverage gaps remain.

Review effort: Balanced
Findings: 1 High severity · 4 Medium severity

Open (5)

Comment thread aiter/ops/prefill_batch_metadata.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.

Copilot review overview

🟡 Changes recommended

The dense metadata cache grows without eviction, and the documented gate and test coverage remain incomplete.

Review effort: Balanced
Findings: 2 Medium severity

Open (2)
Resolved since last review (5)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Document or support all regime gate conditions

aiter/​ops/​flydsl/​linear_attention_prefill_kernels.py:963

The PR description presents its regime gate as exhaustive, but these additional conditions are not listed. In particular, g_head_major defaults to False, so a token-major caller can satisfy every documented condition yet silently miss the blocked path; save_new_value=False, in-place state, natural-exp mode, and non-truncating conversion do likewise. Either support these forms or document the complete gate so applicability and performance claims are accurate.

Replace the hard-coded blocked case list with --context-lens,
--blocked-mode, --blocked-state-dtype and --init-state swept through
itertools.product; bf16 and fp32 state both covered by default.

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.

Copilot review overview

🟡 Changes recommended

The dispatch can allocate excessive scratch for highly batched short prompts and repeatedly synchronize sequence lengths to the host.

Review effort: Balanced
Findings: 1 High severity

Open (1)
Resolved since last review (2)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Avoid cu_seqlens host sync when adaptive metadata is cached

aiter/​ops/​flydsl/​linear_attention_prefill_kernels.py:976

For varlen callers that omit prefill_metadata, this calls cu_seqlens.tolist() before _resolve_adaptive_k5_metadata can inspect its tensor-attached cache. Consequently every repeated eligible forward incurs a blocking device-to-host synchronization even after both the existing prologue and adaptive schedule are cached. Check the adaptive cache using tensor identity/version, T, and target_segments first, and derive/store host lengths only on a cache miss.

Require the longest sequence to have at least 64 chunks and
total_blocks * H <= 6 * max_chunks. Serial time tracks the longest
sequence while blocked time tracks total block-head work, so packed
batches of short prompts fall back to serial; this also bounds the
maps/entry scratch.

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.

Copilot review overview

🔵 Needs a closer look

The build-map launch can use a stream from the wrong GPU, breaking multi-device correctness and launch ordering.

Review effort: Balanced
Findings: None

Resolved since last review (1)
Previously missed (3)

In code that hasn't changed since last review

Medium severity Add the missing CLI entry point for direct AOT compilation

aiter/​aot/​flydsl/​chunk_gdn_blocked.py:344

This new AOT module has no main/__main__ entry point, so python -m aiter.aot.flydsl.chunk_gdn_blocked exits successfully without compiling anything. That differs from every sibling AOT module and defeats the direct compile-smoke workflow documented in aiter/aot/flydsl/README.md:34-38; add the same CLI/job runner wiring used by chunk_gdn_h.py:333-399.

Medium severity Use the input tensor device when selecting the CUDA stream

aiter/​ops/​flydsl/​linear_attention_prefill_kernels.py:1131

This launch takes the stream from the process's current CUDA device rather than from k.device. If a caller passes tensors on a non-current GPU, build-map can launch with a stream owned by another device, and it will not be ordered with the carry/emit launches below, which correctly select the tensor device. Use the input device here as well.

Medium severity Count final-state output traffic when no initial state exists

op_tests/​test_flydsl_linear_attention_prefill.py:710

The final-state tensor is written for every row, including init_state=0, but its traffic is counted only when h0 exists. Consequently the reported TB/s undercounts every no-initial-state row, while rows with h0 correctly count both the input and output state. Count ref_fs unconditionally as the final-state output.

@johannes-graner

Copy link
Copy Markdown
Contributor Author

Thanks for the 0.4.2 run. All 24 inline threads are addressed in 66cfe046cf, ff6b9710cd, 35f4fdb9bb, 1f7f4fc2db, 8533bb34b9 (replies inline). The empty-request carry branch is removed and the blocked entry raises on a zero length. The blocked AOT module now reuses XCD_VARIANTS with (xcds, cu_num) pairs; keying chunk_gdn_h's variants by (arch, cu_num) is deferred to a follow-up. The description is updated: 16-row CLI matrix, full gate list, 0.4.2 note replaced by your validation. Revalidated at 8533bb34b9 on GPU 6 (gfx950, flydsl 0.4.1): tests/test_flydsl_aot_replay.py 12 passed, blocked matrix 16/16, Qwen3.5-35B sweep 16/16 (flydsl/triton/hip). The new commits are not yet run on 0.4.2. On the squash message: the merger should drop the branch name (it carries the ticket ID) from the default squash message.

…ports

Move the blocked-gate constants to a dependency-free module so the AOT
collector no longer imports the Triton GDN package on GPU-less build hosts.
The runtime module re-exports the names unchanged.
@zufayu
zufayu removed the request for review from coderfeli November 11, 2026 06:49
@zufayu zufayu assigned xytpai and unassigned coderfeli Nov 11, 2026
@zufayu
zufayu requested a review from coderfeli November 11, 2026 06:49
…chunk-SILOTIGER-1112

# Conflicts:
#	tests/test_flydsl_aot_replay.py
…chunk-SILOTIGER-1112

# Conflicts:
#	tests/test_flydsl_aot_replay.py
@samremes
samremes requested a review from yadaish November 19, 2026 08:09
…chunk-SILOTIGER-1112

# Conflicts:
#	aiter/ops/flydsl/linear_attention_prefill_kernels.py
sources.py now requires every variable a cache's sources read to be declared; chip_info.get_num_xcds reads AITER_NUM_XCDS.
Copilot AI balanced review requested due to automatic review settings December 4, 2026 07:37

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 raw AITER_NUM_XCDS value causes cache misses for equivalent specializations, and the unbound carry factory bypasses the exported-object cache, preventing full AOT reuse during inference.

2 open issues

Review effort: Balanced

Comment thread aiter/aot/flydsl/sources.py Resolved
Copilot AI balanced review requested due to automatic review settings December 4, 2026 07:56

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

Reapproving.

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 stale cached sequence boundaries and divergent architecture detection threaten correctness, while permissive output checks can miss corrupted tiles.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants