Skip to content

[Triton/Gluon] [ASM] [HIP] MHAv4 per-row block-sparse geometry, LSE and ragged KV on gfx950 - #6575

Merged
vgokhale merged 23 commits into
ROCm:mainfrom
nsakkine:mha_v4-sparse-geometry
Nov 6, 2026
Merged

vgokhale merged 23 commits into
ROCm:mainfrom
nsakkine:mha_v4-sparse-geometry

Conversation

@nsakkine

@nsakkine nsakkine commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

MHAv4: per-row block-sparse geometry, LSE and ragged KV on gfx950

Motivation

Block-sparse mha_v4 had one tile geometry per arch: every gfx950 sparse row routed on 256x128, every gfx942 row on 256x64. mha_v4_kv_tile() returned that one value and callers shaped their block masks to it. That stops working once an arch ships more than one geometry. It also limited three things models need:

  • Finer routing. Models that route on blocks smaller than 128 tokens (64x64) had no row to run on.
  • LSE per row. Sorted-sparse rows export the log-sum-exp since [ASM] [HIP] Mha v4: LSE on sorted-sparse, kernel race fixes, gfx950 refresh #6841, so a sparse result can be merged with another partial (for example a KV shard on another rank). Whether a call may ask for it was decided by a hard-coded (Q, V) list in Python. Once one recipe has several rows, that has to follow the row the launcher actually dispatches.
  • Ragged key lengths. A sparse call required Sk % ts_kv == 0, so callers had to pad K/V with zero keys. That padding is not free: each zero key still draws softmax weight exp(-max).

This PR makes the geometry, LSE and ragged-KV support properties of the manifest row, and adds the rows and queries to use them.

What changes

