Skip to content

[ASM] [HIP] Sol-Attn: gfx950 kernels - #7794

Merged
JohnNikolay84 merged 5 commits into
mainfrom
nsakkine/sol-attn-asm
Nov 13, 2026
Merged

JohnNikolay84 merged 5 commits into
mainfrom
nsakkine/sol-attn-asm

Conversation

@nsakkine

@nsakkine nsakkine commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

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_lse reports 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-scale
relayout 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() and sol_tilt (#7729), both already on main. The Sol benchmarks follow
in 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

  • Launcher.
    • fmha_v4_fwd_sol has its own kernarg layout: 1040 bytes, 1056 with a work table, 1088 with
      the E8M0 Jensen pair.
    • The manifest gains three capability columns, kv_range, jensen and sorted. The launcher
      checks them per row, like lse.
    • Both arch CSVs take the new schema. gfx942 has no mode-2 rows.
  • Raw API. 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 with
    sol_prepare() and launches.
    • It serves nine of the ten recipes. MXFP8 has FP8's formats, so it goes through
      mha_v4_packed.
    • It applies mha_v4's gated K smoothing and adds q @ k_mean back into the returned LSE.
  • Packed API. mha_v4_packed takes the pooled triple mean_k, mean_v and
    block_bitmap, all three or none and only with a LUT. It also takes:
    • the pooled scales the E8M0 recipes need;
    • optional mean_k_var for the Jensen term;
    • sol_tilt.
  • block_tile is 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 moved
    the 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_packed now raises ValueError when a LUT comes without
    block_tile, in sparse and Sol mode. A recipe with no row still raises NotImplementedError.
  • LUT row order. The kernels stage a LUT row in an LDS region sized for the key length's KV
    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.
    • With AITER_MHA_V4_VALIDATE_LUT=1, the validator now rejects a lut_count above the key
      length's KV-block count, and any row whose indices are not strictly ascending. It already
      checked each index's range.
    • The docstring and mha_v4.md state the contract: each row lists distinct KV blocks in
      ascending order, as block_attn_mask_to_ragged_lut() and sol_prepare() build it.
    • The unvalidated path is unchanged, so there is no performance cost.
  • E8M0 scale layout. No gfx950 object reads a Q or K descale's token stride. The hd128 64x64
    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.
    • The launcher requires contiguous E8M0 Q and K descales, the producers' [B, S, H, D/32].
      hd128 MXFP6 K's descale is unread and exempt.
    • The launcher builds the head-major K-scale copy itself for the objects that read it, picked
      from the selected manifest row. One kernel writes the image and zeroes the padding and slack,
      which new_empty used to leave uninitialized. The Python relayout in mha_v4_packed is
      removed.
  • MXFP6 K.
    • The MXFP6-K rows (mxfp6, f6f4 and f6f8) read their pooled scales from inside the 17,408-byte
      tile records of mean_k and mean_k_var, as every hd128 MXFP6-K kernel reads K.
    • The launcher checks that both are views of whole records with the packer's 256-byte slack.
      mean_k_scale and mean_k_var_scale are optional and unread there; sol_prepare() still
      returns them for sol_jensen_cap() and sol_tilt_planes().
  • Per-row options.
    • Sorted dispatch: an LPT work table, bitwise identical to raster order.
    • kv_range_tokens: LSE-merged key ranges, in multiples of 32 tiles.
    • The Jensen second-order term.
    • A low-rank pooled-value tilt (PoC) on Jensen rows.
  • Work order. Both the sparse and the Sol launchers now default to HeadPromoted at 64-row
    query tiles and keep LPT above that. AITER_MHA_V4_WORK_ORDER still overrides the choice. This
    only changes the order in which tiles run, so outputs are unchanged.
  • gfx950 objects.
    • 20 Sol rows cover the same ten recipes as the sparse rows, each at its default 256-row tile
      (256x64 for bf16 and bf16fp8, 256x128 otherwise) and at 64x64.
    • All are hd128, rebuilt from the unified generators (pyISA ca3b8f7).
    • They inherit the sparse rows' 17-bit work-table count rank and the 64x64 MX-V scale-slack
      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.

Hardware Workload/configuration Before After Change
MI355X, exclusive f6f8 Sol, b1, h24, 32k tokens, beta 0.4 64x64 row 2.571 ms 256x128 row 1.955 ms 24-27% faster
MI355X, exclusive f6f8 Sol 256x128 vs f6f8 sparse 256x128, same selection sparse Sol +2-10% time
MI355X, exclusive 64x64 work order, synthetic 720p FP8 masks exact LPT, 35% behind best HeadPromoted, within 1% of best on average (5% worst) -
MI355X, exclusive rebuilt vs previously deployed Sol objects, h16, sq=16384, ~16% density deployed rebuilt i8fp8 -5..-6%, bf16fp8 -3.5..-4.2%, bf16 -2.6..-2.9%, f6f4 -1.5..-3.2%, others within ±1.7%
MI355X, exclusive low-rank tilt at 64x64 over the Jensen pass rank 0 rank 2 / rank 8 +13-22% / +38-46% per call
MI355X, exclusive 64x64 MXFP8/MXFP4 sparse through mha_v4_packed, 3 shapes Python relayout, 36.4-87.7 us launcher relayout, 34.0-86.0 us 1-2.5 us faster; Sol within noise

Testing

  • Unit tests added or updated
  • Performance benchmarks run (on the Sol commits during development, with the bench PR's tools;
    the relayout timing at this revision)
  • Tested on MI250X
  • Tested on MI300X (no gfx942 hardware here, and gfx942 ships no Sol rows)

Documentation

  • Docstrings updated
  • User guide updated (aiter/ops/mha_v4.md: recipe table, Sol-Attn section, pooled scales
    including MXFP6 K, the E8M0 scale layout, the required block_tile, the ascending LUT-row
    contract, validation commands)
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

  • mha_v4_packed raises ValueError when a LUT is passed without block_tile. Callers that
    relied on the default must name the tile the LUT was built for. mha_v4() and mha_v4_sol()
    build their own LUTs and are unaffected. The bench PR updates bench_sage.py, which relied on
    the default.
  • The launcher rejects non-contiguous E8M0 Q and K descales. These were read wrongly before,
    except through mha_v4_packed on the 64x64 MXFP8/MXFP4 rows.
  • Both fmha_v4_fwd.csv manifests gain the columns kv_range, jensen and sorted, which are 0
    on 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 of mha_v4_packed; both
use sol_prepare() from main for routing and pooling. The options are sorted_dispatch,
kv_range_tokens, the Jensen K-variance term and the low-rank sol_tilt. The PR ships 20 gfx950
objects (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:

  • At 64-row query tiles, the default work-table order is now HeadPromoted instead of LPT. This
    changes scheduling only, not results.
  • mha_v4_packed requires block_tile with a LUT, and the launcher requires contiguous E8M0 Q/K
    descales. Both turn silently wrong results into errors.
  • With AITER_MHA_V4_VALIDATE_LUT=1, LUT rows with a lut_count above the KV-block count, or with
    repeated or out-of-order indices, are rejected. Such rows overran the LDS region or lost blocks
    before. Without the variable, nothing changes.
  • The 64x64 MXFP8/MXFP4 K-scale relayout moved from Python into the launcher. It produces the same
    head-major image, now with zeroed slack, in one launch.
  • Both manifests gain the columns kv_range, jensen and sorted, set to 0 on every non-Sol
    row. 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 module
module_fmha_v4_fwd.so was 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) and black --check are clean on the touched Python files;
    clang-format 23.1.5 was applied to the touched C++ lines.
  • Negative control for the K-scale layout: with the launcher relayout disabled, exactly the four
    64x64 MXFP8/MXFP4 cases of the new per-head test fail ("head 1's K scales reached head 0").
  • Negative control for the LUT validator: against the previous build, exactly the three new
    malformed-LUT cases fail (count above the KV blocks, a duplicate index, descending indices).

Accuracy is checked against the fp32 oracle sol_attn_ref on sequences of 512-1024 with ragged
tails, 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:

  • No gfx942 hardware was available. gfx942 has no mode-2 rows, so its only changes are the csv
    comments and the three new columns, all 0. A Sol call there raises "no MHA v4 kernel" from the
    manifest lookup.
  • The low-rank tilt (sol_tilt, a proof of concept) has no op test here. Its evidence is from the
    development runs:
    • rank 0 is bitwise equal to the Jensen objects;
    • ranks 1-8 are finite and deterministic on 12 Wan attention cases;
    • compiled output is bitwise equal to eager on six rows.
  • LUT row order and length are checked only under AITER_MHA_V4_VALIDATE_LUT=1. The default path
    trusts the caller, as it already did for index range.
  • The launcher does not check the backing slack behind the pooled mean_v_scale. It relies on
    sol_prepare allocating it.
  • The source K of the MXFP6-K recipes gets no record-backing check in the dense, sparse or Sol
    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.
  • The 256-row Q-scale backing check runs on every E8M0 launch, although only the 64x64 MX objects
    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.
  • The Sol performance numbers were measured on the Sol commits with the bench PR's tools, not at
    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_sol
raises before quantizing when the recipe has no row.

Dtype. Ten recipes have Sol rows:

  • bf16, bf16fp8, fp8, i8fp8, mxfp8 and f6f8;
  • mxfp4, mxfp6, f8f6 and f6f4, each with FP6-P V.

Output is BF16 only. mean_k and mean_v must have K's and V's dtypes. Pooled scales are required
exactly 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 and
mean_k_var's tile records. There mean_k_scale and mean_k_var_scale are optional and unread,
and mean_k and mean_k_var must be views of whole 17,408-byte records, with a 136-byte row
stride 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 == 128 with no causal mask, at the row's
ts_qoxts_kv. A LUT must come with the block_tile it was built for: 256x64 for bf16 and
bf16fp8 and 256x128 otherwise at the 256-row tile, or 64x64. ceil(seqlen_k / ts_kv) must not
exceed the row's lut_max: 8192 on bf16 and bf16fp8 256x64, 7680 on fp8 256x128, and 65536
elsewhere. All rows accept a ragged key length. The launcher also requires:

  • lut_start and lut_count to have one int32 entry per (batch, head, query tile);
  • kv_block_indices to be non-empty;
  • block_bitmap to be contiguous;
  • all strides and extents to fit the 32-bit kernarg slots.

Invariants. Every option is gated on a manifest capability column:

  • sorted_dispatch=1 needs sorted. Auto (-1) picks sorted dispatch only on such rows, and only
    when batch and heads are each under 256 and there are fewer than 65536 query tiles.
  • kv_range_tokens > 0 needs kv_range, which the bf16 rows do not declare. It must also be a
    multiple of 32 * ts_kv.
  • Both the Jensen term and the tilt need jensen, and tilt_rank must be in [0, 64].
  • mean_k, mean_v and block_bitmap come all-or-none, and only together with a LUT and its
    block_tile.
  • Each LUT row lists distinct KV blocks in strictly ascending order, so lut_count never exceeds
    the key length's KV-block count. AITER_MHA_V4_VALIDATE_LUT=1 enforces both.
  • On the 64x64 MXFP4/MXFP6 V rows, the launcher refuses a V descale that lacks the 1 KiB zeroed
    slack the raw scale gather reads into.
  • On the hd128 64x64 sparse and Sol MXFP8/MXFP4 rows, the launcher hands the kernel its own
    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 is
    new, 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:

      • the oracle comparison, and Sol beating both keep-all and drop;
      • select-all matching the sparse row, and matching dense at 64x64;
      • empty LUT rows falling back to the pooled softmax;
      • the LSE being the joint softmax denominator;
      • FP8 P keeping pooled mass far below the exact max;
      • tolerance of a K common-mode shift.
    • 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_sol matches quantizing and routing by hand. Raw and packed calls have
      compile parity, and fullgraph compiles without graph breaks at both tiles and with pooled
      scales.

    • Pooling:

      • MXFP4 fills both pooled scale slots;
      • the kernel reads the pooled scale it was given;
      • pooled scales are required exactly for E8M0 operands other than MXFP6 K;
      • E8M0 round-trips;
      • block-granular scales are not pooled into the codes;
      • integer operands round rather than truncate;
      • the K shift needs a packed K of matching shape.
    • MXFP6 K (mxfp6, f6f4 and f6f8 at both tiles, with the Jensen term on):

      • dropping or perturbing mean_k_scale and mean_k_var_scale leaves the output bitwise
        identical;
      • perturbing the scales inside mean_k's or mean_k_var's records changes it;
      • a contiguous copy of either, and a view without the 256-byte slack, are rejected.

      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):

      • bumping head 1's K scales changes head 1's output and leaves head 0's bitwise equal. This
        pins each row's layout: with the relayout disabled, the 64x64 cases fail;
      • a head-major copy of the Q or K scale, with the producer's shape and values, is rejected.
    • block_tile: mha_v4_packed rejects a LUT without block_tile in 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_lut gains three cases
      under AITER_MHA_V4_VALIDATE_LUT=1: a lut_count above 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:

      • recipes without a manifest row;
      • pooled tensors without a LUT;
      • partial pooled triples;
      • key lengths past lut_max;
      • sorted dispatch on a row that doesn't declare it.
    • 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 gfx950
    block-sparse mode (MHA_V4_BLOCK_SPARSE_MODES, modes 1 and 2) instead of mode 1 only. The 64x64
    Sol 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 and
    still 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.

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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 Radeon R9700 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 7794 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

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]>
@nsakkine
nsakkine force-pushed the nsakkine/sol-attn-asm branch from 2e064b4 to 8402b7d Compare November 12, 2026 10:06
@nsakkine
nsakkine marked this pull request as ready for review November 12, 2026 10:07
@nsakkine
nsakkine requested a review from a team November 12, 2026 10:07
@github-actions github-actions Bot changed the title Sol-Attn: gfx950 kernels [ASM] [HIP] Sol-Attn: gfx950 kernels Nov 12, 2026
@aiter-bot

