Repository navigation
[ASM] [HIP] Sol-Attn: gfx950 kernels - #7794
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
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]>
2e064b4 to
8402b7d
Compare
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
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]>
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]>
…les 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]>
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]>
Summary
Adds Sol-Attn (MHA v4 mode 2, arXiv 2607.24027) on gfx950. It runs the same block-sparse exact
pass as mode 1, then sweeps pooled per-block K/V over the blocks the LUT left out. A block below
the routing threshold therefore contributes its zeroth-order term instead of nothing. Both passes
share one online-softmax state, and
return_lsereports that one softmax.It also tightens three packed-API contracts that could give silently wrong results: a LUT must now
name its
block_tile; E8M0 Q/K scales must be in the producers' layout, with the 64x64 K-scalerelayout moved into the launcher; and the opt-in LUT validator now rejects rows that repeat or
reorder KV blocks.
This builds on the per-row sparse geometry (#6575) and on the Triton pooling and routing
helpers
sol_prepare()andsol_tilt(#7729), both already onmain. The Sol benchmarks followin a separate PR stacked on this one.
Motivation
Block-sparse attention (mode 1) drops every unselected KV block outright. At the densities that
make sparsity pay off, the dropped mass is what limits accuracy, and the only lever is selecting
more blocks, which costs the speedup. Sol-Attn keeps the sparse pass's cost profile and gives
dropped blocks a cheap pooled stand-in. At the same selection, it is more accurate than both
keep-or-drop and the sparse row.
Changes
fmha_v4_fwd_solhas its own kernarg layout: 1040 bytes, 1056 with a work table, 1088 withthe E8M0 Jensen pair.
kv_range,jensenandsorted. The launcherchecks them per row, like
lse.mha_v4_sol(..., beta=0.4, block_tile=None, kv_range_tokens=0, sorted_dispatch=None)quantizes, routes from the quantized K the kernel reads, pools withsol_prepare()and launches.mha_v4_packed.q @ k_meanback into the returned LSE.mha_v4_packedtakes the pooled triplemean_k,mean_vandblock_bitmap, all three or none and only with a LUT. It also takes:mean_k_varfor the Jensen term;sol_tilt.block_tileis required with a LUT. A LUT holds block numbers, not their size. [Triton/Gluon] [ASM] [HIP] MHAv4 per-row block-sparse geometry, LSE and ragged KV on gfx950 #6575 movedthe gfx950 BF16 and BF16/FP8 sparse rows from 256x128 to 256x64, so the old default read a
128-key LUT as 64-key blocks: the wrong keys, with every index in range, past even
AITER_MHA_V4_VALIDATE_LUT.mha_v4_packednow raisesValueErrorwhen a LUT comes withoutblock_tile, in sparse and Sol mode. A recipe with no row still raisesNotImplementedError.blocks, and stop the exact pass at the first block at or past the partial last one, which they
finish as the masked tail. A row that repeats indices can therefore overrun the 8192- or
7680-entry region of the 256x64/256x128 objects. A row listed out of order loses every block
after the partial last one.
AITER_MHA_V4_VALIDATE_LUT=1, the validator now rejects alut_countabove the keylength's KV-block count, and any row whose indices are not strictly ascending. It already
checked each index's range.
mha_v4.mdstate the contract: each row lists distinct KV blocks inascending order, as
block_attn_mask_to_ragged_lut()andsol_prepare()build it.sparse and Sol MXFP8/MXFP4 objects read K scales head-major at the descale batch and head
strides; every other object derives the addresses from the head counts.
[B, S, H, D/32].hd128 MXFP6 K's descale is unread and exempt.
from the selected manifest row. One kernel writes the image and zeroes the padding and slack,
which
new_emptyused to leave uninitialized. The Python relayout inmha_v4_packedisremoved.
tile records of
mean_kandmean_k_var, as every hd128 MXFP6-K kernel reads K.mean_k_scaleandmean_k_var_scaleare optional and unread there;sol_prepare()stillreturns them for
sol_jensen_cap()andsol_tilt_planes().kv_range_tokens: LSE-merged key ranges, in multiples of 32 tiles.HeadPromotedat 64-rowquery tiles and keep LPT above that.
AITER_MHA_V4_WORK_ORDERstill overrides the choice. Thisonly changes the order in which tiles run, so outputs are unchanged.
(256x64 for bf16 and bf16fp8, 256x128 otherwise) and at 64x64.
check: disassembly shows the 64x64 Sol MX-V objects gather V scales through a raw pointer,
while the 256x128 ones use the buffer descriptor.
Performance (if applicable)
The Sol numbers were recorded on the Sol commits during development. The later fixes change only
host-side checks, the opt-in LUT validator, and the 64x64 K-scale relayout, which is measured in
the last row.
mha_v4_packed, 3 shapesTesting
the relayout timing at this revision)
Documentation
aiter/ops/mha_v4.md: recipe table, Sol-Attn section, pooled scalesincluding MXFP6 K, the E8M0 scale layout, the required
block_tile, the ascending LUT-rowcontract, validation commands)
Dependencies
Breaking Changes
mha_v4_packedraisesValueErrorwhen a LUT is passed withoutblock_tile. Callers thatrelied on the default must name the tile the LUT was built for.
mha_v4()andmha_v4_sol()build their own LUTs and are unaffected. The bench PR updates
bench_sage.py, which relied onthe default.
except through
mha_v4_packedon the 64x64 MXFP8/MXFP4 rows.fmha_v4_fwd.csvmanifests gain the columnskv_range,jensenandsorted, which are 0on every non-Sol row. Out-of-tree tooling that parses the manifest by column position must read
them by header name instead.
PR Self-Review
Reviewed revision
fc5ea7f
Behavior and intent
Adds a third MHA v4 mode, Sol-Attn, on gfx950. It runs the block-sparse exact pass, then folds in
pooled per-block K/V for the blocks the LUT dropped, within one shared online softmax, so the
returned LSE is the joint softmax denominator. The existing sparse mode (mode 1) drops unselected
blocks entirely. At useful densities that dropped mass dominates the error, and the only way to
recover it today is to select more blocks and lose the speedup.
New entry points are
mha_v4_sol(raw inputs) and the pooled arguments ofmha_v4_packed; bothuse
sol_prepare()frommainfor routing and pooling. The options aresorted_dispatch,kv_range_tokens, the Jensen K-variance term and the low-ranksol_tilt. The PR ships 20 gfx950objects (10 recipes at two tiles each) and their manifest rows.
Dense and sparse callers keep their outputs bitwise for valid inputs. They see these changes:
changes scheduling only, not results.
mha_v4_packedrequiresblock_tilewith a LUT, and the launcher requires contiguous E8M0 Q/Kdescales. Both turn silently wrong results into errors.
AITER_MHA_V4_VALIDATE_LUT=1, LUT rows with alut_countabove the KV-block count, or withrepeated or out-of-order indices, are rejected. Such rows overran the LDS region or lost blocks
before. Without the variable, nothing changes.
head-major image, now with zeroed slack, in one launch.
kv_range,jensenandsorted, set to 0 on every non-Solrow. Tooling that parses the csv by column position must read these by header name.
Validation and unverified scope
Validated on MI355X (gfx950) with a shared GPU, via
brr run -g 1 --shared. The JIT modulemodule_fmha_v4_fwd.sowas removed first, so it was rebuilt from this revision's source.python3 op_tests/test_mha_v4_sparse.py: 609 checks ran, 5 skipped, 0 failed.python3 op_tests/test_mha_v4.py: 327 checks ran, 0 failed.ruff check(ruff 0.16.0) andblack --checkare clean on the touched Python files;clang-format 23.1.5 was applied to the touched C++ lines.
64x64 MXFP8/MXFP4 cases of the new per-head test fail ("head 1's K scales reached head 0").
malformed-LUT cases fail (count above the KV blocks, a duplicate index, descending indices).
Accuracy is checked against the fp32 oracle
sol_attn_refon sequences of 512-1024 with raggedtails, sorted dispatch and KV ranges. Where Sol is compared with keep-or-drop, it beats both. The
ragged-tail oracle cases also cover the relayout's partial-tile padding at 64x64.
Unverified or not covered:
comments and the three new columns, all 0. A Sol call there raises "no MHA v4 kernel" from the
manifest lookup.
sol_tilt, a proof of concept) has no op test here. Its evidence is from thedevelopment runs:
AITER_MHA_V4_VALIDATE_LUT=1. The default pathtrusts the caller, as it already did for index range.
mean_v_scale. It relies onsol_prepareallocating it.launchers, and the hd128 objects never read the source K-scale tensor the launchers still
require. This predates this PR and is left for a follow-up.
read Q scales through a raw pointer, and they need only 64-row padding. Every in-tree producer
pads to 256 rows. This predates this PR and is left for a follow-up.
this revision; only the relayout timing is from this revision.
PR-specific question
Architecture. Only gfx950 has mode-2 manifest rows. On any other architecture,
find_config(arch, recipe, 2, head_dim, q_tile, kv_tile)raises "no MHA v4 kernel".mha_v4_solraises before quantizing when the recipe has no row.
Dtype. Ten recipes have Sol rows:
Output is BF16 only.
mean_kandmean_vmust have K's and V's dtypes. Pooled scales are requiredexactly when that operand's scale mode is E8M0, and their shapes are checked against the operand's
own scale layout. The exception is MXFP6 K, whose rows read the pooled scales from
mean_k's andmean_k_var's tile records. Theremean_k_scaleandmean_k_var_scaleare optional and unread,and
mean_kandmean_k_varmust be views of whole 17,408-byte records, with a 136-byte rowstride and the packer's 256-byte slack behind the last record. E8M0 Q and K descales must be
contiguous
[B, S, H, D/32]in every mode, except hd128 MXFP6 K's unread one.Shape. Rows match only
hdim_q == hdim_v == 128with no causal mask, at the row'sts_qoxts_kv. A LUT must come with theblock_tileit was built for: 256x64 for bf16 andbf16fp8 and 256x128 otherwise at the 256-row tile, or 64x64.
ceil(seqlen_k / ts_kv)must notexceed the row's
lut_max: 8192 on bf16 and bf16fp8 256x64, 7680 on fp8 256x128, and 65536elsewhere. All rows accept a ragged key length. The launcher also requires:
lut_startandlut_countto have one int32 entry per (batch, head, query tile);kv_block_indicesto be non-empty;block_bitmapto be contiguous;Invariants. Every option is gated on a manifest capability column:
sorted_dispatch=1needssorted. Auto (-1) picks sorted dispatch only on such rows, and onlywhen batch and heads are each under 256 and there are fewer than 65536 query tiles.
kv_range_tokens > 0needskv_range, which the bf16 rows do not declare. It must also be amultiple of
32 * ts_kv.jensen, andtilt_rankmust be in [0, 64].mean_k,mean_vandblock_bitmapcome all-or-none, and only together with a LUT and itsblock_tile.lut_countnever exceedsthe key length's KV-block count.
AITER_MHA_V4_VALIDATE_LUT=1enforces both.slack the raw scale gather reads into.
head-major K-scale copy with zeroed padding and slack; callers never pass that layout.
Changed op tests
op_tests/test_mha_v4_sparse.py: the Sol-Attn kernel and launcher contract. Every Sol test isnew, because mode 2 did not exist before. The existing sparse tests never pass pooled tensors, so
they cannot catch a wrong pooled sweep or a wrong joint LSE.
Against
sol_attn_ref:Options: sorted dispatch is bitwise equal to raster, KV ranges merge to the one-range
answer, and the Jensen term matches the block K variance.
Raw API:
mha_v4_solmatches quantizing and routing by hand. Raw and packed calls havecompile parity, and fullgraph compiles without graph breaks at both tiles and with pooled
scales.
Pooling:
MXFP6 K (mxfp6, f6f4 and f6f8 at both tiles, with the Jensen term on):
mean_k_scaleandmean_k_var_scaleleaves the output bitwiseidentical;
mean_k's ormean_k_var's records changes it;No other test can see this, because the generic pooled-scale tests only perturb the separate
scale tensors.
E8M0 K-scale layout (mxfp8 and mxfp4, sparse and Sol, at both tiles):
pins each row's layout: with the relayout disabled, the 64x64 cases fail;
block_tile:mha_v4_packedrejects a LUT withoutblock_tilein sparse and Sol mode.The existing tests that passed a LUT now name its tile through a
_default_block_tile()helper; a recipe without any row still raises
NotImplementedError.LUT validation:
test_mha_v4_sparse_validation_rejects_malformed_lutgains three casesunder
AITER_MHA_V4_VALIDATE_LUT=1: alut_countabove the KV-block count, a duplicate index,and descending indices. The existing cases only covered out-of-range indices, which all three
pass. Against the previous build, exactly these three fail.
Rejections:
lut_max;Defaults: the work-table default at each query-tile size, which pins the HeadPromoted
change above. Four sparse LSE and block-tile tests were moved within the file, not added.
op_tests/test_mha_v4.py: the bounded-scale-gather disassembly test now excludes every gfx950block-sparse mode (
MHA_V4_BLOCK_SPARSE_MODES, modes 1 and 2) instead of mode 1 only. The 64x64Sol MX objects, like the 64x64 sparse ones, gather scales with global loads, guarded by the
launcher's backing-storage checks. The 256x128 Sol objects gather scales through buffer
descriptors, but each contains two lane-masked
global_load_dwords that aren't scale reads andstill match the test's pattern. Without this change these objects would fail a test meant for
dense rows. The test still covers every dense row, and no other test makes this claim.