Manifest and launcher (csrc/py_itfs_cu/asm_mha_v4_fwd.cu, hsa/*/fmha_v4_fwd/fmha_v4_fwd.csv)

  • New manifest columns: lut_max, lse, ragged_kv. They describe what a code object can do; they are not requests. Columns a manifest omits read as 0.
    • lut_max: the number of KV tiles per sequence the row's staged LUT can hold. The launcher refuses a key length whose LUT could exceed it, instead of overrunning the staged region.
    • lse: return_lse is honoured only on a row that declares it. Otherwise the call raises, rather than leaving the buffer unwritten. This replaces the Python (Q, V) allow-list; the gfx942 "LSE not validated" gate stays.
    • ragged_kv: seqlen_k % ts_kv == 0 is required only on rows without it. Rows with it mask the short last KV block themselves.
  • find_config keys on ts_qo/ts_kv. A block-sparse launch must name its geometry, so a missing row is an error, not whichever row the manifest listed first. The workgroup size is derived from the row's ts_qo (four waves for a 64-row tile).
  • The sorted work-table order is selectable per call with AITER_MHA_V4_WORK_ORDER=lpt|head|raster.
    • lpt, the default, is the existing global longest-first order.
    • head sorts longest-first within each head, so in-flight work items share that head's K/V in L2. It ranks every LUT count up to the 65536 lut_max distinctly, in both the fused and the ATen sort.
    • raster is the identity.
  • The gfx942 manifest gains the new columns (sparse lut_max 7679 / 7871, no lse, no ragged_kv), so its behaviour is unchanged. Its sparse objects are renamed MI300/fwd_hd128_{i8fp8,fp8}_sparse_256x64.co.

gfx950 sparse rows

Q/K V default tile lut_max (default tile) 64x64 row LSE ragged KV
BF16 BF16 256x64 (was 256x128) 8192 new yes yes
BF16 FP8 256x64 (was 256x128) 8192 new yes yes
INT8 FP8 256x128 8192 new yes yes
FP8 FP8 256x128 7680 new yes yes
MXFP8 FP8 256x128 8192 new yes yes
FP8 MXFP6 (FP6-P) 256x128 8192 new yes yes
MXFP6 FP8 256x128 8192 new yes yes
MXFP6 MXFP6 (FP6-P) 256x128 65536 new yes yes
MXFP6 MXFP4 (FP6-P) 256x128 8192 new yes yes
MXFP4 MXFP4 (FP6-P) 256x128 8192 new yes yes

Every 64x64 row has lut_max 65536. A row with lut_max 8192 stages its LUT in LDS, which still covers 1M keys at a 128-key tile and 512K keys at a 64-key tile. The 65536 rows walk the LUT from HBM.

  • Every sparse object is rebuilt with the LSE store and a masked ragged last KV block, so every gfx950 dense and sparse row now declares lse.
  • Object names now carry their geometry and V packing (*_sparse_256x128.co, *_sparse_256x64.co, *_sparse_64x64.co, *_fp6p_sparse_*.co).

Refreshed 256x64 / 256x128 sparse objects

The default-tile sparse objects are rebuilt from the current generators. Dense objects are unchanged.

  • Numerics.
    • BF16, BF16/FP8 (O), MXFP6/FP8, MXFP6, FP8/MXFP6 and MXFP6/MXFP4 match the previous sparse objects bitwise.
    • MXFP4 matches on O bitwise; its LSE is within 3e-6.
    • FP8, INT8/FP8, MXFP8 and BF16/FP8 no longer apply an LSE debias that their dense rows do not have, so with an all-true mask they now reproduce the dense row bitwise.
  • LUT placement. MXFP6/MXFP4 now stages its LUT in LDS, so its lut_max goes 65536 → 8192. MXFP6 keeps the HBM walk because the LDS build was slower in every case measured. INT8/FP8 and MXFP8 lut_max go 7680 → 8192.
  • Performance. Kernel device time through mha_v4 with return_lse=True on MI355X. Shape: B=1, H=16, Sq=Sk=16384, hd128, 40% of blocks selected.
Q/K V before (µs) after (µs)
BF16 BF16 845 810
BF16 FP8 669 560
INT8 FP8 486 459
FP8 FP8 403 402
MXFP8 FP8 412 415
FP8 MXFP6 (FP6-P) 366 364
MXFP6 FP8 378 375
MXFP6 MXFP6 (FP6-P) 337 327
MXFP6 MXFP4 (FP6-P) 321 311
MXFP4 MXFP4 (FP6-P) 292 283

MXFP8 is about 0.7% slower. It is updated anyway so that its sparse numerics match its dense row like the other FP8-family recipes.

Python API (aiter/ops/mha_v4.py)

  • mha_v4 and mha_v4_packed take block_tile, which defaults to the recipe's own geometry. The sparse launcher's pybind takes q_tile and kv_tile.
  • New geometry queries. They read the same manifest the launcher dispatches on, behind torch_compile_guard, so they trace under torch.compile(fullgraph=True):
    • mha_v4_operands(...): the seven values that pick a manifest row.
    • mha_v4_block_tile(operands, mode): the default sparse (q_tile, kv_tile) for a recipe.
    • mha_v4_block_tiles(operands, mode): every geometry a recipe has.
    • mha_v4_block_tiles_in_any_precision(mode): every geometry the GPU has, for error messages and capability checks.
    • mha_v4_kv_tile_for_q_tile(q_tile, operands, mode): the KV tile served at a Q tile, or 0 if none.
    • mha_v4_ragged_kv(operands, mode, block_tile=None): whether a row takes a key length that is not a multiple of its tile.
  • mha_v4_kv_tile takes operands and mode. Where the rows disagree, it raises instead of returning a tile the mask may not match.
  • block_attn_mask_to_ragged_lut picks BLOCK_KB from the row length: the next power of two, clamped to [128, 2048]. On MI300X that is within 1.2× of the best width from 32 to 4096 KV blocks, where a fixed 128 or a 512 cap ran up to 2× slower on long rows.
  • bench_sage.py asks the geometry per recipe instead of per arch, and --mha4-block-tile benchmarks a non-default geometry (for example the 64x64 rows).

Fixes

  • MX Q-scale padding. The 64x64 sparse objects gather a whole query tile of Q scales with unbounded global loads, so a partial final tile reads past the logical sequence. The MXFP8, MXFP6 and MXFP4 Q quantizers again back their scales with a zeroed 256-row tile. The launcher now checks that backing for every MX Q descale.
  • MX V-scale backing on the 64x64 rows.
    • The problem. The 64x64 FP6-P sparse objects, with V in MXFP6 or MXFP4, gather V scales through a raw pointer, 512 bytes from each 64-token block's first token. When the last selected block is the second half of a 128-token scale tile, that read ends 256 bytes past the tensor.
    • The fix. The MXFP6 FP6-P producer now reserves 1 KiB of zeroed slack, as the MXFP4 V producer already did. After selecting the row, the launcher checks for that slack on rows with a 64-token KV tile, for both MXFP6 and MXFP4 V.
    • Dense and 256x128 rows. These objects bound the V-scale gather with a buffer descriptor, so a compact V scale gives bitwise the same output there. main's MXFP4 V check on every launch is therefore narrowed to the rows that need it. The MXFP4 K-scale check is unchanged.

Also

  • aiter/ops/mha_v4.md documents per-row geometry, lut_max, LSE and ragged KV.

Breaking changes

  • gfx950 BF16 and BF16/FP8 sparse masks are now in 64-key blocks, not 128. A mask built for the old geometry no longer matches. Build masks from mha_v4_block_tile(mha_v4_operands(...), mode) rather than assuming a size.
  • mha_v4_kv_tile() without operands raises on gfx950, because its rows no longer agree on one KV tile. Pass the operands and mode of the call being launched.
  • Direct callers of the sparse launcher must pass q_tile/kv_tile. A sparse launch with no geometry is refused. mha_v4 and mha_v4_packed pass it for you.
  • MX Q descales must be backed to a 256-row tile. Descales from the aiter.ops.mha_v4_quant producers already are. A hand-built Q descale with no slack is now refused at launch instead of risking an out-of-bounds read.
  • MXFP6 V descales on a 64x64 row must carry 1 KiB of slack. The aiter.ops.mha_v4_quant producers reserve it. A hand-built or cloned compact scale is refused on those rows, and is still accepted on dense and 256x128 rows.

Testing

op_tests/test_mha_v4_sparse.py and op_tests/test_mha_v4.py, run as scripts (python3 op_tests/test_mha_v4_sparse.py). On MI355X (gfx950): the sparse suite runs 290 checks with 5 skipped and 0 failed; the dense suite runs 238 checks with 0 failed. On gfx942 the sparse tests run against the existing MI300 objects.

New and changed checks:

  • Geometry queries:
    • test_mha_v4_block_tile_default_is_the_256_row_of_the_named_recipe
    • test_mha_v4_block_tile_refuses_to_guess_when_the_rows_disagree
    • test_mha_v4_kv_tile_for_q_tile_is_zero_when_unserved
    • test_mha_v4_rejects_a_geometry_with_no_row
    • test_mha_v4_block_mask_without_a_sparse_row_names_the_recipe
  • Ragged KV:
    • test_mha_v4_ragged_kv_answers_per_row
    • test_mha_v4_ragged_kv_is_false_on_gfx942
    • test_mha_v4_sparse_masks_a_ragged_last_block
    • test_mha_v4_sparse_rejects_ragged_key_length_on_a_padded_row (was ..._rejects_ragged_key_length; it now applies only to rows without ragged_kv)
  • LSE, over every gfx950 LSE row at both the default tile and 64x64:
    • test_mha_v4_dense_lse_matches_logsumexp
    • test_mha_v4_asking_for_the_lse_does_not_change_the_output
    • test_mha_v4_sparse_lse_covers_only_the_selected_blocks: a sparse row's LSE covers exactly the mass of the blocks its LUT selected.
    • test_mha_v4_packed_rejects_overlapping_lse_views: an LSE expanded from [1, 1, Sq] to [2, 3, Sq] is refused by both the dense and the sparse launch; a contiguous buffer of the same shape is accepted.
  • 64x64 rows:
    • test_mha_v4_sparse_64x64_all_true_mask_matches_dense
    • test_mha_v4_sparse_64x64_follows_the_lut
    • test_mha_v4_sparse_64x64_honours_a_mask_that_varies_per_query_tile
  • All recipes: test_mha_v4_sparse_all_true_mask_matches_dense and test_mha_v4_sparse_empty_row_writes_zeros are now parametrized over every recipe rather than per launcher.
  • Work order:
    • test_mha_v4_sparse_work_table_follows_the_work_order
    • test_mha_v4_sparse_work_table_rejects_an_unknown_work_order
    • test_mha_v4_sparse_work_table_orders_counts_through_65536: counts 65535 and 65536 keep longest-first order, in lpt and head order, on both sides of the 8192-entry hand-off to ATen.
  • Q-scale padding: test_mha_v4_q_scale_backing_storage_covers_query_tile checks that MXFP8, MXFP4 and MXFP6 Q scales carry a zeroed 256-row tile for sequence lengths 1, 255, 256, 257 and 513.
  • V-scale backing:
    • test_mha_v4_mx_v_scale_backing_storage_covers_the_64x64_gather (was test_mha_v4_mxfp4_v_scale_backing_storage_covers_lookahead_tiles) checks that the MXFP4 and MXFP6 FP6-P producers reserve the 1 KiB.
    • test_mha_v4_packed_mx_v_scales_need_backing_only_on_64x64_rows, for MXFP4 and MXFP6. A compact (cloned) V scale gives bitwise the same output as the producer-backed one on dense and 256x128, and is refused on 64x64, where the padded scale runs.
    • test_mha_v4_packed_rejects_unbacked_mxfp4_k_scales (was ..._rejects_unbacked_mx_scales) keeps the K-scale half.
  • LUT capacity: the sparse tests read each row's lut_max from the manifest, and test_mha_v4_sparse_bf16_rejects_lut_beyond_lds_capacity now trips the launcher's lut_max check.
  • test_mha_v4.py:
    • The MXFP4/FP8 LSE rejection check is removed, because LSE is now decided per manifest row and that recipe has no row.
    • The seqlens_k rejection test sizes its INT8/FP8 block mask from that recipe's own sparse tile.
    • FP8 parametrizations use the arch's native FP8 format.

PR Self-Review

Reviewed revision

ca81c65f20c1e035a5028673291eaae9c0e8dd65

Behavior and intent

What changes. Block-sparse mha_v4 geometry, LSE support and ragged-KV support become properties of the manifest row rather than of the arch:

  • The manifest gains lut_max, lse and ragged_kv columns. The launcher enforces them:
    • it refuses a key length whose LUT could exceed lut_max;
    • it honours return_lse only on rows with lse;
    • it requires Sk % ts_kv == 0 only on rows without ragged_kv.
  • find_config matches on ts_qo/ts_kv, so a sparse launch must name its geometry, and a geometry with no row is an error.
  • gfx950 ships two geometries per recipe:
    • BF16 and BF16/FP8 route on 256x64 (was 256x128); the quantized recipes stay on 256x128;
    • every recipe adds a 64x64 row;
    • every sparse row exports LSE and masks a ragged last KV block.
  • The default-tile sparse objects are rebuilt.
    • They are equal or faster on every recipe except MXFP8, which is about 0.7% slower.
    • FP8, INT8/FP8, MXFP8 and BF16/FP8 now share their dense row's LSE numerics (no debias).
    • MXFP6/MXFP4 stages its LUT in LDS (lut_max 8192).
  • Python adds block_tile on mha_v4/mha_v4_packed and the geometry queries (mha_v4_operands, mha_v4_block_tile, mha_v4_block_tiles, mha_v4_block_tiles_in_any_precision, mha_v4_kv_tile_for_q_tile, mha_v4_ragged_kv). mha_v4_kv_tile now takes operands and raises where rows disagree.
  • AITER_MHA_V4_WORK_ORDER=lpt|head|raster selects the sorted work-table order. The default, lpt, is the existing order. head ranks every count up to 65536 distinctly.
  • block_attn_mask_to_ragged_lut derives BLOCK_KB from the row length.
  • MX Q scales are again backed to a zeroed 256-row tile. The 64x64 objects gather Q scales with unbounded global loads, and the launcher checks that backing.
  • MX V scales carry 1 KiB of zeroed slack from the producers (now also MXFP6 FP6-P). The launcher requires it only on the 64x64 rows, whose V-scale gather is unbounded. main checked MXFP4 V on every launch and never checked MXFP6.

Why the existing behaviour is insufficient.

  • One KV tile per arch cannot describe a GPU that serves several geometries, so mha_v4_kv_tile() would hand callers a tile their mask may not match.
  • Models routing on 64-token blocks had no row at all.
  • LSE was allowed per (Q, V) pair in Python, which cannot follow the row actually dispatched once one recipe has several rows.
  • Sparse callers had to zero-pad K/V to a tile multiple, which biases softmax (each zero key still gets weight exp(-max)).
  • The old LUT conversion's fixed BLOCK_KB ran up to 2× slower on long rows.

Validation and unverified scope

Validated. Hardware: MI355X (gfx950); software: ROCm 10.1.0, torch 2.13.0. The JIT modules were rebuilt from the tested revision before testing.

  • Op tests at 50e9c08ef1, run from /tmp:

    Command Result
    PYTHONPATH=<aiter> python3 op_tests/test_mha_v4_sparse.py checks: 290 ran, 5 skipped, 0 failed
    PYTHONPATH=<aiter> python3 op_tests/test_mha_v4.py checks: 238 ran, 0 skipped, 0 failed

    The 5 skips are arch- or row-gated cases that do not apply to gfx950, for example test_mha_v4_ragged_kv_is_false_on_gfx942.

  • New guards fail without their fix. Run against the launcher built from the preceding revision:

    • test_mha_v4_sparse_work_table_orders_counts_through_65536 fails in head order on both the fused and the ATen path;
    • test_mha_v4_packed_rejects_overlapping_lse_views depends on a check the preceding revision did not have, because its two LSE stride checks accept an expanded view with strides [0, 0, 1].
  • Object A/B, performance and LUT placement were measured at 3683a2b208. The later commits change only host-side launcher checks and the work-table key, not objects or the default lpt order.

  • Old versus new sparse objects (A/B). The same aiter build ran against two AITER_ASM_DIR trees, one with the previous objects and one with the new ones.

    • Output bitwise equal: BF16, BF16/FP8 O, FP8/MXFP6, MXFP6/FP8, MXFP6, MXFP6/MXFP4.
    • MXFP4: O bitwise equal, LSE within 3e-6.
    • With an all-true mask at Sk=8192, FP8, INT8/FP8, MXFP8 and BF16/FP8 sparse output is bitwise equal to the dense row.
  • LSE against an fp32 reference. The mean LSE bias moved as follows, all within test tolerance:

    • FP8 −0.022 → −0.003;
    • INT8/FP8 −0.001 → +0.019;
    • MXFP8 −0.002 → +0.018;
    • BF16/FP8 +0.019, with O cosine 0.99930 → 0.99918.
  • Performance. Kernel device time from the torch profiler through mha_v4(..., return_lse=True), median of 40 launches. Shape: B=1, H=16, Sq=Sk=16384, hd128, random mask with 40% of blocks selected. Before → after, in µs:

    Recipe Before After
    BF16 845 810
    BF16/FP8 669 560
    INT8/FP8 486 459
    FP8 403 402
    MXFP8 412 415
    FP8/MXFP6 366 364
    MXFP6/FP8 378 375
    MXFP6 337 327
    MXFP6/MXFP4 321 311
    MXFP4 292 283
  • LUT placement (LDS versus HBM), timed in pairs across several densities and lengths:

    • MXFP6 with an LDS LUT was 0.15–1.2% slower in every case, so it keeps the HBM walk (lut_max 65536).
    • MXFP6/MXFP4 with an LDS LUT was 0.7–1.15% faster except at 95% sparsity (+1.2%), so it ships the LDS LUT (lut_max 8192).
  • V-scale bounds, from disassembly:

    • The dense and refreshed 256x128 MX-V objects load V scales through a buffer descriptor sized to one (batch, head) slab, so over-reads return 0.
    • The 64x64 FP6-P objects use raw global_load_dword and can read up to 256 bytes past the slab.
    • The compact-scale test confirms the first point at runtime.
  • Lint: ruff check --select F and black --check pass on all changed Python files.

Unverified.

  • gfx942 is not re-run at this revision. Its objects are only renamed, and its manifest declares lut_max with lse=0 and ragged_kv=0, so behaviour should be unchanged. The sparse tests have not been re-run on MI300X since the refresh.
  • The 64x64 objects are not part of this refresh. They are covered for correctness by the op tests, but have no performance comparison, since no previous row exists.
  • Performance is measured at one shape and density (above), plus the LUT-placement sweep. Batch > 1, GQA and short sequences are not benchmarked. The head and raster work orders are not benchmarked here.
  • lut_max is exercised at its limit only for BF16 (test_mha_v4_sparse_bf16_rejects_lut_beyond_lds_capacity). No row was launched at exactly lut_max KV tiles, and the 65536-tile HBM rows were not run near their limit (8M keys at 128-key tiles). The work-table ordering at 65536 is tested on the table alone.
  • bench_sage.py was not run at this revision, only linted.
  • kv_block_indices values are not range-checked on the host.
  • Old BF16 LUTs passed directly are not detected. A caller that passes a LUT triple directly to mha_v4_packed, without block_tile, gets the recipe's default geometry. A BF16 or BF16/FP8 LUT built for the old 128-key tile is therefore read as 64-key blocks. Nothing faults, because the indices stay in range, but the result is wrong. Block masks are shape-checked and are not affected.

PR-specific question

Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?

Path selection. The sorted-sparse path (manifest mode=1) is selected in only two ways:

  • mha_v4(..., block_mask=...);
  • mha_v4_packed(..., kv_block_indices=, lut_start=, lut_count=), where all three must be given or all omitted, otherwise it is a ValueError.

Without them, the dense path runs, and its manifest rows, objects and dispatch are unchanged.

Architecture.

  • gfx950 serves the new rows.
  • gfx942 keeps its two sparse rows: INT8/FP8 and FP8 at 256x64, with no LSE and no ragged KV.
  • Any other arch has no manifest row, so find_config raises.
  • LSE is additionally rejected in Python off gfx950 (_check_lse_capable).

Dtype and recipe. A launch must match a manifest row exactly on all of the following:

  • q_format, k_format, v_format, v_pack;
  • the three scale modes;
  • hdim_q = hdim_v = 128, mask = 0;
  • BF16 output with no output scale;
  • mode, ts_qo and ts_kv.

A sparse launch with q_tile/kv_tile unset is refused, so it cannot fall back to the first matching row. A geometry with no row raises a ValueError listing the recipe's geometries and the GPU's geometries.

Shape and host checks.

Boundary Invariant
block_mask Bool, on Q's device, shape [B, H, ceil(Sq/q_tile), ceil(Sk/kv_tile)] (or the 3-D form). A mask cut for another geometry fails the shape check.
Key length Sk % ts_kv == 0 unless the row declares ragged_kv; every gfx950 sparse row does, neither gfx942 row does. ceil(Sk/ts_kv) <= lut_max.
Per-batch seqlens_k Rejected on the sparse path.
GQA nhead_q % nhead_k == 0, power-of-two ratio up to 16.
Work table batch < 256, nhead < 256, q_tiles < 65536; LUT counts are ranked through 65536.
LUT tensors int32, on Q's device, 1-D; lut_start/lut_count have one entry per (batch, head, Q tile); kv_block_indices is non-empty.
MX Q descales Storage must cover a zeroed 256-row tile.
MX V descales (MXFP6, MXFP4) On rows with a 64-token KV tile, storage must cover the scale plus 1 KiB of zeroed slack.
LSE Only on rows with lse=1; the tensor must be float32 [B, Hq, Sq], contiguous, on Q's device. An expanded or otherwise overlapping view is refused before either launch.

The one unguarded case is the direct LUT triple described under Unverified: the LUT's KV-tile unit is not encoded in the tensors, so it is the caller's responsibility (mha_v4_block_tile(operands, mode) returns it).

Changed op tests

  • op_tests/test_mha_v4_sparse.py covers the new sparse behaviour, which nothing else tests:

    • Geometry queries: default tile, refusal when rows disagree, an unserved Q tile, a geometry with no row, and the error that names a recipe without a sparse row.
    • Ragged KV: per-row answers, false on gfx942, and a masked ragged last block compared with a reference. The old ragged-rejection test now covers only rows without ragged_kv.
    • LSE per row, at the default tile and 64x64: dense LSE against logsumexp, output unchanged when LSE is requested, and sparse LSE covering only the selected blocks.
    • 64x64 rows: an all-true mask against dense, LUT following, and a mask that varies per Q tile.
    • Work order: AITER_MHA_V4_WORK_ORDER ordering, the rejection of an unknown value, and distinct ranks for counts through 65536 on both sort paths.

    The all-true and empty-row checks are re-parametrized over every recipe instead of per launcher. The default-tile objects behave differently per recipe (geometry, LSE debias, LUT placement), so one launcher-level case would miss a regression in a single recipe. Each check targets a distinct launcher or manifest invariant, and none duplicates another check or a main test.

  • op_tests/test_mha_v4.py covers the dense-file guards this PR changes:

    • test_mha_v4_q_scale_backing_storage_covers_query_tile pins the 256-row zeroed Q-scale backing for MXFP8, MXFP6 and MXFP4 at sequence lengths around the tile boundary (1, 255, 256, 257, 513). Without it, a padding regression faults the GPU later at an unrelated synchronization point instead of failing a test.
    • The Q-backing check excludes gfx950 sparse rows, because the launcher check is what guards them.
    • V-scale backing:
      • test_mha_v4_mx_v_scale_backing_storage_covers_the_64x64_gather replaces the MXFP4-only lookahead test and adds the MXFP6 FP6-P producer.
      • test_mha_v4_packed_mx_v_scales_need_backing_only_on_64x64_rows pins where the launcher requires the slack: bitwise-equal output from a compact scale on dense and 256x128, and refusal on 64x64.
      • test_mha_v4_packed_rejects_unbacked_mxfp4_k_scales keeps the K-scale half of the old combined test.
    • test_mha_v4_packed_rejects_overlapping_lse_views pins the contiguous-LSE check on both launches.
    • The MXFP4/FP8 LSE rejection is removed, because LSE is now decided per manifest row and that recipe has no row.
    • The seqlens_k rejection test sizes its INT8/FP8 mask from that recipe's own sparse tile rather than from mha_v4_kv_tile(), which now raises on gfx950.
    • FP8 parametrizations use native_fp8_format() so the same cases run on gfx942 (FNUZ).

    These are changes to existing guards, not new coverage of sparse behaviour, so they do not overlap with test_mha_v4_sparse.py.

  • op_tests/op_benchmarks/triton/bench_sage.py is a benchmark, not a correctness test.

    • It is changed because it called mha_v4_kv_tile() with no operands, which now raises on gfx950. It now asks each recipe's manifest row for its geometry (mha4_operands → mha_v4_block_tile), so masks match the row it launches.
    • It adds --mha4-block-tile to benchmark a non-default geometry such as 64x64, which no other benchmark can select.
    • It is not run at this revision (see Unverified).

The sparse tile used to be one value per arch. On gfx950 it is now a
property of the manifest row: BF16 and BF16/FP8 route on 256x64, the
quantized recipes on 256x128, and every recipe also ships a 64x64 row
for models whose routing is finer than a 128-token block.

Manifest and launcher:
- New lut_max, lse and ragged_kv columns. The launcher refuses a key
  length whose LUT could exceed the row's lut_max, honours return_lse
  only on a row that declares lse, and requires seqlen_k % ts_kv == 0
  only on a row without ragged_kv. Columns a manifest omits read as 0,
  so the gfx942 rows keep their old behaviour.
- find_config keys on ts_qo/ts_kv. A block-sparse launch must name its
  geometry, so a missing row is an error instead of whichever row the
  manifest listed first.
- The sorted work table order can be selected per call with
  AITER_MHA_V4_WORK_ORDER=lpt|head|raster.

Python API:
- mha_v4 and mha_v4_packed take block_tile, defaulting to the recipe's
  own geometry.
- New geometry queries: mha_v4_block_tile, mha_v4_block_tiles,
  mha_v4_block_tiles_in_any_precision, mha_v4_kv_tile_for_q_tile,
  mha_v4_operands, mha_v4_ragged_kv. mha_v4_kv_tile takes operands and
  mode, and raises where rows disagree instead of returning a tile the
  mask may not match.
- block_attn_mask_to_ragged_lut picks BLOCK_KB from the row length.
- The FP6-P MXFP6 V scale image gets zeroed slack, because the kernels
  prefetch one tile past its end.

gfx950 objects: every sparse object is rebuilt with LSE and a masked
ragged last KV block (except f6f8's 256x128 row, which has no LSE). The
64x64 sparse rows are added for FP8, INT8/FP8, BF16, BF16/FP8, MXFP8,
FP8/MXFP6, MXFP6, MXFP6/MXFP4, MXFP4 and MXFP6/FP8. The orphaned f4f4
objects are removed.

Tests cover the geometry queries, LSE on sparse rows, ragged key
lengths, the 64x64 rows, and the LUT capacity check. On gfx942 the
sparse tests run against the existing MI300 objects.

Signed-off-by: Niko Säkkinen <[email protected]>
@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 (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 6575 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

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 stop the title rewrites; labels stay in sync either way.

Rebuild fwd_hd128_f6f8_sparse_256x128.co with the epilogue LSE store
and set lse=1 on its manifest row, so every gfx950 dense and sparse row
now serves return_lse. Update the manifest comments and mha_v4.md that
described the exception.

The rejects test no longer expects that row to refuse return_lse, and
the sparse LSE suite lists f6f8 alongside the other LSE rows, so its
dense and sparse LSE are checked against logsumexp.

Signed-off-by: Niko Sakkinen <[email protected]>
@nsakkine
nsakkine force-pushed the mha_v4-sparse-geometry branch from 80eb7c9 to b554d30 Compare October 15, 2026 13:51
On MI300X the LUT fill keeps getting faster up to 1024-2048 lanes. The
512 cap ran 1.3-2x slower than the best width at 1024 KV blocks and
above. With 2048 every row length from 32 to 4096 KV blocks is within
1.2x of the best. Not yet measured on MI355X.

Signed-off-by: Niko Sakkinen <[email protected]>
No row reads the raw column-major MXFP4 V order and nothing called
quantize_v_mxfp4. csrc/include/torch/mha_v4_quant.h was included
nowhere and declared at::Tensor signatures for a module built
without torch.

Signed-off-by: Niko Sakkinen <[email protected]>
Mention AITER_MHA_V4_WORK_ORDER, drop the outdated example of which
gfx950 geometries exist, and state what the sparse lse covers rather
than why.

Signed-off-by: Niko Sakkinen <[email protected]>
Reduce the comments to what callers and the launcher rely on: column
meanings and capabilities. Drop kernarg offsets, LDS and register
notes, softmax and PV implementation notes, model-specific figures,
and the commented-out F4F4 row. Data rows are unchanged.

Signed-off-by: Niko Sakkinen <[email protected]>
Derive each mha4_ kernel's tile from its own manifest row instead of an
FP8 stand-in, and allow --mha4-block-tile QxKV (e.g. 64x64 on gfx950)
to choose another geometry the recipe ships. The tile is passed to
mha_v4/mha_v4_packed as block_tile. Recipes without a sparse row, such
as BF16 on gfx942, now fail in argument validation.

Signed-off-by: Niko Sakkinen <[email protected]>
Matches the gfx950 objects, so the test helper finding deployed
objects no longer needs a suffix-less case.

Signed-off-by: Niko Sakkinen <[email protected]>
Each test or recipe skips when mha_v4_block_tiles() has no row for it,
at the geometry it launches. This replaces the file globbing and the
hard-coded gfx942/gfx950 recipe lists, so gfx942's FP8 and INT8/FP8 rows
now also run the tile-count tests.

Signed-off-by: Niko Sakkinen <[email protected]>
Both tests now cover each recipe at its default tile and at 64x64 where
the manifest has the row. Previously only the ragged-last-block test and
three FP8 tests touched 64x64, and no test reached the 64x64 LSE stores.

Signed-off-by: Niko Sakkinen <[email protected]>
…bucket

mha_v4_packed divided by a zero KV tile when its operands had no
block-sparse row; it now raises the same error as mha_v4. Also remove
the never-used bucket parameter from the work-table builder, test every
AITER_MHA_V4_WORK_ORDER on both sides of the ATen hand-off, and correct
the geometry docstrings that still said gfx950's 64x64 rows are
FP8/BF16-only.

Signed-off-by: Niko Sakkinen <[email protected]>
Keeps this branch's gfx950 sorted-sparse objects and manifest (per-row
ts_qo/ts_kv, lut_max, lse and ragged_kv columns; 256x64 BF16/BF16FP8,
256x128 quantized, 64x64 for every recipe) and drops main's
fwd_hd128_*_sparse.co. Dense objects are main's.

Main's sparse objects bound their Q-scale gathers; this branch's do not,
so the Q-scale padding (MHA_V4_QUERY_TILE_ROWS, query_block_scale) and
the launcher's Q backing-storage check stay. The scale-gather
disassembly test excludes the gfx950 sparse rows until they are rebuilt.

LSE capability stays per manifest row (set_lse_kernarg) rather than
_LSE_CAPABLE_QV. test_mha_v4_sparse.py moves to main's check harness;
main's sparse LSE and seqlens_k guard tests are ported onto the
per-recipe geometry, and the ragged-key rejection now targets rows
without ragged_kv.

Signed-off-by: Niko Säkkinen <[email protected]>
Chi-Chu319
Chi-Chu319 previously approved these changes Nov 2, 2026
Rebuild nine gfx950 block-sparse code objects from the unified fmha_sage_fwd
generators (dmip 993109e4, pyISA ca3b8f7) as sorted sparse with Sol off:
bf16 and bf16fp8 (256x64); i8fp8, fp8 and f6f8 (256x128); mxfp4, mxfp6, f8f6
and f6f4 FP6-P (256x128). Kernel names, kernarg layout and workgroup size are
unchanged. mxfp6 and f6f4 keep walking the LUT from HBM, so their lut_max stays
65536. The i8fp8 LUT now holds 8192 KV tiles, so its manifest row says so.

Device time through mha_v4 (16 heads, sq=sk=16384, 40% of tiles selected),
old -> new: bf16 845 -> 810 us, bf16fp8 669 -> 560, i8fp8 486 -> 459,
fp8 403 -> 402, f6f8 378 -> 375, mxfp4 292 -> 283, mxfp6 337 -> 327,
f8f6 366 -> 364, f6f4 321 -> 313. Paired kernel timing at sq 16384 and 65536
and 50-80% sparsity agrees (bf16fp8 -12..-14%, i8fp8 -5..-6%, fp8 equal).

Outputs:
- bf16, f6f8, mxfp6, f8f6, f6f4: bitwise the old objects' O and LSE,
  including ragged KV, empty rows and very sparse rows.
- mxfp4: bitwise O, LSE within 3e-6.
- fp8, i8fp8, bf16fp8: now the dense rows' numerics, so a sparse launch with
  every tile selected is bitwise the dense one. The old fp8/i8fp8 objects
  applied the packed-L LSE debias that dense does not; against an fp32
  logsumexp the mean LSE error moves from -0.022 to -0.003 (fp8) and from
  -0.001 to +0.019 (i8fp8). bf16fp8 takes dense's P path: O cosine against
  fp32 0.99918 (was 0.99930), LSE error +0.019 (was -0.0004).

The mxfp8 256x128 object stays: the rebuild measured 0.7-0.85% slower. The
64x64 objects already match the generators' code, and gfx942 and dense are
untouched.

Signed-off-by: Niko Säkkinen <[email protected]>
Rebuild fwd_hd128_mxfp8_sparse_256x128.co from the unified generator
(dmip 993109e4, sorted sparse, Sol off) like the other 256x128 rows. Its
LUT now holds 8192 KV tiles (was 7680), so the manifest row says so. The
rebuild is 0.6-0.9% slower than the old object (mha_v4 device time at 16
heads, sq=sk=16384, 40% of tiles: 412 -> 415 us). Its O matches the old
object to cosine 0.9999999. Like i8fp8 it now carries the dense row's LSE
without the packed-L debias, so a sparse launch with every tile selected
is bitwise the dense one.

Rebuild f6f4 FP6-P with its LUT staged in LDS instead of walked from HBM.
It is about 1% faster at up to 60% sparsity and on long sequences, equal
at 80% and about 1% slower at 95% (paired kernel timing), and 313 -> 311 us
in the mha_v4 shape above. Its lut_max drops from 65536 to 8192 KV tiles
(1,048,576 tokens at ts_kv=128). Outputs stay bitwise the old object's.

Signed-off-by: Niko Säkkinen <[email protected]>
@aiter-bot

aiter-bot commented Nov 3, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision ca81c65f20c1 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

**What changes.** Block-sparse `mha_v4` geometry, LSE support and ragged-KV support become properties of the manifest row rather than of the arch:

- The manifest gains `lut_max`, `lse` and `ragged_kv` columns. The launcher enforces them:
  - it refuses a key length whose LUT could exceed `lut_max`;
  - it honours `return_lse` only on rows with `lse`;
  - it requires `Sk % ts_kv == 0` only on rows without `ragged_kv`.
- `find_config` matches on `ts_qo`/`ts_kv`, so a sparse launch must name its geometry, and a geometry with no row is an error.
- gfx950 ships two geometries per recipe:
  - BF16 and BF16/FP8 route on 256x64 (was 256x128); the quantized recipes stay on 256x128;
  - every recipe adds a 64x64 row;
  - every sparse row exports LSE and masks a ragged last KV block.
- The default-tile sparse objects are rebuilt.
  - They are equal or faster on every recipe except MXFP8, which is about 0.7% slower.
  - FP8, INT8/FP8, MXFP8 and BF16/FP8 now share their dense row's LSE numerics (no debias).
  - MXFP6/MXFP4 stages its LUT in LDS (`lut_max` 8192).
- Python adds `block_tile` on `mha_v4`/`mha_v4_packed` and the geometry queries (`mha_v4_operands`, `mha_v4_block_tile`, `mha_v4_block_tiles`, `mha_v4_block_tiles_in_any_precision`, `mha_v4_kv_tile_for_q_tile`, `mha_v4_ragged_kv`). `mha_v4_kv_tile` now takes operands and raises where rows disagree.
- `AITER_MHA_V4_WORK_ORDER=lpt|head|raster` selects the sorted work-table order. The default, `lpt`, is the existing order. `head` ranks every count up to 65536 distinctly.
- `block_attn_mask_to_ragged_lut` derives `BLOCK_KB` from the row length.
- MX Q scales are again backed to a zeroed 256-row tile. The 64x64 objects gather Q scales with unbounded global loads, and the launcher checks that backing.
- MX V scales carry 1 KiB of zeroed slack from the producers (now also MXFP6 FP6-P). The launcher requires it only on the 64x64 rows, whose V-scale gather is unbounded. `main` checked MXFP4 V on every launch and never checked MXFP6.

**Why the existing behaviour is insufficient.**

- One KV tile per arch cannot describe a GPU that serves several geometries, so `mha_v4_kv_tile()` would hand callers a tile their mask may not match.
- Models routing on 64-token blocks had no row at all.
- LSE was allowed per (Q, V) pair in Python, which cannot follow the row actually dispatched once one recipe has several rows.
- Sparse callers had to zero-pad K/V to a tile multiple, which biases softmax (each zero key still gets weight `exp(-max)`).
- The old LUT conversion's fixed `BLOCK_KB` ran up to 2× slower on long rows.

Validation and unverified scope

**Validated.** Hardware: MI355X (gfx950); software: ROCm 10.1.0, torch 2.13.0. The JIT modules were rebuilt from the tested revision before testing.

- **Op tests** at `50e9c08ef1`, run from `/tmp`:

  | Command | Result |
  |---|---|
  | `PYTHONPATH=<aiter> python3 op_tests/test_mha_v4_sparse.py` | `checks: 290 ran, 5 skipped, 0 failed` |
  | `PYTHONPATH=<aiter> python3 op_tests/test_mha_v4.py` | `checks: 238 ran, 0 skipped, 0 failed` |

  The 5 skips are arch- or row-gated cases that do not apply to gfx950, for example `test_mha_v4_ragged_kv_is_false_on_gfx942`.
- **New guards fail without their fix.** Run against the launcher built from the preceding revision:
  - `test_mha_v4_sparse_work_table_orders_counts_through_65536` fails in `head` order on both the fused and the ATen path;
  - `test_mha_v4_packed_rejects_overlapping_lse_views` depends on a check the preceding revision did not have, because its two LSE stride checks accept an expanded view with strides `[0, 0, 1]`.
- **Object A/B, performance and LUT placement** were measured at `3683a2b208`. The later commits change only host-side launcher checks and the work-table key, not objects or the default `lpt` order.
- **Old versus new sparse objects (A/B).** The same aiter build ran against two `AITER_ASM_DIR` trees, one with the previous objects and one with the new ones.
  - Output bitwise equal: BF16, BF16/FP8 O, FP8/MXFP6, MXFP6/FP8, MXFP6, MXFP6/MXFP4.
  - MXFP4: O bitwise equal, LSE within 3e-6.
  - With an all-true mask at Sk=8192, FP8, INT8/FP8, MXFP8 and BF16/FP8 sparse output is bitwise equal to the dense row.
- **LSE against an fp32 reference.** The mean LSE bias moved as follows, all within test tolerance:
  - FP8 −0.022 → −0.003;
  - INT8/FP8 −0.001 → +0.019;
  - MXFP8 −0.002 → +0.018;
  - BF16/FP8 +0.019, with O cosine 0.99930 → 0.99918.
- **Performance.** Kernel device time from the torch profiler through `mha_v4(..., return_lse=True)`, median of 40 launches. Shape: B=1, H=16, Sq=Sk=16384, hd128, random mask with 40% of blocks selected. Before → after, in µs:

  | Recipe | Before | After |
  |---|---|---|
  | BF16 | 845 | 810 |
  | BF16/FP8 | 669 | 560 |
  | INT8/FP8 | 486 | 459 |
  | FP8 | 403 | 402 |
  | MXFP8 | 412 | 415 |
  | FP8/MXFP6 | 366 | 364 |
  | MXFP6/FP8 | 378 | 375 |
  | MXFP6 | 337 | 327 |
  | MXFP6/MXFP4 | 321 | 311 |
  | MXFP4 | 292 | 283 |

- **LUT placement (LDS versus HBM)**, timed in pairs across several densities and lengths:
  - MXFP6 with an LDS LUT was 0.15–1.2% slower in every case, so it keeps the HBM walk (`lut_max` 65536).
  - MXFP6/MXFP4 with an LDS LUT was 0.7–1.15% faster except at 95% sparsity (+1.2%), so it ships the LDS LUT (`lut_max` 8192).
- **V-scale bounds**, from disassembly:
  - The dense and refreshed 256x128 MX-V objects load V scales through a buffer descriptor sized to one (batch, head) slab, so over-reads return 0.
  - The 64x64 FP6-P objects use raw `global_load_dword` and can read up to 256 bytes past the slab.
  - The compact-scale test confirms the first point at runtime.
- **Lint:** `ruff check --select F` and `black --check` pass on all changed Python files.

**Unverified.**

- **gfx942 is not re-run at this revision.** Its objects are only renamed, and its manifest declares `lut_max` with `lse=0` and `ragged_kv=0`, so behaviour should be unchanged. The sparse tests have not been re-run on MI300X since the refresh.
- **The 64x64 objects are not part of this refresh.** They are covered for correctness by the op tests, but have no performance comparison, since no previous row exists.
- **Performance is measured at one shape and density** (above), plus the LUT-placement sweep. Batch > 1, GQA and short sequences are not benchmarked. The `head` and `raster` work orders are not benchmarked here.
- **`lut_max` is exercised at its limit only for BF16** (`test_mha_v4_sparse_bf16_rejects_lut_beyond_lds_capacity`). No row was launched at exactly `lut_max` KV tiles, a

[truncated in readiness report; see the PR description for the full answer]

PR-specific question

**Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?**

**Path selection.** The sorted-sparse path (manifest `mode=1`) is selected in only two ways:
- `mha_v4(..., block_mask=...)`;
- `mha_v4_packed(..., kv_block_indices=, lut_start=, lut_count=)`, where all three must be given or all omitted, otherwise it is a `ValueError`.

Without them, the dense path runs, and its manifest rows, objects and dispatch are unchanged.

**Architecture.**
- gfx950 serves the new rows.
- gfx942 keeps its two sparse rows: INT8/FP8 and FP8 at 256x64, with no LSE and no ragged KV.
- Any other arch has no manifest row, so `find_config` raises.
- LSE is additionally rejected in Python off gfx950 (`_check_lse_capable`).

**Dtype and recipe.** A launch must match a manifest row exactly on all of the following:
- `q_format`, `k_format`, `v_format`, `v_pack`;
- the three scale modes;
- `hdim_q = hdim_v = 128`, `mask = 0`;
- BF16 output with no output scale;
- `mode`, `ts_qo` and `ts_kv`.

A sparse launch with `q_tile`/`kv_tile` unset is refused, so it cannot fall back to the first matching row. A geometry with no row raises a `ValueError` listing the recipe's geometries and the GPU's geometries.

**Shape and host checks.**

| Boundary | Invariant |
|---|---|
| `block_mask` | Bool, on Q's device, shape `[B, H, ceil(Sq/q_tile), ceil(Sk/kv_tile)]` (or the 3-D form). A mask cut for another geometry fails the shape check. |
| Key length | `Sk % ts_kv == 0` unless the row declares `ragged_kv`; every gfx950 sparse row does, neither gfx942 row does. `ceil(Sk/ts_kv) <= lut_max`. |
| Per-batch `seqlens_k` | Rejected on the sparse path. |
| GQA | `nhead_q % nhead_k == 0`, power-of-two ratio up to 16. |
| Work table | `batch < 256`, `nhead < 256`, `q_tiles < 65536`; LUT counts are ranked through 65536. |
| LUT tensors | int32, on Q's device, 1-D; `lut_start`/`lut_count` have one entry per (batch, head, Q tile); `kv_block_indices` is non-empty. |
| MX Q descales | Storage must cover a zeroed 256-row tile. |
| MX V descales (MXFP6, MXFP4) | On rows with a 64-token KV tile, storage must cover the scale plus 1 KiB of zeroed slack. |
| LSE | Only on rows with `lse=1`; the tensor must be float32 `[B, Hq, Sq]`, contiguous, on Q's device. An expanded or otherwise overlapping view is refused before either launch. |

The one unguarded case is the direct LUT triple described under Unverified: the LUT's KV-tile unit is not encoded in the tensors, so it is the caller's responsibility (`mha_v4_block_tile(operands, mode)` returns it).

Changed op tests

- **`op_tests/test_mha_v4_sparse.py`** covers the new sparse behaviour, which nothing else tests:
  - **Geometry queries:** default tile, refusal when rows disagree, an unserved Q tile, a geometry with no row, and the error that names a recipe without a sparse row.
  - **Ragged KV:** per-row answers, false on gfx942, and a masked ragged last block compared with a reference. The old ragged-rejection test now covers only rows without `ragged_kv`.
  - **LSE per row**, at the default tile and 64x64: dense LSE against `logsumexp`, output unchanged when LSE is requested, and sparse LSE covering only the selected blocks.
  - **64x64 rows:** an all-true mask against dense, LUT following, and a mask that varies per Q tile.
  - **Work order:** `AITER_MHA_V4_WORK_ORDER` ordering, the rejection of an unknown value, and distinct ranks for counts through 65536 on both sort paths.

  The all-true and empty-row checks are re-parametrized over every recipe instead of per launcher. The default-tile objects behave differently per recipe (geometry, LSE debias, LUT placement), so one launcher-level case would miss a regression in a single recipe. Each check targets a distinct launcher or manifest invariant, and none duplicates another check or a `main` test.
- **`op_tests/test_mha_v4.py`** covers the dense-file guards this PR changes:
  - `test_mha_v4_q_scale_backing_storage_covers_query_tile` pins the 256-row zeroed Q-scale backing for MXFP8, MXFP6 and MXFP4 at sequence lengths around the tile boundary (1, 255, 256, 257, 513). Without it, a padding regression faults the GPU later at an unrelated synchronization point instead of failing a test.
  - The Q-backing check excludes gfx950 sparse rows, because the launcher check is what guards them.
  - **V-scale backing:**
    - `test_mha_v4_mx_v_scale_backing_storage_covers_the_64x64_gather` replaces the MXFP4-only lookahead test and adds the MXFP6 FP6-P producer.
    - `test_mha_v4_packed_mx_v_scales_need_backing_only_on_64x64_rows` pins where the launcher requires the slack: bitwise-equal output from a compact scale on dense and 256x128, and refusal on 64x64.
    - `test_mha_v4_packed_rejects_unbacked_mxfp4_k_scales` keeps the K-scale half of the old combined test.
  - `test_mha_v4_packed_rejects_overlapping_lse_views` pins the contiguous-LSE check on both launches.
  - The MXFP4/FP8 LSE rejection is removed, because LSE is now decided per manifest row and that recipe has no row.
  - The `seqlens_k` rejection test sizes its INT8/FP8 mask from that recipe's own sparse tile rather than from `mha_v4_kv_tile()`, which now raises on gfx950.
  - FP8 parametrizations use `native_fp8_format()` so the same cases run on gfx942 (FNUZ).

  These are changes to existing guards, not new coverage of sparse behaviour, so they do not overlap with `test_mha_v4_sparse.py`.
- **`op_tests/op_benchmarks/triton/bench_sage.py`** is a benchmark, not a correctness test.
  - It is changed because it called `mha_v4_kv_tile()` with no operands, which now raises on gfx950. It now asks each recipe's manifest row for its geometry (`mha4_operands` → `mha_v4_block_tile`), so masks match the row it launches.
  - It adds `--mha4-block-tile` to benchmark a non-default geometry such as 64x64, which no other benchmark can select.
  - It is not run at this revision (see Unverified).

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@nsakkine
nsakkine marked this pull request as ready for review November 3, 2026 07:46
@nsakkine
nsakkine requested a review from a team November 3, 2026 07:46
@github-actions github-actions Bot changed the title MHAv4 per-row block-sparse geometry, LSE and ragged KV on gfx950 [Triton/Gluon] [ASM] [HIP] MHAv4 per-row block-sparse geometry, LSE and ragged KV on gfx950 Nov 3, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot November 3, 2026 10:33

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

Validation still accepts overlapping LSE outputs and undersized MXFP6 descale buffers, risking aliased writes and out-of-bounds reads, while head-order ranking conflates distinct valid counts.

3 open issues
What changed in this PR

This PR makes MHA v4 sparse geometry and capabilities manifest-driven. It extends gfx950 support with 64×64 tiles, per-row LSE, and ragged KV lengths, building on the sparse LSE work in #6841.

Changes:

  • Add per-row geometry, LUT capacity, LSE, and ragged-KV metadata with launcher checks.
  • Expose geometry queries and tile selection, add work-order options, and pad quantization scales.
  • Expand regression tests and update the benchmark and API documentation.
File Description
op_tests/​test_mha_v4.py Add Q-scale backing checks and update recipe-specific tests.
op_tests/​test_mha_v4_sparse.py Expand geometry, ragged-KV, LSE, and work-order coverage.
op_tests/​op_benchmarks/​triton/​bench_sage.py Query per-recipe geometry and expose tile selection.
hsa/​gfx950/​fmha_v4_fwd/​fmha_v4_fwd.csv Declare capabilities and add 64×64 sparse rows.
hsa/​gfx942/​fmha_v4_fwd/​fmha_v4_fwd.csv Add capability columns and geometry-specific object names.
csrc/​pybind/​mha_v4_fwd_pybind.cu Expose sparse tile arguments through Python bindings.
csrc/​py_itfs_cu/​asm_mha_v4_fwd.cu Dispatch by geometry and enforce row capabilities.
csrc/​include/​torch/​mha_v4_fwd.h Update launcher signatures and contract comments.
aiter/​ops/​triton/​attention/​utils.py Make LUT scan width optional.
aiter/​ops/​triton/​_triton_kernels/​attention/​block_lut.py Derive the default scan width from mask length.
aiter/​ops/​mha_v4.py Add geometry queries and route sparse calls by tile.
aiter/​ops/​mha_v4.md Document per-row capabilities and geometry selection.
aiter/​ops/​mha_v4_quant.py Add Q-scale padding and FP6-P V-scale slack.

Review effort: Balanced

Comment thread aiter/ops/mha_v4_quant.py Resolved
Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
The 64x64 FP6-P sparse objects gather V scales through a raw pointer,
reading 512 bytes from each 64-token block's first token. When the
last selected block is the second half of a 128-token scale tile, that
read ends 256 bytes past the tensor. The dense and refreshed 256x128
objects bound the gather with a buffer descriptor and need no slack.

So the launcher now checks for 1 KiB of backing storage for MXFP6 and
MXFP4 V after the row is selected, and only on rows with a 64-token KV
tile. Before, it checked MXFP4 V on every launch and never checked
MXFP6. The producers keep reserving the slack.

New test: a compact (cloned) V scale gives bitwise the same output as
the producer-backed one on dense and 256x128, and is rejected on
64x64. The K-scale rejection test keeps its K half.

Signed-off-by: Niko Säkkinen <[email protected]>
@zufayu
zufayu requested a review from a team November 4, 2026 01:33
azaidy
azaidy previously requested changes Nov 4, 2026

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

Please split changes for different backends into different PRs.

@azaidy
azaidy requested a review from vgokhale November 4, 2026 08:45
@azaidy azaidy assigned vgokhale and unassigned Boss2002n Nov 4, 2026
The row-length BLOCK_KB default is a Triton change, so under the
one-backend-per-PR rule it moves to its own PR
(triton-block-lut-block-kb). Nothing here depends on it: mha_v4
passes no BLOCK_KB, and the LUT kernel walks a row in BLOCK_KB
chunks, so main's default of 128 builds the same LUT in more steps.

Signed-off-by: Niko Säkkinen <[email protected]>
@nsakkine

nsakkine commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Please split changes for different backends into different PRs.

Removed explicit Triton code changes and the only Triton-path file is bench_sage.py script. It follows this PR's mha_v4_kv_tile change, without which its MHA v4 sparse mode raises on gfx950. Good to go forward like this, @azaidy?

@jcaraban
jcaraban force-pushed the mha_v4-sparse-geometry branch from c52938a to 171be0a Compare November 4, 2026 21:56
Split-KV capped its count at key_length // mha_v4_kv_tile(), the
operand-free block-sparse tile. That was 128 while every gfx950
sparse row agreed, but this branch moves BF16 and BF16/FP8 to 256x64
sparse rows, so the call raises "rows disagree on ts_kv" and every
kv_splits > 1 failed in test_mha_v4.py.

The bound is about the dense launch, whose BF16 and BF16/FP8 rows
were already 256x64, so read the KV tile from the recipe's own dense
manifest row instead, behind the torch.compile guard the sparse
lookup uses. BF16 and BF16/FP8 now allow up to key_length // 64
splits; INT8/FP8 and FP8/FP8 keep 128. "auto" is unchanged.

The reject test covers both tiles, and the checks that cut a mask or
a split count from mha_v4_kv_tile() now name their recipe.

Signed-off-by: Niko Säkkinen <[email protected]>

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

why bench_sage.py is in triton folder ? what does asm benchmark have to do with triton ?

@jcaraban

jcaraban commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

why bench_sage.py is in triton folder ? what does asm benchmark have to do with triton ?

@JohnNikolay84 for historical reasons. Originally the bench was meant for the Triton implementations. Then the ASM kernels reused the bench so we could compared them. Now the ASM has nearly deprecated the Triton alternatives, but we never split their benching script. Partly because Triton provides nice bench utilities, partly because nobody cared. I understood that @azaidy already assigned the task of "taking care of the bench" to somebody in the AITER team, but our existing PRs around MHAv4 still use it

@nsakkine

nsakkine commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Probably due to historical reasons, it started as a benchmark for Triton Sage attention IIRC. Since then it has evolved into a benchmark script for various attention variants. This PR does not change its role, only preserves functionality.

@nsakkine

nsakkine commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

@azaidy I believe we are ready to merge. Could you please help

@nsakkine
nsakkine requested a review from azaidy November 6, 2026 15:34
@vgokhale
vgokhale dismissed azaidy’s stale review November 6, 2026 15:39

Discussed offline - It's fine as is we will clean up.

@vgokhale
vgokhale merged commit 93d1e7c into ROCm:main Nov 6, 2026
ruanjm pushed a commit that referenced this pull request Nov 10, 2026
…nd ragged KV on gfx950 (#6575)

* mha_v4: per-row block-sparse geometry, LSE and ragged KV on gfx950

The sparse tile used to be one value per arch. On gfx950 it is now a
property of the manifest row: BF16 and BF16/FP8 route on 256x64, the
quantized recipes on 256x128, and every recipe also ships a 64x64 row
for models whose routing is finer than a 128-token block.

Manifest and launcher:
- New lut_max, lse and ragged_kv columns. The launcher refuses a key
  length whose LUT could exceed the row's lut_max, honours return_lse
  only on a row that declares lse, and requires seqlen_k % ts_kv == 0
  only on a row without ragged_kv. Columns a manifest omits read as 0,
  so the gfx942 rows keep their old behaviour.
- find_config keys on ts_qo/ts_kv. A block-sparse launch must name its
  geometry, so a missing row is an error instead of whichever row the
  manifest listed first.
- The sorted work table order can be selected per call with
  AITER_MHA_V4_WORK_ORDER=lpt|head|raster.

Python API:
- mha_v4 and mha_v4_packed take block_tile, defaulting to the recipe's
  own geometry.
- New geometry queries: mha_v4_block_tile, mha_v4_block_tiles,
  mha_v4_block_tiles_in_any_precision, mha_v4_kv_tile_for_q_tile,
  mha_v4_operands, mha_v4_ragged_kv. mha_v4_kv_tile takes operands and
  mode, and raises where rows disagree instead of returning a tile the
  mask may not match.
- block_attn_mask_to_ragged_lut picks BLOCK_KB from the row length.
- The FP6-P MXFP6 V scale image gets zeroed slack, because the kernels
  prefetch one tile past its end.

gfx950 objects: every sparse object is rebuilt with LSE and a masked
ragged last KV block (except f6f8's 256x128 row, which has no LSE). The
64x64 sparse rows are added for FP8, INT8/FP8, BF16, BF16/FP8, MXFP8,
FP8/MXFP6, MXFP6, MXFP6/MXFP4, MXFP4 and MXFP6/FP8. The orphaned f4f4
objects are removed.

Tests cover the geometry queries, LSE on sparse rows, ragged key
lengths, the 64x64 rows, and the LUT capacity check. On gfx942 the
sparse tests run against the existing MI300 objects.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: LSE on the gfx950 MXFP6/FP8 256x128 sparse row

Rebuild fwd_hd128_f6f8_sparse_256x128.co with the epilogue LSE store
and set lse=1 on its manifest row, so every gfx950 dense and sparse row
now serves return_lse. Update the manifest comments and mha_v4.md that
described the exception.

The rejects test no longer expects that row to refuse return_lse, and
the sparse LSE suite lists f6f8 alongside the other LSE rows, so its
dense and sparse LSE are checked against logsumexp.

Signed-off-by: Niko Sakkinen <[email protected]>

* block_lut: cap the default BLOCK_KB at 2048 instead of 512

On MI300X the LUT fill keeps getting faster up to 1024-2048 lanes. The
512 cap ran 1.3-2x slower than the best width at 1024 KV blocks and
above. With 2048 every row length from 32 to 4096 KV blocks is within
1.2x of the best. Not yet measured on MI355X.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: drop the unused raw MXFP4 V op and torch quant header

No row reads the raw column-major MXFP4 V order and nothing called
quantize_v_mxfp4. csrc/include/torch/mha_v4_quant.h was included
nowhere and declared at::Tensor signatures for a module built
without torch.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: refresh the fmha_v4_fwd_sparse header comments

Mention AITER_MHA_V4_WORK_ORDER, drop the outdated example of which
gfx950 geometries exist, and state what the sparse lse covers rather
than why.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: keep kernel internals out of the fmha_v4_fwd manifests

Reduce the comments to what callers and the launcher rely on: column
meanings and capabilities. Drop kernarg offsets, LDS and register
notes, softmax and PV implementation notes, model-specific figures,
and the commented-out F4F4 row. Data rows are unchanged.

Signed-off-by: Niko Sakkinen <[email protected]>

* bench_sage: pick the MHA v4 block-sparse tile with --mha4-block-tile

Derive each mha4_ kernel's tile from its own manifest row instead of an
FP8 stand-in, and allow --mha4-block-tile QxKV (e.g. 64x64 on gfx950)
to choose another geometry the recipe ships. The tile is passed to
mha_v4/mha_v4_packed as block_tile. Recipes without a sparse row, such
as BF16 on gfx942, now fail in argument validation.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: name the gfx942 sparse objects by their 256x64 tile

Matches the gfx950 objects, so the test helper finding deployed
objects no longer needs a suffix-less case.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: gate the sparse tests on manifest rows, not .co files

Each test or recipe skips when mha_v4_block_tiles() has no row for it,
at the geometry it launches. This replaces the file globbing and the
hard-coded gfx942/gfx950 recipe lists, so gfx942's FP8 and INT8/FP8 rows
now also run the tile-count tests.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: run the sparse LSE and all-true tests at 64x64 as well

Both tests now cover each recipe at its default tile and at 64x64 where
the manifest has the row. Previously only the ragged-last-block test and
three FP8 tests touched 64x64, and no test reached the 64x64 LSE stores.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: name the missing row from mha_v4_packed, drop the work-table bucket

mha_v4_packed divided by a zero KV tile when its operands had no
block-sparse row; it now raises the same error as mha_v4. Also remove
the never-used bucket parameter from the work-table builder, test every
AITER_MHA_V4_WORK_ORDER on both sides of the ATen hand-off, and correct
the geometry docstrings that still said gfx950's 64x64 rows are
FP8/BF16-only.

Signed-off-by: Niko Sakkinen <[email protected]>

* mha_v4: refresh the gfx950 256x64/256x128 sparse objects

Rebuild nine gfx950 block-sparse code objects from the unified fmha_sage_fwd
generators (dmip 993109e4, pyISA ca3b8f7) as sorted sparse with Sol off:
bf16 and bf16fp8 (256x64); i8fp8, fp8 and f6f8 (256x128); mxfp4, mxfp6, f8f6
and f6f4 FP6-P (256x128). Kernel names, kernarg layout and workgroup size are
unchanged. mxfp6 and f6f4 keep walking the LUT from HBM, so their lut_max stays
65536. The i8fp8 LUT now holds 8192 KV tiles, so its manifest row says so.

Device time through mha_v4 (16 heads, sq=sk=16384, 40% of tiles selected),
old -> new: bf16 845 -> 810 us, bf16fp8 669 -> 560, i8fp8 486 -> 459,
fp8 403 -> 402, f6f8 378 -> 375, mxfp4 292 -> 283, mxfp6 337 -> 327,
f8f6 366 -> 364, f6f4 321 -> 313. Paired kernel timing at sq 16384 and 65536
and 50-80% sparsity agrees (bf16fp8 -12..-14%, i8fp8 -5..-6%, fp8 equal).

Outputs:
- bf16, f6f8, mxfp6, f8f6, f6f4: bitwise the old objects' O and LSE,
  including ragged KV, empty rows and very sparse rows.
- mxfp4: bitwise O, LSE within 3e-6.
- fp8, i8fp8, bf16fp8: now the dense rows' numerics, so a sparse launch with
  every tile selected is bitwise the dense one. The old fp8/i8fp8 objects
  applied the packed-L LSE debias that dense does not; against an fp32
  logsumexp the mean LSE error moves from -0.022 to -0.003 (fp8) and from
  -0.001 to +0.019 (i8fp8). bf16fp8 takes dense's P path: O cosine against
  fp32 0.99918 (was 0.99930), LSE error +0.019 (was -0.0004).

The mxfp8 256x128 object stays: the rebuild measured 0.7-0.85% slower. The
64x64 objects already match the generators' code, and gfx942 and dense are
untouched.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: refresh the gfx950 mxfp8 sparse object; f6f4 LUT in LDS

Rebuild fwd_hd128_mxfp8_sparse_256x128.co from the unified generator
(dmip 993109e4, sorted sparse, Sol off) like the other 256x128 rows. Its
LUT now holds 8192 KV tiles (was 7680), so the manifest row says so. The
rebuild is 0.6-0.9% slower than the old object (mha_v4 device time at 16
heads, sq=sk=16384, 40% of tiles: 412 -> 415 us). Its O matches the old
object to cosine 0.9999999. Like i8fp8 it now carries the dense row's LSE
without the packed-L debias, so a sparse launch with every tile selected
is bitwise the dense one.

Rebuild f6f4 FP6-P with its LUT staged in LDS instead of walked from HBM.
It is about 1% faster at up to 60% sparsity and on long sequences, equal
at 80% and about 1% slower at 95% (paired kernel timing), and 313 -> 311 us
in the mha_v4 shape above. Its lut_max drops from 65536 to 8192 KV tiles
(1,048,576 tokens at ts_kv=128). Outputs stay bitwise the old object's.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: require MX-V scale backing on the 64x64 sparse rows only

The 64x64 FP6-P sparse objects gather V scales through a raw pointer,
reading 512 bytes from each 64-token block's first token. When the
last selected block is the second half of a 128-token scale tile, that
read ends 256 bytes past the tensor. The dense and refreshed 256x128
objects bound the gather with a buffer descriptor and need no slack.

So the launcher now checks for 1 KiB of backing storage for MXFP6 and
MXFP4 V after the row is selected, and only on rows with a 64-token KV
tile. Before, it checked MXFP4 V on every launch and never checked
MXFP6. The producers keep reserving the slack.

New test: a compact (cloned) V scale gives bitwise the same output as
the producer-backed one on dense and 256x128, and is rejected on
64x64. The K-scale rejection test keeps its K half.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: require a contiguous LSE output again

The unit-row and batch-stride checks that replaced is_contiguous() in
98424e2 accept an expanded view: [1, 1, Sq] expanded to [2, 3, Sq]
has strides [0, 0, 1], so every (batch, head) row would write the same
storage. Restore the contiguous check in set_lse_kernarg, which both
the dense and the sparse launch use. Every Python path already
allocates LSE contiguous.

Test that an expanded LSE is rejected by both launches, and that a
contiguous buffer of the same shape is accepted.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: keep LUT counts through 65536 distinct in head work order

lut_max reaches 65536, but the HEAD_LOCAL key complemented the count
into 16 bits clamped at 65535, so 65535 and 65536 tied and the shorter
row stayed first. The ATen key had the same 16-bit field. Give the
count 17 bits in both: the fused key places it between the 16-bit
group and the 31-bit slot, and the ATen key scales the group by 2^17.
Both clamp counts to [0, 65536].

Test that counts through 65536 keep longest-first order within a head
group, on both sides of the 8192-entry hand-off.

Signed-off-by: Niko Säkkinen <[email protected]>

* mha_v4: sort the attention utils import in test_mha_v4.py

The merge of main left it out of order (ruff I001).

Signed-off-by: Niko Säkkinen <[email protected]>

* block_lut: leave the BLOCK_KB default to its own Triton PR

The row-length BLOCK_KB default is a Triton change, so under the
one-backend-per-PR rule it moves to its own PR
(triton-block-lut-block-kb). Nothing here depends on it: mha_v4
passes no BLOCK_KB, and the LUT kernel walks a row in BLOCK_KB
chunks, so main's default of 128 builds the same LUT in more steps.

Signed-off-by: Niko Säkkinen <[email protected]>

* Fix bench_sage imports after sparse geometry merge

* mha_v4: bound kv_splits by the recipe's dense KV tile

Split-KV capped its count at key_length // mha_v4_kv_tile(), the
operand-free block-sparse tile. That was 128 while every gfx950
sparse row agreed, but this branch moves BF16 and BF16/FP8 to 256x64
sparse rows, so the call raises "rows disagree on ts_kv" and every
kv_splits > 1 failed in test_mha_v4.py.

The bound is about the dense launch, whose BF16 and BF16/FP8 rows
were already 256x64, so read the KV tile from the recipe's own dense
manifest row instead, behind the torch.compile guard the sparse
lookup uses. BF16 and BF16/FP8 now allow up to key_length // 64
splits; INT8/FP8 and FP8/FP8 keep 128. "auto" is unchanged.

The reject test covers both tiles, and the checks that cut a mask or
a split count from mha_v4_kv_tile() now name their recipe.

Signed-off-by: Niko Säkkinen <[email protected]>

---------

Signed-off-by: Niko Säkkinen <[email protected]>
Signed-off-by: Niko Sakkinen <[email protected]>
Co-authored-by: Jesús Carabaño <[email protected]>
Co-authored-by: jcaraban <[email protected]>
gyohuangxin pushed a commit that referenced this pull request Nov 11, 2026
…ather (#7804)

#6575 made the mha_v4 launcher require MX Q descales to be backed out to a
whole 256-row query tile (check_scale_backing_storage), but the fused
intranode A2A op (#5815) still allocated packed Q scales unpadded. Whenever
world_size * sequence is not a multiple of 256, feeding its packed MX Q
scales to mha_v4 failed, e.g. in test_attention_a2a.py e4m3_pc at ws=4
s=1184 h=8:

  MX Q descale needs 38912 mapped bytes ... but only 37888 are backed

Reserve the same zeroed slack as mha_v4_quant.query_block_scale for
mxfp4/mxfp6/mxfp8 Q scales in packed return. Logical shape and strides are
unchanged; aligned sequences and non-MX Q codecs get no padding.

Co-authored-by: TennyWang1223 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
vpietila-amd pushed a commit that referenced this pull request Nov 12, 2026
…ather (#7804)

#6575 made the mha_v4 launcher require MX Q descales to be backed out to a
whole 256-row query tile (check_scale_backing_storage), but the fused
intranode A2A op (#5815) still allocated packed Q scales unpadded. Whenever
world_size * sequence is not a multiple of 256, feeding its packed MX Q
scales to mha_v4 failed, e.g. in test_attention_a2a.py e4m3_pc at ws=4
s=1184 h=8:

  MX Q descale needs 38912 mapped bytes ... but only 37888 are backed

Reserve the same zeroed slack as mha_v4_quant.query_block_scale for
mxfp4/mxfp6/mxfp8 Q scales in packed return. Logical shape and strides are
unchanged; aligned sequences and non-MX Q codecs get no padding.

Co-authored-by: TennyWang1223 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@nsakkine nsakkine mentioned this pull request Nov 12, 2026
5 of 10 tasks
nsakkine added a commit that referenced this pull request Nov 12, 2026
A LUT holds block numbers, not their size, and mha_v4_packed filled in
the manifest's default tile when block_tile was omitted. #6575 moved the
gfx950 BF16 and BF16/FP8 sparse rows from 256x128 to 256x64, so a LUT
built for 128-key blocks is now read as 64-key blocks: every index is
still in range and the call silently attends to the wrong keys, which
even AITER_MHA_V4_VALIDATE_LUT cannot catch.

Raise a ValueError when a LUT is passed without block_tile, in both the
sparse and the Sol-Attn mode. A recipe with no row at all still raises
NotImplementedError. mha_v4() and mha_v4_sol() build their own LUT and
already pass the tile they cut it at.

Update the tests that passed a LUT without its tile, add a test for the
new error, and document the requirement.

Signed-off-by: Niko Säkkinen <[email protected]>
JohnNikolay84 pushed a commit that referenced this pull request Nov 13, 2026
* [ASM] mha_v4: Sol-Attn (mode 2) on gfx950

Sol-Attn (arXiv 2607.24027) runs the block-sparse exact pass of mode 1,
then sweeps pooled per-block K/V over the blocks the LUT leaves out, so
a block under the threshold adds its zeroth-order term instead of
nothing. Both passes share one online-softmax state.

- Launcher fmha_v4_fwd_sol, with the manifest columns kv_range, jensen
  and sorted as per-row capabilities.
- mha_v4_sol(..., beta=0.4) routes from the quantized K that the kernel
  reads, through sol_prepare. mha_v4_packed takes the pooled operands.
- Options on the rows that declare them: sorted_dispatch,
  kv_range_tokens, the Jensen term and the low-rank value tilt
  (sol_tilt).
- 20 gfx950 Sol-Attn kernel objects over the sparse recipes and
  geometries.

Tests: test_mha_v4_sparse.py, against the sol_attn_ref oracle in
aiter/test_mha_common.py, and test_mha_v4.py.

Signed-off-by: Niko Säkkinen <[email protected]>

* [ASM] mha_v4: check MXFP6 K's pooled record backing in Sol-Attn

The MXFP6-K Sol-Attn rows (mxfp6, f6f4, f6f8 at 256x128 and 64x64) read
their pooled E8M0 scales from inside mean_k's and mean_k_var's 17,408-byte
tile records and never load mean_k_scale, its strides or
mean_k_var_scale. The launcher still required and shape-checked those
tensors, yet accepted any mean_k of the right shape, so a plain tensor was
read with the wrong rows and scales, or out of bounds.

- Check that MXFP6 K's mean_k and mean_k_var are views of whole tile
  records with the packer's 256-byte slack.
- Make mean_k_scale and mean_k_var_scale optional and unread for MXFP6 K.
  sol_prepare still returns them for sol_jensen_cap and sol_tilt_planes.
- Fill ptr_mean_k_var from K's scale mode, not from whether
  mean_k_var_scale was passed.
- Correct the launcher comments and the pooled-scale docs.
- Test that the record scales are read, that the separate images are
  ignored, and that a wrongly backed mean_k or mean_k_var is rejected.

Signed-off-by: Niko Säkkinen <[email protected]>

* [MHA v4] mha_v4_packed: require block_tile with a LUT

A LUT holds block numbers, not their size, and mha_v4_packed filled in
the manifest's default tile when block_tile was omitted. #6575 moved the
gfx950 BF16 and BF16/FP8 sparse rows from 256x128 to 256x64, so a LUT
built for 128-key blocks is now read as 64-key blocks: every index is
still in range and the call silently attends to the wrong keys, which
even AITER_MHA_V4_VALIDATE_LUT cannot catch.

Raise a ValueError when a LUT is passed without block_tile, in both the
sparse and the Sol-Attn mode. A recipe with no row at all still raises
NotImplementedError. mha_v4() and mha_v4_sol() build their own LUT and
already pass the tile they cut it at.

Update the tests that passed a LUT without its tile, add a test for the
new error, and document the requirement.

Signed-off-by: Niko Säkkinen <[email protected]>

* [ASM] mha_v4: enforce the E8M0 scale layout and relay out 64x64 K scales in the launcher

No gfx950 object reads a Q or K descale's token stride. Most derive
every scale address from the head counts and read the producers'
contiguous [B, S, H, D/32]; the hd128 64x64 sparse and Sol-Attn MXFP8
and MXFP4 objects read K scales head-major at the descale batch and
head strides. The launcher checked only sizes, and the head-major copy
was made in mha_v4_packed, so a strided scale, or a producer-layout K
scale reaching those objects directly, was read silently wrong whenever
there was more than one KV head.

Require contiguous E8M0 Q and K descales in the launcher (hd128 MXFP6
K's descale is not read). Build the head-major copy in the launcher for
the objects that read it, chosen from the selected row, with one kernel
that also zeroes the padding and slack, which new_empty left
uninitialized. Drop the Python relayout.

Test that each KV head's K scales reach only that head on every
MXFP8/MXFP4 row, and that a strided Q or K scale is refused. One launch
instead of a copy plus fills makes the 64x64 sparse rows 1-2 us faster.

Signed-off-by: Niko Säkkinen <[email protected]>

* [ASM] mha_v4: reject LUT rows that repeat or reorder KV blocks

check_lut_capacity bounds the key length's KV blocks by a row's LUT
region, which holds only when no row repeats a block, and the opt-in
validator checked each index's range but not the row's length or order.
A row that repeats indices can therefore overrun the 8192- or 7680-entry
region the 256x64/256x128 objects stage it in, and one listed out of
order loses every block after the partial last one, which the kernels
finish as the masked tail.

With AITER_MHA_V4_VALIDATE_LUT=1, reject lut_count above the KV block
count and any row whose indices are not strictly ascending. Document
that a row lists distinct blocks in ascending order, as
block_attn_mask_to_ragged_lut builds it. The unvalidated path is
unchanged.

Signed-off-by: Niko Säkkinen <[email protected]>

---------

Signed-off-by: Niko Säkkinen <[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.

9 participants