Skip to content

[FlyDSL] [CI] [Feature] Enable gfx1250 paged attention decode with FP8 and BF16 - #6462

Merged
coderfeli merged 44 commits into
mainfrom
enable-gfx1250-pa-decode
Oct 21, 2026
Merged

coderfeli merged 44 commits into
mainfrom
enable-gfx1250-pa-decode

Conversation

@fsx950223

@fsx950223 fsx950223 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enable planned FlyDSL paged-attention decode on gfx1250 with FP8 and native BF16 K/V caches. The wave32 WMMA backend supports BF16/FP16 queries, causal multi-token decode, windows, sinks, and reusable GPU work plans.

Merged main at 033e8bda9c6d8271847acb72971668d6f207e914, retaining its FlyDSL GPU planner algorithm and adapting its updated partition reducer to wave32. Validation uses main's flydsl==0.4.0 pin.

Changes

  • Add a four-wave gfx1250 backend with asynchronous K/V staging, TDM for supported layouts, FP8 Q/P normalization, native BF16 operands, and FP32 accumulation/statistics. Support page16/64/128 and head dimensions 64 or multiples of 128 through 1024.
  • Place gfx1250 traits, memory/staging operations, WMMA helpers, and pipeline in the existing pa_decode/traits.py, op_lds.py, op_gemm.py, and pipeline.py files alongside the CDNA classes. Keep compilation and launch in pa_decode_kernel.py through the shared compile_pa_decode_tile entry point.
  • Extend dispatch and main's register/LDS partition reducer to gfx1250. Infer compute type from the KV cache when omitted; reject scales for native BF16.
  • Write output directly for one-partition gfx1250 plans when sinks are absent and query/output strides match. Split the wide BF16 D1024/G16/QL4 transposed-page128 specialization into four query CTAs.
  • Keep FP8 D256/G8/QL4 full-attention queries fused over packed 128-token pages for scalar and per-token scales, sharing K/V transfers between query tiles.
  • Extend packed FP8 LDS staging to transposed page16 caches at D128/D256 with at most 16 query rows per CTA. Each wave gathers its own page, and two LDS buffers overlap the next four pages with computation. Reuse the existing packed WMMA operand readers and fused PV accumulation.
  • Add a packed BF16 page128 pipeline for transposed caches at D64/D128/D256. Keep Q in registers, overlap next-page TDM with computation through two LDS buffers, and accumulate PV into the rescaled running output. D256 supports up to 32 query rows per CTA; other layouts/shapes retain the existing pipeline. Exact V-tail extents zero-fill unwritten slots.
  • Extend main's plan-preparation/autotuning API and CLI to gfx1250. The default work budget remains twice the CU count.
  • Add max_batch_size to planning/preparation and --max-batch-size to the tuning CLI. The default remains 4096; plans retain their chosen cap on refresh. Larger actual batches must fit the device's per-block LDS capacity.
  • Extend the existing parameterized PA tests to gfx1250 and run them in shard 0 of gfx1250 bring-up CI. Reconcile main's pipe-policy helper with the architecture-specific launch options.

No new standalone test functions, Kimi K3 configurations, benchmark files, docs/ files, or separate gfx1250 modules are included.

Performance

Measurements use bench_pa_decode.py from the validated revision, kept outside this PR. Hardware/software: gfx1250 with 256 CUs, FlyDSL 0.4.0, PyTorch 2.11.0+rocm10.1, HIP 7.16.26315. BF16 queries, transposed page128 caches, budget512, seven rounds, twelve replays, 32 calls per graph. Timings include decode and reduction, excluding planning, allocation, and compilation.

Configuration Median Useful KV bandwidth Max absolute reference error
FP8 B64/64K, D256, H64/KV8, QL4, per-tensor scales 1.097 ms 15.65 TB/s 0.0001744
Same, per-token scales 1.042 ms 16.48 TB/s 0.0001737
BF16 B4/1K, D1024, H16/KV1, QL4 53.19 µs 0.315 TB/s 0.0002014
BF16 B64/64K, D256, H64/KV8, QL1 2.411 ms 14.25 TB/s 0.00001354
BF16 B64/64K, D256, H64/KV8, QL4 3.112 ms 11.04 TB/s 0.00001570
BF16 B64/64K, D128, H64/KV4, QL4 1.050 ms 8.18 TB/s 0.00002661