aiter-bot commented Nov 12, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision fc5ea7f3e8d2 · 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

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 of `mha_v4_packed`; both
use `sol_prepare()` from `main` for routing and pooling. The options are `sorted_dispatch`,
`kv_range_tokens`, the Jensen K-variance term and the low-rank `sol_tilt`. The PR ships 20 gfx950
objects (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:

- At 64-row query tiles, the default work-table order is now HeadPromoted instead of LPT. This
  changes scheduling only, not results.
- `mha_v4_packed` requires `block_tile` with a LUT, and the launcher requires contiguous E8M0 Q/K
  descales. Both turn silently wrong results into errors.
- With `AITER_MHA_V4_VALIDATE_LUT=1`, LUT rows with a `lut_count` above the KV-block count, or with
  repeated or out-of-order indices, are rejected. Such rows overran the LDS region or lost blocks
  before. Without the variable, nothing changes.
- The 64x64 MXFP8/MXFP4 K-scale relayout moved from Python into the launcher. It produces the same
  head-major image, now with zeroed slack, in one launch.
- Both manifests gain the columns `kv_range`, `jensen` and `sorted`, set to 0 on every non-Sol
  row. 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 module
`module_fmha_v4_fwd.so` was 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) and `black --check` are clean on the touched Python files;
  clang-format 23.1.5 was applied to the touched C++ lines.
