Repository navigation
[FlyDSL] [CI] [Feature] Enable gfx1250 paged attention decode with FP8 and BF16 - #6462
Conversation
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.
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.
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.
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%.
|
Ask: can The test below reproduces it with M3 shapes. Feel free to take it into Why M3 sends that many sequences, and resultsM3 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 ( 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.
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.
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.
|
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.
Second ask: can the planner compile once per size bucket instead of once per row count? All sizes, both dtypesTested 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).
Correctness, planner cost, and how this was run
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: |
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]>
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]>
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'sflydsl==0.4.0pin.Changes
pa_decode/traits.py,op_lds.py,op_gemm.py, andpipeline.pyfiles alongside the CDNA classes. Keep compilation and launch inpa_decode_kernel.pythrough the sharedcompile_pa_decode_tileentry point.max_batch_sizeto planning/preparation and--max-batch-sizeto 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.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.
Paired BF16 measurements use identical inputs before and after the packed-page pipeline, relative to merge commit
9b6a04af3034ea1d75e05564770e6fbb8f5387f7: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 withplan_pa_decode(..., max_batch_size=32768). The same graph timing protocol gives: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.0.000336, FP8 per-tensor0.003153, FP8 per-token0.003398, within the existingatol=rtol=0.005check. These configurations remain outside the repository.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.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.Gfx1250Pipeline, CDNA pipeline/staging classes, and shared compiler entry point retain their ASTs after adding the BF16 specialization.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_typenow infers it from the KV cache.