Paired BF16 measurements use identical inputs before and after the packed-page pipeline, relative to merge commit 9b6a04af3034ea1d75e05564770e6fbb8f5387f7:

B64/64K configuration Previous pipeline Packed BF16 pipeline Latency reduction
D256, H64/KV8, QL1 3.048 ms 2.411 ms 20.9%
D256, H64/KV8, QL4 4.068 ms 3.112 ms 23.5%
D128, H64/KV4, QL4 1.818 ms 1.050 ms 42.3%

Fresh comparisons against main's gfx1250 Gluon implementation at B64/64K, D256, H64/KV8 measured QL1 at 2.408 ms for FlyDSL versus 2.128 ms for public Gluon 3D. QL4 measured 3.107 ms for FlyDSL versus 4.651 ms for native Gluon 3D using main's one-segment configuration, or 4.267 ms with two segments (including Triton segment reduction). These are measured configurations, not an exhaustive Gluon tuning search.

MiniMax-M3 sparse-layer prefill uses B32768 length-1 query rows, H16/KV1/D128, shuffled page16 caches, a shared 4096-page pool, and lengths min(row + 1, 2048). Opt into this batch with plan_pa_decode(..., max_batch_size=32768). The same graph timing protocol gives:

KV dtype Decode + reduction Planning + decode + reduction Decode rows/s Relative L2 error
BF16 3.191 ms 3.320 ms 10.27M 0.00139
FP8, per-token scales 0.872 ms 0.984 ms 37.58M 0.01792

Paired FP8 measurements on identical inputs, relative to 9bb5ee0bdb2e37181762817e0e0f25f50ee3b1ec, show decode + reduction improving from 2.711 ms to 0.872 ms (3.11x, 67.8% lower latency). Including planning, latency improves from 2.839 ms to 0.984 ms (2.88x). The page16 kernel uses 116 VGPRs and 37,952 bytes of LDS, with zero scratch or spills.

All outputs are finite. Accuracy checks cover ten rows at page boundaries and the 2048-token cap, using relative L2 limits of 0.01 (BF16) and 0.06 (FP8). The sparse-row benchmark/configurations remain outside the repository. FP8 now uses packed page16 staging in the existing pipeline; BF16 page16 retains padded staging.

Useful bandwidth counts logical K/V bytes once. Graph replays reuse inputs; this metric is not a physical-memory counter. Sparse-row bandwidth counts logical reads for each row while reusing the shared page pool.

Testing

  • op_tests/test_flydsl_pa_decode.py: 119 passed, 5 skipped in 131.93 seconds on gfx1250 with FlyDSL 0.4.0 and runtime caching disabled. Coverage includes mixed/empty contexts, FP8/BF16, windows, sinks, QL4, graph replay, planner refresh, and main's new partition/staging cases. Skips cover unsupported gfx9 BF16 D192 cases and rejection cases for inputs accepted on gfx1250.
  • Local Kimi K3 accuracy validation: 12 passed, Q heads64/KV heads4/D128, BF16 queries, native BF16 or FP8 per-tensor/per-token caches, QL1/QL4, mixed contexts and 64K context. Maximum absolute errors across these checks: BF16 0.000336, FP8 per-tensor 0.003153, FP8 per-token 0.003398, within the existing atol=rtol=0.005 check. These configurations remain outside the repository.
  • Packed BF16 pipeline local accuracy validation: 36 passed in 39.73 seconds, covering D64/D128/D256, QL1/QL3/QL4, Kimi H64/KV4/D128, mixed/empty contexts, page boundaries, windows, sinks, direct output, FP16 queries, graph replay, and NaNs in unwritten V tails. Configurations remain outside the repository.
  • Packed FP8 page16 validation: 16 focused tests passed, plus 28 local comparisons at D128/D256 with mixed/empty contexts, page-boundary lengths, varying scalar/per-token scales, windows, sinks, and query-negating graph replay. Local comparisons require relative L2 < 0.06 against FP32 and before/after atol=rtol=0.001. Both previous and new kernels can exceed the generic pointwise 0.005 bound on these varied-scale inputs; the paired check verifies the optimization preserves the previous result. Configurations remain outside the repository.
  • All benchmark configurations above pass reference accuracy checks, including the paired BF16 and fresh Gluon comparisons.
  • gfx942/gfx950 FP8/BF16 COMPILE_ONLY=1: D128/G16/page128/QL4 and D256/G8/page64/QL4 tiles; register, LDS, and XCD/sink reducer paths; FlyDSL planner. All 24 ISA comparisons are byte-identical to latest main using the same FlyDSL 0.4.0 wheel. Numerical validation on gfx942/gfx950 hardware was not performed.
  • Main's CDNA classes/functions and the branch's four gfx1250 classes retain their ASTs after conflict resolution. The GPU planner function retains main's AST; its host wrapper adds the configurable batch cap. Test/helper function names match main.
  • Existing Gfx1250Pipeline, CDNA pipeline/staging classes, and shared compiler entry point retain their ASTs after adding the BF16 specialization.
  • Configurable batch cap: mixed/empty planner coverage and graph refresh at B4097/B8192/B16384; B32768 sparse BF16/FP8 decode; BF16 B4097 QL1/QL4 decode and graph refresh; autotune candidates and nondefault cached work budgets preserve the cap; default/custom bound, CLI, and LDS rejection checks. Validation scripts remain outside the repository.
  • Black, Ruff, and whitespace checks pass on the final implementation.