- Negative control for the K-scale layout: with the launcher relayout disabled, exactly the four
  64x64 MXFP8/MXFP4 cases of the new per-head test fail ("head 1's K scales reached head 0").
- Negative control for the LUT validator: against the previous build, exactly the three new
  malformed-LUT cases fail (count above the KV blocks, a duplicate index, descending indices).

Accuracy is checked against the fp32 oracle `sol_attn_ref` on sequences of 512-1024 with ragged
tails, 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:

- No gfx942 hardware was available. gfx942 has no mode-2 rows, so its only changes are the csv
  comments and the three new columns, all 0. A Sol call there raises "no MHA v4 kernel" from the
  manifest lookup.
- The low-rank tilt (`sol_tilt`, a proof of concept) has no op test here. Its evidence is from the
  development runs:
  - rank 0 is bitwise equal to the Jensen objects;
  - ranks 1-8 are finite and deterministic on 12 Wan attention cases;
  - compiled output is bitwise equal to eager on six rows.
- LUT row order and length are checked only under `AITER_MHA_V4_VALIDATE_LUT=1`. The default path
  trusts the caller, as it already did for index range.
- The launcher does not check the backing slack behind the pooled `mean_v_scale`. It relies on
  `sol_prepare` allocating it.
- The source K of the MXFP6-K recipes gets no record-backing check in the dense, sparse or Sol
  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.