Generic padded paths require finite unwritten V tails. The earlier BF16 page16/plain-V/FP16-query benchmark combination remains unvalidated.

Dependencies and API

No additional dependency beyond main's FlyDSL 0.4.0 pin. Retain main's explicit-work-plan API and gfx942/gfx950 implementations. Omitting compute_type now infers it from the KV cache.

fsx950223 and others added 30 commits September 23, 2026 03:46
Use the unaligned MTP window union to bound reducer specialization,
while retaining the CU-count plan cap, scratch layout and query selector.
Cover partition-boundary crossings during refresh in the generic test.

Validated on dzm-mi355-gpu34-dev: 196 unit tests passed, with two
70-case native accuracy/performance sweeps. W1024/B200/QL4 improves
from 80.18 us to 29.14 us, excluding plan construction and refresh.

Signed-off-by: fsx950223 <[email protected]>
Include pending varlen KV buffer loads, prefetch scheduling and compact reduction. Bound dense planned work for native QL2/QL4 query splitting and cover the selector and address boundaries in the generic unit test.

Add offline model/batch budget sweeps with fixed-plan timing, strict FP32 validation and static recommendation keys. Keep context distributions in benchmark metadata only, and preserve failed numerical cases without recommendations.

Validate with MI355 native A/B and generic GPU tests, 22 CPU tuner tests, Black 26.5.1 and Ruff 0.16.0. The existing short-context FP8 numerical limitation is not changed.

Signed-off-by: fsx950223 <[email protected]>
…de-oop

Preserve planned query splitting, unsigned KV buffer loads and prefetch ordering in the PA operation classes. Track the full helper source closure in offline tuning keys and test persistent-cache separation for wide/buffer specializations.
Always normalize Q rows by absmax and scale P before FP8 conversion, compensating both scales in the QK and output stages. This prevents small queries and probability tails from underflowing on the per-tensor KV path.

Add four regression cases with quantized FP8 KV caches and non-unit scales. Validated on MI355: all 264 native PA decode tests pass.
Use one parameterized correctness test with shared input construction and an independent FP32 reference. Cover query dtypes, FP8 KV quantization, cache layouts, partitioning, plans, windows and sinks, including the small-Q and probability-tail regressions.

Remove the benchmark CLI, tuning CSV tests and internal scheduling assertions from this file. Run the unit test once through pytest in CI.

Validated on MI355: all 80 cases pass. The four original scaling regressions still fail against the old shortcut implementation.
Remove static tile dispatch, direct output, uniform scratch layouts, and
the static reducer branches. All FlyDSL decode calls now use work plans,
including a partition cap of one, with sinks applied once by the reducer.

Configure partition caps on plan_pa_decode and make the optional decode
arguments keyword-only. Update the tuner and generic unit test, and adapt
Gluon's existing FlyDSL reducer fallback to provide reduction metadata.

Validate on MI355 with 80 generic cases, six Gluon reducer cases, tuner
smoke, and ten graph/eager replays. All replay outputs match the previous
planned implementation bit for bit, including its two-token FP8 error.
Use the existing C++ PS reducer first and fall back directly to Triton.
Remove FlyDSL imports, dispatch checks, and reduction-plan metadata from
the Gluon wrapper.
Require a PADecodePlan for every decode call and reject None before
launch setup. Remove automatic plan construction, budget lookup, and the
decode-only tuned_file parameter.

Make the generic unit test create a plan for every case, including the
default partition cap.
Use common representable Q/K values with tail probabilities near 2^-12.
The previous fixture landed on a coarse FNUZ probability rounding point
and failed the MI300X CI job.

Keep the reference, tolerance, and case matrix unchanged. Unscaled FP8
probabilities still round all tails to zero, preserving the regression
check for omitted probability scaling.
Add wave32 FP8 WMMA K64/K128, native eight-element conversion and async K/V LDS staging behind the existing work-plan interface. Select the FP8 format and compilation cache by tensor device, and adapt partition reduction to wave32 with full-wave statistic broadcasts.

Cover gfx1250 with the generic PA suite, partition/graph/stride/wide-address regressions and FFM CI. Validated 95 GPU tests, five offline tuning searches, native cache hits/misses, emitted ISA, and gfx942/gfx950 compile-only checks.

Signed-off-by: who who who <[email protected]>
Extend packed D128 staging to 128-token tiles. For D256 per-token FP8
page128 full attention, reuse page lookup and overlap K/V TDM with
asynchronous global-to-LDS scale copies using two LDS buffers.

Add a random-input variable-length/fixed-context benchmark and packed
page-boundary regressions. Remove the standalone gfx1250 test module,
update CI references, and keep BF16 test helpers self-contained.

Record paired timing, FETCH_SIZE, and ATT/resource evidence. Best measured
physical read bandwidth is 54.91% (12.820 TB/s), up from 50.84%; the 60%
target remains unmet. Document the budget2048 varlen regression.

Validation: 88 FP8 tests passed; 137 FP8/BF16 tests collected. Black and
Ruff checks passed. The native-BF16/page16 GPU fault was not reproduced.

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.

Move the gfx1250 compiler and launch definitions into pa_decode_kernel.py
and remove the separate gfx1250 module. Reuse the shared context import
and give the architecture cache an explicit name. The public dispatcher
and nested GPU kernel/launcher bodies keep their existing behavior.

Validation: 110 passed, 4 skipped with FlyDSL 0.3.4.1 and cache disabled.
Three native FP8/BF16 benchmarks retain byte-identical ISA and reference
errors, with latency changes below 0.3%. gfx942/gfx950 FP8/BF16 compile
checks also retain byte-identical ISA. Black, Ruff and whitespace pass.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 06:25

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.

Retain main PA planner and updated partition reducer, add wave32 reducer support, and reconcile the existing pipe-policy helper with gfx1250 launch options. Keep Kimi K3 accuracy configurations outside the PR.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 07:40

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.

Keep native BF16 Q in registers and retain packed 128-token K/V pages in two LDS buffers. Fuse PV accumulation and zero-fill exact tail extents. Enable D64/D128/D256 transposed page128 caches, with D256 bounded to 32 query rows per CTA.

Validated on gfx1250 with FlyDSL 0.4.0: 119 tests passed, 5 skipped, plus 36 local accuracy cases. B64/64K D256 H64/KV8 latency improves 20.9% for QL1 and 23.5% for QL4; D128 H64/KV4 QL4 improves 42.3%.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 08:29

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.

@lirui927

Copy link
Copy Markdown
Contributor

Ask: can plan_pa_decode take more than 4096 sequences? MiniMax-M3 sparse prefill on gfx1250 sends one sequence per prefill token, up to 32768 in one step, and the planner rejects every call past 4096.

The test below reproduces it with M3 shapes. Feel free to take it into op_tests/test_flydsl_pa_decode.py.

Why M3 sends that many sequences, and results

M3 sparse layers run prefill per token as decode: each token is a length-1 sequence with its own page-16 block table, and its length is capped at top-k 16 blocks x 128 = 2048. One call has as many sequences as the step has prefill tokens (--max-num-batched-tokens 32768 in the M3 config). Past 4096, ATOM sends the call to unified attention.