- The 256-row Q-scale backing check runs on every E8M0 launch, although only the 64x64 MX objects
  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.
- The Sol performance numbers were measured on the Sol commits with the bench PR's tools, not at
  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_sol`
raises before quantizing when the recipe has no row.

**Dtype.** Ten recipes have Sol rows:

- bf16, bf16fp8, fp8, i8fp8, mxfp8 and f6f8;
- mxfp4, mxfp6, f8f6 and f6f4, each with FP6-P V.

Output is BF16 only. `mean_k` and `mean_v` must have K's and V's dtypes. Pooled scales are required
exactly 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 and
`mean_k_var`'s tile records. There `mean_k_scale` and `mean_k_var_scale` are optional and unread,
and `mean_k` and `mean_k_var` must be views of whole 17,408-byte records, with a 136-byte row
stride 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 == 128` with no causal mask, at the row's
`ts_qo`x`ts_kv`. A LUT must come with the `block_tile` it was built for: 256x64 for bf16 and
bf16fp8 and 256x128 otherwise at the 256-row tile, or 64x64. `ceil(seqlen_k / ts_kv)` must not
exceed the row's `lut_max`: 8192 on bf16 and bf16fp8 256x64, 7680 on fp8 256x128, and 65536
elsewhere. All rows accept a ragged key length. The launcher also requires:

- `lut_start` and `lut_count` to have one int32 entry per (batch, head, query tile);
- `kv_block_indices` to be non-empty;
- `block_bitmap` to be contiguous;
- all strides and extents to fit the 32-bit kernarg slots.

**Invariants.** Every option is gated on a manifest capability column:

- `sorted_dispatch=1` needs `sorted`. Auto (`-1`) picks sorted dispatch only on such rows, and only
  when batch and heads are each under 256 and there are fewer than 65536 query tiles.
- `kv_range_tokens > 0` needs `kv_range`, which the bf16 rows do not declare. It must also be a
  multiple of `32 * ts_kv`.
- Both the Jensen term and the tilt need `jensen`, and `tilt_rank` must be in [0, 64].
- `mean_k`, `mean_v` and `block_bitmap` come all-or-none, and only together with a LUT and its
  `block_tile`.
- Each LUT row lists distinct KV blocks in strictly ascending order, so `lut_count` never exceeds
  the key length's KV-block count. `AITER_MHA_V4_VALIDATE_LUT=1` enforces both.
- On the 64x64 MXFP4/MXFP6 V rows, the launcher refuses a V descale that lacks the 1 KiB zeroed
  slack the raw scale gather reads into.
- On the hd128 64x64 sparse and Sol MXFP8/MXFP4 rows, the launcher hands the kernel its own
  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 is
  new, 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`:**
    - the oracle comparison, and Sol beating both keep-all and drop;
    - select-all matching the sparse row, and matching dense at 64x64;
    - empty LUT rows falling back to the pooled softmax;
    - the LSE being the joint softmax denominator;
    - FP8 P keeping pooled mass far below the exact max;
    - tolerance of a K common-mode shift.
  - **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_sol` matches quantizing and routing by hand. Raw and packed calls have
    compile parity, and fullgraph compiles without graph breaks at both tiles and with pooled
    scales.
  - **Pooling:**
    - MXFP4 fills both pooled scale slots;
    - the kernel reads the pooled scale it was given;
    - pooled scales are required exactly for E8M0 operands other than MXFP6 K;
    - E8M0 round-trips;
    - block-granular scales are not pooled into the codes;
    - integer operands round rather than truncate;
    - the K shift needs a packed K of matching shape.
  - **MXFP6 K** (mxfp6, f6f4 and f6f8 at both tiles, with the Jensen term on):
    - dropping or perturbing `mean_k_scale` and `mean_k_var_scale` leaves the output bitwise
      identical;
    - perturbing the scales inside `mean_k`'s or `mean_k_var`'s records changes it;
    - a contiguous copy of either, and a view without the 256-byte slack, are rejected.

    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):
    - bumping head 1's K scales changes head 1's output and leaves head 0's bitwise equal. This
      pins each row's layout: with the relayout disabled, the 64x64 cases fail;
    - a head-major copy of the Q or K scale, with the producer's shape and values, is rejected.
  - **`block_tile`:** `mha_v4_packed` rejects a LUT without `block_tile` in 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_lut` gains three cases
    under `AITER_MHA_V4_VALIDATE_LUT=1`: a `lut_count` above 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:**
    - recipes without a manifest row;
    - pooled tensors without a LUT;
    - partial pooled triples;
    - key lengths past `lut_max`;
    - sorted dispatch on a row that doesn't declare it.
  - **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 gfx950
  block-sparse mode (`MHA_V4_BLOCK_SPARSE_MODES`, modes 1 and 2) instead of mode 1 only. The 64x64
  Sol 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_dword`s that aren't scale reads and
  still 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.

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.

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

4 participants