Shapes are one TP4 rank: 16 Q heads, 1 KV head, head_dim 128, page 16, SHUFFLE cache. 12 passed on gfx1250 with this PR merged and flydsl 0.3.4.1; the 4096 check is unchanged at fbf1fce.

rows bf16 fp8 per-token
16, 2048, 4096 matches fp32 reference matches fp32 reference
4097, 8192, 32768 ValueError: plan supports batches in [1, 4096] same
test_flydsl_pa_m3_sparse_rows.py
# MiniMax-M3 sparse-layer prefill through FlyDSL pa_decode, gfx1250.
# Each prefill token is one length-1 sequence with its own page-16 block table;
# its length is capped at top-k 16 blocks * 128 = 2048.
# TP4 rank shapes: 16 query heads, 1 KV head, head_dim 128, page 16, SHUFFLE cache.
import pytest
import torch

from aiter.ops.flydsl.pa_decode import pa_decode, plan_pa_decode
from aiter.ops.triton.utils.types import e4m3_dtype
from op_tests.triton_tests.attention.test_unified_attention import shuffle_kv_cache

NUM_Q_HEADS, NUM_KV_HEADS, HEAD_DIM, PAGE = 16, 1, 128, 16
TOPK_TOKENS = 16 * 128
POOL_PAGES = 4096
SCALE = HEAD_DIM**-0.5
DEV = "cuda"


def make_inputs(num_rows, kv_dtype, seed=0):
    g = torch.Generator(device=DEV).manual_seed(seed)
    lens = torch.clamp(torch.arange(1, num_rows + 1, device=DEV), max=TOPK_TOKENS).int()
    max_pages = TOPK_TOKENS // PAGE
    bt = torch.argsort(torch.rand(num_rows, POOL_PAGES, device=DEV, generator=g), dim=1)
    bt = bt[:, :max_pages].int().contiguous()
    q = torch.randn(num_rows, NUM_Q_HEADS, HEAD_DIM, device=DEV, generator=g).bfloat16()
    k = torch.randn(POOL_PAGES, PAGE, NUM_KV_HEADS, HEAD_DIM, device=DEV, generator=g)
    v = torch.randn(POOL_PAGES, PAGE, NUM_KV_HEADS, HEAD_DIM, device=DEV, generator=g)
    if kv_dtype == "bf16":
        k, v = k.bfloat16(), v.bfloat16()
        ks = vs = None
        k_ref, v_ref = k.float(), v.float()
    else:  # per-token scales [num_blocks, num_kv_heads, block_size]
        ks = (k.abs().amax(-1) / 448.0).clamp_min(1e-6).permute(0, 2, 1).contiguous()
        vs = (v.abs().amax(-1) / 448.0).clamp_min(1e-6).permute(0, 2, 1).contiguous()
        k = (k / ks.permute(0, 2, 1)[..., None]).to(e4m3_dtype)
        v = (v / vs.permute(0, 2, 1)[..., None]).to(e4m3_dtype)
        k_ref = k.float() * ks.permute(0, 2, 1)[..., None]
        v_ref = v.float() * vs.permute(0, 2, 1)[..., None]
    kc, vc = shuffle_kv_cache(k, v)
    return q, kc, vc, ks, vs, k_ref, v_ref, bt, lens


def run_flydsl(q, kc, vc, ks, vs, bt, lens, kv_dtype):
    plan = plan_pa_decode(lens, NUM_KV_HEADS, query_length=1)
    rows = NUM_Q_HEADS // NUM_KV_HEADS
    shape = (int(plan.num_kv_heads), int(plan.capacity), rows)
    exp_sums = torch.empty(shape, dtype=torch.float32, device=DEV)
    max_logits = torch.empty(shape, dtype=torch.float32, device=DEV)
    tmp_out = torch.empty(*shape, HEAD_DIM, dtype=q.dtype, device=DEV)
    out = torch.empty_like(q)
    pa_decode(out, q, kc, vc, lens, bt, SCALE, 1,
              compute_type=torch.bfloat16 if kv_dtype == "bf16" else e4m3_dtype,
              key_scale=None if ks is None else ks.unsqueeze(-1),
              value_scale=None if vs is None else vs.unsqueeze(-1),
              exp_sums=exp_sums, max_logits=max_logits, temporary_output=tmp_out,
              work_plan=plan)
    return out


def reference_rows(q, k_ref, v_ref, bt, lens, rows):
    outs = []
    for i in rows:
        n = int(lens[i])
        idx = bt[i, : (n + PAGE - 1) // PAGE].long()
        kk = k_ref[idx].reshape(-1, HEAD_DIM)[:n]
        vv = v_ref[idx].reshape(-1, HEAD_DIM)[:n]
        p = torch.softmax(q[i].float() @ kk.T * SCALE, dim=-1)
        outs.append(p @ vv)
    return torch.stack(outs)


@pytest.mark.parametrize("kv_dtype", ["bf16", "fp8"])
@pytest.mark.parametrize("num_rows", [16, 2048, 4096])
def test_m3_sparse_rows_within_planner_limit(num_rows, kv_dtype):
    q, kc, vc, ks, vs, k_ref, v_ref, bt, lens = make_inputs(num_rows, kv_dtype)
    out = run_flydsl(q, kc, vc, ks, vs, bt, lens, kv_dtype)
    torch.cuda.synchronize()
    rows = sorted({0, 1, 15, 16, 17, 255, 256, 2047, 2048} & set(range(num_rows))
                  | {num_rows - 1})
    ref = reference_rows(q, k_ref, v_ref, bt, lens, rows)
    rel = ((out[rows].float() - ref).norm() / ref.norm()).item()
    tol = 1e-2 if kv_dtype == "bf16" else 6e-2  # fp8 also quantizes Q and P
    assert torch.isfinite(out).all()
    assert rel < tol, f"rows={num_rows} kv={kv_dtype} rel={rel:.3e}"


@pytest.mark.parametrize("kv_dtype", ["bf16", "fp8"])
@pytest.mark.parametrize("num_rows", [4097, 8192, 32768])
def test_m3_sparse_rows_over_planner_limit(num_rows, kv_dtype):
    q, kc, vc, ks, vs, k_ref, v_ref, bt, lens = make_inputs(num_rows, kv_dtype)
    with pytest.raises(ValueError, match=r"plan supports batches in \[1, 4096\]"):
        run_flydsl(q, kc, vc, ks, vs, bt, lens, kv_dtype)

Add max_batch_size to planning and tuning, with a 4096 default retained on plan refresh. Expose --max-batch-size in the tuning CLI and reject actual batches exceeding per-block LDS capacity. Preserve the GPU planner algorithm.

Validated 119 existing tests (5 skipped), larger-batch planning and graph refresh, and MiniMax-M3 B32768 BF16/FP8 sparse decode accuracy and performance.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 09:30

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.

Gather one page16 K/V slice per wave into packed LDS and overlap the next four pages through a second buffer. Reuse packed WMMA operand readers and fused PV accumulation for D128/D256 transposed FP8 caches with up to 16 query rows per CTA.

Validated on gfx1250 with FlyDSL 0.4.0: 119 tests passed, 5 skipped, plus 28 local accuracy comparisons. MiniMax-M3 B32768 H16/KV1 D128 FP8 decode improves from 2.711 ms to 0.872 ms; including planning, from 2.839 ms to 0.984 ms.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 09:44

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.

@lirui927

Copy link
Copy Markdown
Contributor

Ask: with BF16 KV at M3 sparse prefill sizes, FlyDSL runs 1.9x to 2.5x slower than gfx1250 unified attention from 4096 rows up; the script below reproduces it. max_batch_size itself works, and FP8 is 2.2x to 3.6x faster than unified at every size.

BF16 rows FlyDSL us unified us
4096 353.0 185.5
8192 776.5 333.7
32768 3222.2 1261.8

Second ask: can the planner compile once per size bucket instead of once per row count? compile_pa_decode_plan is cached on the exact batch (it sizes task_ends at compile time), so each new count costs about 18 ms. M3 sparse prefill sees a new count on most steps. Sizing task_ends by max_batch_size or a power-of-two bucket, with the live batch as a runtime argument, would compile once per bucket.

All sizes, both dtypes

Tested at 0cbd0b1 (flydsl 0.4.0) on gfx1250, with M3 sparse-prefill shapes: one length-1 sequence per token, page 16, SHUFFLE cache, 16 Q heads, 1 KV head, head_dim 128, length min(p + 1, 2048).

KV rows FlyDSL us unified us unified / FlyDSL
bf16 1024 50.0 73.7 1.47
bf16 4096 353.0 185.5 0.53
bf16 8192 776.5 333.7 0.43
bf16 16384 1617.7 641.5 0.40
bf16 32768 3222.2 1261.8 0.39
fp8 per-token 1024 50.4 112.1 2.23
fp8 per-token 4096 123.0 437.2 3.55
fp8 per-token 8192 247.1 874.1 3.54
fp8 per-token 16384 499.9 1751.3 3.50
fp8 per-token 32768 986.2 3514.4 3.56
Correctness, planner cost, and how this was run
  • With plan_pa_decode(..., max_batch_size=rows), 4097, 8192, 16384 and 32768 rows match an fp32 reference for BF16 and FP8 per-token KV; without it the planner still rejects past 4096. The test from the earlier comment, extended: 20 passed.
  • Planner: the first call for a new row count compiles, about 18 ms (205 ms for the first in the process); a refresh of an existing plan takes 0.03 to 0.16 ms.
  • Eager timing with CUDA events, 20 calls after 3 warm-up calls, plan built outside the timed loop. The FP8 rows used feat(attention): per-token fp8 KV and split-K verify in gfx1250 unified attention #6660 for per-token scales in unified attention; the BF16 rows use the unified path already on main.
  • Decode shapes are faster than unified on this head for both dtypes (for example BF16 B4 x 8K: 6.7 vs 8.2 us; FP8 B3 x 227K: 23.5 vs 182.6 us).
bench_flydsl_pa_bf16_sparse_rows.py (BF16 case slower than unified)
# MiniMax-M3 sparse prefill rows on gfx1250, BF16 KV: FlyDSL pa_decode vs unified_attention.
# One length-1 sequence per prefill token, page 16, SHUFFLE cache, length min(p + 1, 2048).
# TP4 rank shapes: 16 Q heads, 1 KV head, head_dim 128. Eager timing with events.
import torch

from aiter.ops.flydsl.pa_decode import pa_decode, plan_pa_decode
from aiter.ops.triton.attention.unified_attention import unified_attention
from op_tests.triton_tests.attention.test_unified_attention import shuffle_kv_cache

NUM_Q_HEADS, NUM_KV_HEADS, HEAD_DIM, PAGE = 16, 1, 128, 16
TOPK_TOKENS = 16 * 128
POOL_PAGES = 4096
SCALE = HEAD_DIM**-0.5
DEV = "cuda"


def make_inputs(num_rows, seed=0):
    g = torch.Generator(device=DEV).manual_seed(seed)
    lens = torch.clamp(torch.arange(1, num_rows + 1, device=DEV), max=TOPK_TOKENS).int()
    bt = torch.argsort(torch.rand(num_rows, POOL_PAGES, device=DEV, generator=g), dim=1)
    bt = bt[:, : TOPK_TOKENS // PAGE].int().contiguous()
    q = torch.randn(num_rows, NUM_Q_HEADS, HEAD_DIM, device=DEV, generator=g).bfloat16()
    k = torch.randn(POOL_PAGES, PAGE, NUM_KV_HEADS, HEAD_DIM, device=DEV, generator=g)
    v = torch.randn(POOL_PAGES, PAGE, NUM_KV_HEADS, HEAD_DIM, device=DEV, generator=g)
    kc, vc = shuffle_kv_cache(k.bfloat16(), v.bfloat16())
    return q, kc, vc, bt, lens


def event_us(fn, iters=20):
    for _ in range(3):
        fn()
    torch.cuda.synchronize()
    a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    a.record()
    for _ in range(iters):
        fn()
    b.record()
    torch.cuda.synchronize()
    return a.elapsed_time(b) * 1000 / iters


print("rows | flydsl us | unified us | unified / flydsl")
for rows in (1024, 4096, 8192, 16384, 32768):
    q, kc, vc, bt, lens = make_inputs(rows)
    plan = plan_pa_decode(lens, NUM_KV_HEADS, query_length=1, max_batch_size=max(4096, rows))
    shape = (int(plan.num_kv_heads), int(plan.capacity), NUM_Q_HEADS // NUM_KV_HEADS)
    es = torch.empty(shape, dtype=torch.float32, device=DEV)
    ml = torch.empty(shape, dtype=torch.float32, device=DEV)
    tmp = torch.empty(*shape, HEAD_DIM, dtype=q.dtype, device=DEV)
    o1, o2 = torch.empty_like(q), torch.empty_like(q)
    cu = torch.arange(rows + 1, dtype=torch.int32, device=DEV)

    def fly():
        pa_decode(o1, q, kc, vc, lens, bt, SCALE, 1, compute_type=torch.bfloat16,
                  exp_sums=es, max_logits=ml, temporary_output=tmp, work_plan=plan)

    def uni():
        unified_attention(q=q, k=kc, v=vc, out=o2, cu_seqlens_q=cu, seqused_k=lens,
                          max_seqlen_q=1, max_seqlen_k=int(lens.max()), softmax_scale=SCALE,
                          causal=True, window_size=(-1, -1), block_table=bt, softcap=0,
                          q_descale=None, k_descale=None, v_descale=None,
                          shuffled_kv_cache=True, backend="gluon")

    tf, tu = event_us(fly), event_us(uni)
    print(f"{rows} | {tf:.1f} | {tu:.1f} | {tu / tf:.2f}", flush=True)

Run from the aiter root on gfx1250: python bench_flydsl_pa_bf16_sparse_rows.py. It prints one row per size. The numbers above came from a run with the same inputs and timing; this standalone copy drops the FP8 half, which needs #6660.

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

LGTM.

@coderfeli
coderfeli merged commit 9326517 into main Oct 21, 2026
@coderfeli
coderfeli deleted the enable-gfx1250-pa-decode branch October 21, 2026 01:50
lirui927 pushed a commit to ROCm/ATOM that referenced this pull request Oct 26, 2026
gfx1250 has no gluon paged decode, so MiniMax-M3 dense and sparse decode had
no paged kernel there. ROCm/aiter#6462 adds a gfx1250 backend to FlyDSL's
pa_decode, with BF16 and per-token FP8 KV.

- FlyDSL paged decode is on by default on gfx1250; ATOM_PA_FLYDSL=1 still
  opts in on gfx942/gfx950. BF16 KV goes to FlyDSL only where gluon is absent.
- Dense decode on gfx1250 takes the unified arm, which hands FlyDSL every call
  it accepts and passes the SHUFFLE V cache as its 5D view (FlyDSL reads a 4D
  V as the plain layout).
- Sparse rows on gfx1250 skip pa_fwd_asm, which has no code objects there.
- A plan past 4096 sequences sets max_batch_size, up to what one block's LDS
  holds (81792 on gfx1250), so a sparse prefill step stays on FlyDSL.
- The explicit-plan API probe imports aiter.ops.flydsl.pa_decode by module
  path: the package lazily exports a pa_decode function of the same name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lirui927 pushed a commit to ROCm/ATOM that referenced this pull request Oct 26, 2026
gfx1250 has no gluon paged decode, so MiniMax-M3 dense and sparse decode had
no paged kernel there. ROCm/aiter#6462 adds a gfx1250 backend to FlyDSL's
pa_decode, with BF16 and per-token FP8 KV.

- FlyDSL paged decode is on by default on gfx1250; ATOM_PA_FLYDSL=1 still
  opts in on gfx942/gfx950. BF16 KV goes to FlyDSL only where gluon is absent.
- Dense decode on gfx1250 takes the unified arm, which hands FlyDSL every call
  it accepts and passes the SHUFFLE V cache as its 5D view (FlyDSL reads a 4D
  V as the plain layout).
- Sparse rows on gfx1250 skip pa_fwd_asm, which has no code objects there.
- A plan past 4096 sequences sets max_batch_size, up to what one block's LDS
  holds (81792 on gfx1250), so a sparse prefill step stays on FlyDSL.
- The explicit-plan API probe imports aiter.ops.flydsl.pa_decode by module
  path: the package lazily exports a pa_decode function of the same name.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants