Skip to content

[Release v0.1.28] Re-cut post1 from main through #7429 - #7490

Merged
vgokhale merged 86 commits into
release/v0.1.28from
hotfix/v0.1.28-post1
Nov 5, 2026
Merged

vgokhale merged 86 commits into
release/v0.1.28from
hotfix/v0.1.28-post1

Conversation

@vgokhale

@vgokhale vgokhale commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

The v0.1.28 wheel build failed on ROCm 7.0/7.1 compiler errors, so that tag has no published GitHub Release. This PR re-cuts the release branch from the current main snapshot instead of rebuilding the unchanged tag.

The source snapshot is 4e91c7ea6a8ed0adb2e6330e1bc29f5f1d71dc22 (main comparison), 86 commits after v0.1.28. Its HEAD is #7429, so that PR is included. The snapshot also contains the updated release wheel matrix: ROCm 7.2, 7.14, 10.0, and 10.1, each for Python 3.10 and 3.12.

Validation: the release branch started at the original v0.1.28 tag, and this PR's head is exactly the pinned main commit. The squash merge commit ad0554a97858d8089e92c2d8b5db7017a6efc0f2 has the original tag as its parent and the same file tree as 4e91c7ea6a8ed0adb2e6330e1bc29f5f1d71dc22. PR checks started on release/*; formatting, dependency, and OPUS MI300X checks passed, while other tests were still running when merged. The eight-wheel release build is now queued.

Tagged v0.1.28.post1 on the merge commit; release automation is building the wheel set.

aiter-gh-app Bot and others added 30 commits November 2, 2026 15:14
…FP4 prefix KV (#7124)

* Add a gfx950 MLA v4.1 a8w4 prefill kernel for an NVFP4 prefix KV

* Add a gfx950 MLA v4.1 a8w4 16mx4_64nx1 prefill kernel and run the NVFP4 prefix in f16

* Run the dsa_v41 a8w4 NVFP4 prefix in bf16 to keep MXFP8 Q exact
…7219)

* Avoid constructing a torch Stream for default grouped GEMM launches

* Reuse raw stream arguments through MoE route, quant and reduction wrappers
…writes (#7182)

On gfx950, mla_a16w16_qh16_m16x4_n32x1_coex0_mask1 (bf16, gqa 32,
non-persistent) deals KV to splits round-robin in 32-token tiles and
exits without writing a split that gets no tile. mla_decode_fwd used
mgc = 16 for nhead 32, so stage 2 merged min(splits, cdiv(kv, 16))
splits and read up to twice as many as stage 1 wrote, from torch.empty
buffers. Rows with less KV than splits * 32 came back wrong, or NaN
when that memory held NaN. Use mgc = 32 for this kernel, as the fp8
qh64 kernel already does with mgc = 64. gfx942's gqa32 kernel uses
16-token tiles and keeps mgc = 16.

The new op test runs that case with NaN-filled split buffers.

Signed-off-by: Batzorig Zorigoo <[email protected]>
…950 (#6889)

* [Triton/Gluon] Split window-trimmed sliding-window verify on gfx950

On gfx950 a sliding-window call with q > 1 never takes the split grid
(_gfx950_split_grid returns False, and kv_split["SW"] caps MAX_SEGMENTS
at 1), so a spec-decode verify on a sliding layer runs num_kv_heads
programs per sequence over the whole window. Splitting it only pays once
the KV range is cut to the window: the split carves seq_len, so over a
full context the window lands in one or two segments and the rest are
empty (31.9-37.6 us vs 29 us unsplit when forced).

Split only when the KV range is bounded by the window. Row i of a q-row
sequence of length L reads keys from L - q + i - (SW - 1) on, so a block
table trimmed to whole pages holds at most SW + q - 1 + block_size - 1
keys. The new SWB config axis is sliding_window_bounds_kv(): q > 1 and
max_seqlen_k <= sliding_window + max_seqlen_q + block_size - 2. A batch
whose contexts are all that short is bounded as well, trimmed or not, and
takes the same path. _gfx950_split_grid lets verify-sized SWB calls
(max_seqlen_q <= 16 and max_seqlen_q * num_queries_per_kv <= 128)
through and then decides like any other batch (NUM_SEGMENTS > 1).
Longer queries (prefill chunks) keep the 2d grid: with q rows per
sequence in the reduce, MHA q = 128 at window 256-512 ran up to 1.33x
slower split.

The gfx950 gluon kv_split table gains an "SW.SWB" entry, the SW entry
without its segment cap, plus:
- SPLIT_FIT_BUDGET (new): the largest power-of-two split that keeps the
  launch within SEGMENTS_PER_CU (1) programs per CU, sized by the real
  one-block-per-sequence query grid (_gfx950_split_params). The default
  ceil-rounded share splits 2 ways up to B = 51 and loses 30-40% from
  B = 36 (39.7-43.0 us vs 30.4-30.8 us on the 2d grid).
- SPLIT_KV_WINDOW (new): count the KV tiles over the sliding_window +
  max_seqlen_q - 1 keys the rows can see, not the page slack of a trimmed
  table, so SPLIT_MIN_TILES 4 keeps window 128 unsplit at block 128 too
  (64 q / 8 kv heads, q = 4: 8.2 us split vs 6.7 us 2d).
- SPLIT_SEQS_PER_TILE 1.5 (new): no split once num_seqs exceeds 1.5 x the
  KV tiles. The triton reduce_segments pass that every gfx950 split pays
  costs more with the batch (7.6 us at B = 32, 2 segments), while the 2d
  kernel's time follows the KV length, so at windows 256-1024 a split at
  B = 12-32 ran up to 1.87x slower than the 2d grid.

Kernel: a split whose tiles all fall before the window start stores an
empty partial, and split 0 is the only one that counts the attention
sink, so a window starting past tile 0 (block size > 64, or a shorter
row in an untrimmed bounded batch) dropped the sink from the softmax.
The empty-partial path of split 0 now stores M = sink, L = 1.

Unchanged dispatch: SW calls with a context past the bound, SW decode
(q == 1 keeps the cap), q > 16, window 128, full attention, gfx1250 and
the triton backend. Of 328,800 no-launch shapes (window 128-32768, q
1-128, B 1-128, 5 head layouts, D 64-256, bf16/fp8, block 16-256,
ctx bound -300..+5000) only gluon SW calls with 1 < q <= 16 inside the
bound change grid (22,392).

MI355X, 16 q / 2 kv heads, head 64, bf16, block 16, window 2048, q = 8,
ctx 32768 (us per call, CUDA-graph replay, natural dispatch):
  B           1     2     4     8    16    32    48    64
  full      29.0  29.0  29.1  29.5  30.0  30.5  30.6  30.9
  trimmed    6.7   7.2   8.6  10.9  15.8  25.1  30.6  30.8
  segments    64    32    16     8     4     2    2d    2d
Full-attention floor at 2056 keys: 6.6 / 6.8 / 8.1 / 9.4 / 14.4 / 21.9.
The natural pick matches the fastest forced count (1-128) at every B.
Shorter windows, trimmed, same heads (base 2d -> split, us):
  W 512:  B4 9.78 -> 6.79, B8 9.79 -> 7.61, B12 9.82 -> 9.19, B16+ 2d
  W 1024: B4 16.30 -> 7.66, B8 16.35 -> 8.61, B16 16.71 -> 12.27, B32 2d
  W 256:  B4 6.54 -> 6.30, B8+ 2d

Known cost: a caller that captures a graph at max_seqlen_k = window bound
and replays it for batches whose real contexts are a few hundred keys
pays the split + reduce where the 2d kernel was cheaper (B >= 12, ctx <=
1000). A cheaper gfx950 reduce would remove that.

Test: test_triton_unified_attn_sw_verify_split (full and trimmed tables
vs reference with a dominant sink, exact segment counts: trimmed verify
splits, full context stays 2d, SW decode stays 1 segment, q = 17 and
q = 128 prefill chunks stay 2d, block 128 and an untrimmed bounded batch
leave split 0 empty) and test_unified_attn_sw_kv_split_config
(CPU-only kv_split picks at the bound edge, untrimmed, decode, window 128,
and the batch sizes where the split stops).

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [Triton/Gluon] Drop SPLIT_KV_WINDOW; clamp every window-bounded split

Review follow-up. The SPLIT_KV_WINDOW knob was set only in the SW.SWB
entry, so it configured nothing. compute_segment_params now counts KV
tiles over the sliding_window + max_seqlen_q - 1 keys the rows can see
whenever sliding_window_bounds_kv() holds, with no config switch.

The clamp is gated on the bound, not on sliding_window > 0. The split
carves the whole seq_len, so on an untrimmed long context a window-sized
count leaves most segments idle. No unbounded sliding-window call reaches
a split lookup today, so the two gates pick the same grid.

CPU dispatch sweep vs the previous commit, 2,048,256 shapes per arch on
gfx950 (gluon and triton), gfx1250, gfx1100 and gfx1201: no 2d/3d,
NUM_SEGMENTS or TILE_SIZE change. 1,184 gfx950 gluon shapes change only
the triton reduce num_warps (head 256, block >= 64, window + q - 1 of
about 257-512), since the reduce lookup now sees the same clamped length.
test_unified_attn_sw_kv_split_config: 11 passed on CPU; removing the clamp
fails the window 128, block 128 case.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [Triton/Gluon] Key the SWA split on window size: numeric SW axis

Review follow-up. The SW axis was a bool, so a table could not target a
window size. SW is now "opt_num": the keys a row can see,
min(sliding_window, max_seqlen_k), floored at 1, and 0 with no window.
SW_EQ/LEQ/GEQ_<n> keys pick by size, a bare SW matches any window, and
no window matches only "any". Tables that only use a bare SW key (gfx950
gluon and triton, gfx1250 gluon, gfx1201 triton) resolve as before.
_index rejects a table that mixes SW_LEQ and SW_GEQ keys, because every
matching LEQ key would outrank every GEQ key. It is cached on the key
names, so the check runs once per table.

The gfx950 gluon kv_split entry SW.SWB becomes SW_GEQ_256.SWB. Bare SW,
with MAX_SEGMENTS 1, stays the fallback for every other window and for SW
decode. 256 keys is 4 tiles of 64, the smallest window measured to win.
Window 128 now falls back through the threshold, not SPLIT_MIN_TILES.
SWB stays: an untrimmed long context also gives SW = window, and
splitting that table was measured slower.

CPU dispatch sweep vs the previous commit, 3,692,160 shapes per arch
(grid, NUM_SEGMENTS, reduce config, and attn_2d/attn_3d configs for both
backends) on gfx950, gfx1250, gfx1100 and gfx1201: the only change is
6,300 gfx950 gluon shapes at window 255 (q 4-16, just under the
threshold), split -> 2d. Windows above 2048 still split; their perf is
not measured.

Tests: test_unified_attn_sw_kv_split_config gains window 255 vs 256 at
the threshold and window 256 at block 128 (the clamp case).
test_unified_attn_sw_axis_lookup covers the candidate order, the axis
value and its floor, and the LEQ/GEQ guard. 15 passed on CPU. Each of
these mutants fails at least one test: threshold, clamp, guard, bare-SW
fallback, the no-window check, min(), and the floor.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [Triton/Gluon] Test the SWA split without sinks on long pages

Review follow-up (Copilot). Without sinks, a sliding-window split over a
bounded table whose page is much longer than a tile can leave 32 or more
empty leading segments. One example is head 256, q 8, KV 10246, window
2048, block 8192, 64 segments. Before #6888 that made the first
SEGMENT_BLOCK chunk of reduce_segments all -inf, and the merge returned
NaN. #6888's two-pass merge takes the global max first, so those chunks
now weigh 0. Under TRITON_INTERPRET=1, main's reduce_segments on the
partials both shapes leave gives no NaN and matches the single-chunk
reduce within 1.2e-7.

test_triton_unified_attn_sw_split_no_sinks runs both of Copilot's shapes
on gfx950 with head 256 and no sinks, against the reference.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [Triton/Gluon] SWA split tests: check accuracy only

Review follow-up. Tests here target accuracy, not configs or routing.

- Remove test_unified_attn_sw_kv_split_config and
  test_unified_attn_sw_axis_lookup. They pinned kv_split picks and lookup
  order, which couples the tests to the tuned configs and heuristics.
- test_triton_unified_attn_sw_verify_split and
  test_triton_unified_attn_sw_split_no_sinks no longer record or assert
  the grid. Both still compare full and trimmed tables, or the no-sink
  long-page shapes, against the reference.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [Triton/Gluon] Window-aware split-KV for sliding-window attention

With a sliding window, every split-KV launch carved [0, seq_len) into
NUM_SEGMENTS tile ranges, so over an untrimmed long context only the few
segments that overlap the window did work. That is why this PR so far
split only tables bounded by the window.

Carve only the window instead. For SLIDING_WINDOW > 0 each sequence
splits the tiles [tile_lo, cdiv(seq_len, TILE_SIZE)), where tile_lo is
the tile of row 0's first visible key, max(context_len - SLIDING_WINDOW
+ 1, 0) // TILE_SIZE. It is per sequence, so every query block and the
reduce agree. The split launch already puts a sequence's spec-decode rows
in one query block when q * num_queries_per_kv <= 128. The window's tiles
are now what gets split across the segment workgroups.

- The gfx950 gluon split, kernel_unified_attention_3d and reduce_segments
  carve this way. The triton pair shares split_window_tiles, and
  reduce_segments gets SLIDING_WINDOW from the launch. The gfx1250 3d
  wrapper asserts no window: its split still carves seq_len, and
  use_2d_kernel never sends a window there. With no window, all three
  kernels compile to the same gfx950 instructions as before.
- Dispatch: an untrimmed table now splits like a trimmed one.
  _gfx950_split_grid drops the bound check and keeps the q <= 16 and
  q * num_queries_per_kv <= 128 gates. The kv_len clamp applies to every
  sliding-window call. The SWB axis and sliding_window_bounds_kv are gone,
  and the split entry is SW_GEQ_256.Q_GEQ_2, so sliding-window decode
  stays on the capped bare SW entry. CPU dispatch sweep vs the previous
  commit, 3,692,160 shapes per arch: on gfx950 the only change is 75,220
  gluon sliding-window calls with 1 < q <= 16 past the old bound going
  2d -> split. Each gets exactly the dispatch the bounded table already
  had. gfx1250 and gfx1100 do not change.

The existing accuracy tests now run the full-table rows through the
window carve: test_triton_unified_attn_sw_verify_split and
test_triton_unified_attn_sw_split_no_sinks.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Signed-off-by: Oxana Korzh <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Satya Nikhil Kodukula <[email protected]>
…tention implementation (#4188)

* feat(flydsl): add per-tensor fp8 gfx1201 flash-attention kernel

* feat(flydsl): generalize the gfx1201 bf16 flash-attention kernel and wire fp8 dispatch

* feat(flydsl): fully-FlyDSL fp8 per-tensor quant+rotation for gfx1201

* refactor(flydsl): share and harden gfx1201 attention

* test(flydsl): cover gfx1201 bf16 and fp8 attention

* bench(flydsl): add gfx1201 fmha benchmark

* merge(main): resolve gfx1201 FlyDSL attention conflict

* fix(flydsl): validate attention softmax scale

* fix(flydsl): address gfx1201 attention review

* refactor(flydsl): centralize gfx1201 attention build parameters

* test(flydsl): execute gfx1201 pytest suite in op-test shards

* refactor(flydsl): share gfx1201 attention helpers and localize FP8 intrinsics

* refactor(flydsl): clean up gfx1201 kernels

* refactor(flydsl): organize gfx1201 FMHA modules

* refactor(flydsl): localize gfx1201 stream readiness

* refactor(flydsl): use typed pointers in fp8 quant

* refactor(flydsl): use public gfx1201 kernel attributes

* refactor(flydsl): export gfx1201 fp8 quant directly

* test(flydsl): keep gfx1201 FMHA public regressions

* feat(flydsl): add native gfx1201 1 FP8 quantization for more shapes

* flydsl: simplify gfx1201 FMHA stream/quant integration

* op_tests: modernize gfx1201 FMHA validation and benchmark

* flydsl: harden gfx1201 FMHA stream validation and multi-device tests

* flydsl: remove empty gfx1201 FMHA package init

* flydsl: migrate gfx1201 FP8 flash-attn to FlyDSL buffer-view/copy API

* flydsl: use static layouts and coordinate helpers for gfx1201 FP8 KV loads

* flydsl: validate gfx1201 FP8 buffer indices against signed Int32 limits

* flydsl: replace raw arith intrinsics with typed FlyDSL scalar/vector ops in gfx1201 FP8 FMHA

* refactor(flydsl): use typed exp2 in gfx1201 BF16 attention

* test(flydsl): tighten gfx1201 FMHA validation

* refactor: modernize gfx1201 FlyDSL FP8 paths

* test: consolidate FlyDSL gfx1201 op tests

* fix: support wide FlyDSL FP8 quantizer loads

* fix: validate FlyDSL quant offsets and stream coverage

* fix(flydsl): harden gfx1201 FMHA correctness

* fix(flydsl): align FP8 softmax normalization to prevent long-sequence normalization bias

---------

Co-authored-by: vivienfanghuagood <[email protected]>
Co-authored-by: Cursor <[email protected]>
…1250 (#6545)

* Allow the pipelined version of the kernel to be used

* Add tuning config

* More tuning changes

* Pad fp8 rows

* Update reduce waves_per_eu

* Fit 64 heads into two waves

* Add unit test

* Formatting

* Attend to Copilot review comments

* Test fixes

* Update tuning params

* Attend to Copilot review comments

* Fix formatting issues

* Add extra guards

* Add params to desc

* Fix arch name for test
* [Triton/Gluon] [Kernel] Add dual-layout H16 MXFP4 quantization

Fuse row-wise MXFP4 quantization with signed-H16 quantization of the
transposed input. Support independent stochastic rounding and GEMM
layouts on gfx950, with tests, benchmarks and a tuning configuration.

Signed-off-by: DaiXindi-AMD <[email protected]>

* [Misc] Rename fused MXFP4 tuning configuration directory

Signed-off-by: DaiXindi-AMD <[email protected]>

* [Bugfix] Address fused transpose Hadamard MXFP4 review feedback

Use the specific fused API and config key, relocate the four unchanged device helpers to quant.py, and document sign validation and physical scale shapes. Fix module-object monkeypatching after the API/module rename.

Validated all eight changed Python files with Ruff 0.16.0, Black 26.3.0 and 26.10.1, compile and diff checks. Kernel and helper AST equivalence plus isolated CPU helper checks passed. Full package import and GPU tests were not rerun: prior import/collection is blocked by missing Ninja, and no GPU allocation is authorized.

Signed-off-by: DaiXindi-AMD <[email protected]>

* [Docs] Use GPU graph capture terminology for H16 signs

Signed-off-by: DaiXindi-AMD <[email protected]>

* [Misc] Keep MXFP4 layout constants in the host utility

Move the five unchanged layout constants to utils/mxfp4.py and remove the constants-only utils/_triton/mxfp4.py module. The public wrapper still passes the same values as constexpr arguments; device kernel and helper code remain unchanged.

Signed-off-by: DaiXindi-AMD <[email protected]>

---------

Signed-off-by: DaiXindi-AMD <[email protected]>
…nch tile, add round_to_input_dtype and transpose_scale (#6024)

* [Triton/Gluon] [Perf] fused_reduce_act_mul_and_mxfp4_quant: wider launch tile, add round_to_input_dtype and transpose_scale

For N_half > 1024 (no shuffle, no scale padding, no split-K) launch one warp
per row over 256 (M <= 64) or 512 columns instead of a 1x128 tile on 4 warps.
On MI355X thats 1.02-3.77x faster over N_half 2048..28672 and M 1..8192
(9.85 -> 4.29 us at M=64, N_half=14336), output bytes unchanged.

round_to_input_dtype rounds act(x) * x_mul to the input dtype before the
quant, so the result is bitwise equal to act_mul in that dtype followed by
dynamic_mxfp4_quant. transpose_scale (also added to fused_rms_mxfp4_quant)
returns the scales column-major, the layout dynamic_mxfp4_quant returns.
Both default to False.

Signed-off-by: adlashab <[email protected]>

* Fix a typo in the act_mul launch tile comment

Signed-off-by: adlashab <[email protected]>

* [Triton/Gluon] fused_reduce_act_mul_and_mxfp4_quant: honor scaling_mode="ceil"

scaling_mode was accepted but the act_mul kernel always used the "even"
scale. Pass it through to _mxfp4_quant_op, which already has "ceil" as
SCALING_MODE 1: 2^ceil(log2(amax / 6)), the RoundUp scale
per_1x32_f4_quant_hip uses by default. With round_to_input_dtype the output
is then the same fp4 bytes and the same scales as silu_mul followed by
per_1x32_f4_quant_hip, in the same scale layout (plain, padded or shuffled),
so it can stand in for that quant in front of gemm_afp4wfp4_preshuffle /
gemm_a4w4. That is what vLLM's MXFP4 linears on the ASM layout run. One
difference: a 32-block thats all zeros gets scale byte 1 here and 92 from the
HIP kernel. All its fp4 values are 0, so the GEMM output is the same.

Also let the wider launch tile run with scale_shuffle_padding when shuffle is
off. The padding only changes the allocation, the scale store is the same.

New test against per_1x32_f4_quant_hip for plain, padded and shuffled scales.

Signed-off-by: adlashab <[email protected]>

* [Triton/Gluon] [Test] Check fused act_mul + MXFP4 quant against a torch reference

Add a plain torch reference for the per-1x32 MXFP4 quant and compare
fused_reduce_act_mul_and_mxfp4_quant against it bit for bit. The reference
uses the shared CPU helpers from aiter.utility.fp4_utils: the e8m0 scale from
f32_to_mx_e8m0_scale (Even for "even", RoundUp for "ceil"), then x / scale
rounded to nearest even on the E2M1 grid with f32_to_mxfp4.

The test covers both scaling modes, round_to_input_dtype on and off, bf16 and
fp16 input, plain / transposed / padded / shuffled scales, odd M, and an
all-zero 32-block at each end of the output. In "ceil" mode the Triton scale
clamps amax to 6 * 2^-126, so an all-zero block gets scale 1 where RoundUp
gives 0. The fp4 values of that block are 0 either way, the test expects 1.

Also use device="cuda" in the tests this PR adds, like the rest of the file
since #6783.

Signed-off-by: adlashab <[email protected]>

---------

Signed-off-by: adlashab <[email protected]>
Co-authored-by: Shao-Chun Lee <[email protected]>
Since #7029, main runs Triton Test only once a night, as the full
suite. A merge that breaks a Triton test then shows up only the next
day, and the nightly cannot say which merge it was.

A push to main now runs Triton Test again, with the same test selection
as a PR: the tests that the merged commit affects, against its parent on
main. MI300X runs only when the selection asks for it, as on a PR. Each
push gets a concurrency group of its own, so a merge no longer cancels
the run of the one before. A push run does not wait for the pre-checks
and does not post on the nightly status issue.

The nightly and manual runs still run the full suite on MI35X and
MI300X.

Co-authored-by: Xin Huang <[email protected]>
…ile, tuned defaults (on by default) (#7315)

* [FlyDSL] [gfx1250] mega_moe S1F: reachable stage-1 hook, plan precompile, opt-in tuning knobs

On top of the stage-1 fusion (#6564):

- Fix: swap the stage-1 hook into dispatch_context as well as scatter. The
  grouped GEMM reads it off dispatch_context, so replacing scatter alone
  left the probe / fused stage-1 path unreachable on the compact path.
- Precompile every stage-1 compact-plan variant at setup (compile only,
  AITER_S1F_PRECOMPILE=0 skips). Eager widths otherwise JIT-compiled inside
  the serving loop: 250-470 ms prefill steps for the first ~100 s of a run.
- AITER_S1F_MAX_RECV=N: steps whose receive bound exceeds N run the whole
  S1F=0 path (plan, GEMM1, no probe), e.g. fuse decode only.
- AITER_S1F_ANY_TILE=1: fuse when the tuned GEMM1's tile_m matches; the
  stage-1 kernel runs its own 256x256 n/k tiles.
- AITER_S1F_PRODUCERS / AITER_S1F_BLOCK_RUNS: per tokens-per-rank bucket
  overrides of the stage-1 tables.
- AITER_TDM_COMPACT_ROUTE_UPTO / _ROUTE_SPEC / _ROUTE_PARALLEL: keep the
  route-parallel compact walk up to N tokens per rank.

All knobs default to the current behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [FlyDSL] [gfx1250] mega_moe S1F: make S1F and its tuned settings the default

Make S1F and its tuned settings the default on gfx1250; env vars become
optional overrides. With nothing set, gfx1250 MegaMoE now runs the
configuration measured on DSV4.1-Flash DEP4 (MI455X, MLPerf Endpoints
agentic c512, +2.1% gen tok/s/GPU over S1F off):

- AITER_MEGA_S1F: on by default; =0 turns the stage-1 fusion off. Configs
  or steps that do not fit still fall back to dispatch + GEMM1; the
  fallback logs at info level unless AITER_MEGA_S1F=1 was set explicitly.
- S1F_BLOCK_RUNS table: (4, 2, 8, 8). AITER_S1F_BLOCK_RUNS /
  AITER_S1F_PRODUCERS still override the tables.
- AITER_S1F_MAX_RECV: 4096 by default; 0 means no limit.
- AITER_S1F_ANY_TILE: on by default; =0 requires all GEMM1 tiles to match.
- AITER_TDM_COMPACT_ROUTE_UPTO / _ROUTE_SPEC: 1024 / 384,16 by default
  (config._COMPACT_ROUTE_UPTO / _SPEC); UPTO=0 keeps _DISPATCH_COMPACT.
- AITER_S1F_PRECOMPILE stays on by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Read the new S1F/route env vars through the shared env module

Register the env vars this PR adds or changes (AITER_MEGA_S1F,
AITER_S1F_PRECOMPILE / MAX_RECV / ANY_TILE / PRODUCERS / BLOCK_RUNS,
AITER_TDM_COMPACT_ROUTE_UPTO / SPEC / PARALLEL) in mega_moe/envs.py, with
their defaults and parsing, and read them as envs.<NAME> instead of
os.environ. Env vars that were already on main are left as they are.
No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Drop the new env vars; the tuned S1F/route settings are fixed defaults

This PR no longer adds any environment variable. mega_moe/envs.py is back
to main, and the settings tuned on DSV4.1-Flash DEP4 (MI455X, MLPerf
Endpoints agentic c512) are now plain defaults:

- stage-1 plans are always precompiled when S1F is on;
- _S1F_MAX_RECV = 4096 (s1f_ctl.py);
- GEMM1 fuses whenever its tile_m matches (stage-1 runs its own n/k tiles);
- S1F_PRODUCERS / S1F_BLOCK_RUNS come from the s1f_stage1.py tables
  (block runs 4, 2, 8, 8);
- the compact dispatch always walks routes up to _COMPACT_ROUTE_UPTO = 1024
  tokens/rank with _COMPACT_ROUTE_SPEC = (384, 16) (config.py); the
  AITER_TDM_COMPACT_BLOCKS/WARPS override behaves as on main.

AITER_MEGA_S1F keeps its original os.environ read; only its default
changes to on (0 turns it off). S1F fallbacks log at info level.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
* [CI] Reduce A8W8 GEMM benchmark repetition and preserve scale-mode coverage

Signed-off-by: yifehuan <[email protected]>

* Use supported MXFP8 row sizes in focused numerical tests

Signed-off-by: yifehuan <yifehuan@local>

* [CI] Reuse FlyDSL AOT cache and sample A8W8 benchmark timing

Signed-off-by: yifehuan <[email protected]>

---------

Signed-off-by: yifehuan <[email protected]>
Signed-off-by: yifehuan <yifehuan@local>
Signed-off-by: yifehuan <[email protected]>
Co-authored-by: yifehuan <[email protected]>
Co-authored-by: yifehuan <yifehuan@local>
Pass address-only grouped GEMM operands as typed pointers instead of flattened tensors. FlyDSL packs runtime tensor dimensions as int32, so buffers with more than 2^31-1 elements fail in the generated C ABI fill function. The EP arena handle remains a constexpr and is already excluded from runtime packing.

Remove redundant scale-view normalization and replace its tests with host ABI coverage for large buffers, storage offsets, pitched layouts, cached dispatch, 48-bit addresses, and changed arena specializations.

Signed-off-by: Felix Li <[email protected]>
…cture plumbing (#6767)

* [JIT] Add gfx1250-strict architecture plumbing

* [JIT] Fix ruff F821 and black formatting in gfx1250-strict plumbing

Add the missing build_targets._parse_gpu_archs_env import in core.py
(F821 flagged by CI ruff) and apply black to core.py and
test_build_targets_architecture.py.

Co-Authored-By: Claude Code <[email protected]>

* [JIT] Add gfx1250-strict kernel inventory and WS2 build driver

Skeleton inventory for every JIT/FlyDSL/Triton path plus the driver that
fills its strict-build column from a strict-capable container.

Driver verified offline on a non-strict host (module enumeration, child
plumbing, skip classification, --update-md folding):

- CHILD called os.chdir without importing os, so every module would have
  failed with NameError and the whole matrix would have read "fail".
- optCompilerConfig lists 135 modules but get_args_of_build("all") yields
  123. The other 12 are not failures: 10 end in "tune" (skipped by design)
  and 2 are experimental (gated by AITER_ENABLE_EXPERIMENTAL). They are now
  recorded as skip-tune / skip-experimental instead of "missing", so the
  matrix keeps an explicit result for all 135.

Actual pass/fail rows still require the strict toolchain; stock ROCm 7.0.0
rejects gfx1250-strict as an invalid target ID.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Fix empty GPU_ARCHS raising out of build_module

The gfx1250-strict plumbing routed GPU_ARCHS through
build_targets._parse_gpu_archs_env, which raises when the value holds no
architecture names. GPU_ARCHS set but empty -- what a Dockerfile's
`ENV GPU_ARCHS=` or a bare `export GPU_ARCHS=` produces -- previously just
meant "no cluster-launch flag, build normally"; it now raised RuntimeError
inside build_module and failed every JIT build. Blank, whitespace-only and
";" values had the same problem.

Fall back to the detected arch instead, matching aiter/ops/opus/_arch.py,
which treats an empty or "native" GPU_ARCHS as "probe the device" and
never raises. The arch test moves into _build_archs_from_env /
_cluster_launch_target so it is reachable from a CPU-only test.

Covered by TestClusterLaunchBuildArchs: blank/unset/"native" fall back to
detection, explicit archs win, and -DAITER_ENABLE_CLUSTER_LAUNCH still
follows gfx1250 or gfx1250-strict anywhere in a multi-arch GPU_ARCHS.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Inventory the gfx1250 dispatch sites a strict device silently misses

The infra PR keeps gfx1250-strict distinct through parsing, build selection
and the asm guard, but Python dispatch still compares against the exact
literal "gfx1250". On A0 get_gfx() returns "gfx1250-strict", so those
comparisons are False and the constant arch allowlists do not contain it:
the gfx1250 path is skipped with no error, which reads as a kernel-selection
change rather than a failure.

ws2_gfx1250_dispatch_sites.py enumerates them -- 150 uses across 65 files,
132 runtime comparisons and 18 allowlist entries -- and records where the
compared string comes from. get_gfx/get_gfx_runtime sites keep the
hyphenated spelling and are known to miss; triton-arch sites read Triton's
own target name, whose strict spelling stays unverified until the toolchain
lands.

The table is generated into the inventory between HTML markers and the
rewrite is idempotent, so it can be refreshed as owners decide each site.
No dispatch behaviour is changed here: every row is an explicit pending
decision, which is what workstream 2 asks for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Pin the offload-target parser against hyphenated target names

_so_offload_archs backs the guard that keeps a gfx1250 and a gfx1250-strict
.so from standing in for each other, so the shapes it must parse deserve a
test of their own: a feature list after ':', the strict suffix, both
together, and a ROCm generic target.

The previous gfx\w+ pattern truncated at the first hyphen. That reported a
strict .so as plain gfx1250 -- the substitution this guard exists to
prevent -- and also read gfx9-4-generic as gfx9, which matches no running
arch and so rebuilt such a module on every import.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Inventory the arch-keyed tables that have no strict entry

The dispatch-site scan only saw comparisons against the "gfx1250" literal,
which left a blind spot: tables keyed by architecture. A strict device is
simply absent from those, so it takes whatever the lookup does with a
missing key.

Four of them carry a gfx1250 entry and no strict entry, and they do not
behave alike:

- radix_topk_one_block._LONG_RADIX_BY_ARCH and ._ONE_BLOCK_LDS_BUDGET_BYTES
  read with a default, so A0 quietly falls back to the generic radix layout
  and a zero LDS budget, losing the 320 KiB one-block path with nothing
  logged.
- pa_decode's inline fp8 dtype table reads with .get() and raises
  NotImplementedError naming the arch -- the "fail clearly" behaviour the
  enablement plan asks for.
- mhc.MHC_FUSED_POST_PRE_M_UPPER_BOUND reads with a default of 1024, which
  happens to equal the gfx1250 entry, so A0 is correct today only by
  coincidence.

The generated table records the lookup style per row so the difference
between a silent fallback and a clear failure is visible to the owner
making the call. Behaviour is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Extend the gfx1250 site inventory to C++ and skip handled sites

get_gpu_arch() in aiter_hip_common.h cuts the target id at ':' and keeps
everything before it, so a strict device reports "gfx1250-strict" in C++
too and the arch_id == "gfx1250" branches miss exactly as the Python ones
do. 27 of them across 14 files, 11 in mha_bwd.cu alone, where several pick
launch geometry rather than a code path -- a miss changes a block size
instead of raising.

Worth recording for the Opus owner: opus_co_launch_gfx1250.cuh builds its
code-object path from get_gpu_arch(), so A0 looks for gen_co/gfx1250-strict
and fails with a clear AITER_CHECK rather than loading a B0 object. That is
what the plan asks for, so it is called out in the table's preamble instead
of being listed as a gap.

The scan now skips any site with a strict spelling within four lines, so
the asm gate's own early return no longer pads the table and a site drops
out once an owner has handled it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Count the tuned rows a strict device cannot use

Tuned GEMM and MoE configs carry a gfx column and are looked up through
get_gfx(), which reports gfx1250-strict on A0. 1620 rows across 18 config
files are keyed to gfx1250 and none to gfx1250-strict, so on A0 every shape
they cover falls back to the default path.

That is what the plan asks for -- strict tuning has to be explicit and
measured, not a filename alias -- so the generated table is the workstream
3 worklist rather than a defect list: each file needs either measured
strict rows or a recorded decision that the B0 rows hold on A0.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Generate the module table's gfx1250 signal column

The column was hand-filled and followed no single rule: 13 of 135 rows
disagreed with any consistent reading of the sources, in both directions.
module_custom_all_reduce_gfx1250 was marked by its module name while
module_cache was marked `guard` although its sources also compare against
the "gfx1250" string literal. Owners use this column to decide where to
look, so wrong values send them to the wrong file.

--refresh-signals now computes it from the sources that
core.get_args_of_build actually resolves, falling back to the raw config
expressions for the tune and experimental modules that call skips. The
markers are explicit and can combine: `name` for the module name, `str` for
the "gfx1250" string literal, `macro` for the __gfx1250__ guard.

The distinction matters for A0 risk. `macro` rows keep compiling, because
the strict target defines both __gfx1250_strict__ and __gfx1250__. `str`
rows are the runtime decisions a strict device silently misses. The refresh
changed 27 cells and is idempotent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Tie the three arch tables together with a test

Adding a target means editing GFX_MAP, GFX_CU_NUM_MAP and core.py's
allowed_archs, and nothing tied them together. allowed_archs carried a
duplicate "gfx1250" entry until this series removed it, which is what that
drift looks like in practice.

Two invariants hold today and are now pinned: every arch with an offline CU
default is accepted by validate_and_update_archs and maps back through
GFX_MAP, and gfx1250-strict does the same. Deleting gfx1250-strict from
allowed_archs fails both tests, so a half-landed target is caught in CPU-only
CI rather than at build time.

The check is behavioural -- it drives validate_and_update_archs and
get_gfx_custom_op_core with GPU_ARCHS set -- so it also covers the arch
reaching hipcc unchanged as --offload-arch, hyphen included.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Record CK modules as skipped when the submodule is not checked out

aiter's CK-free auto-exclusion tests os.path.isdir(CK_3RDPARTY_DIR), which
is True for an uninitialised submodule: the directory exists, it is simply
empty. A checkout without `git submodule update` therefore still tries to
build the CK modules, and they fail on missing sources.

core._get_ck_exclude_modules() reports 69 of the 135 modules as
CK-dependent, so on such a checkout more than half the build matrix would
fill with failures that say nothing about the strict target. The driver now
treats an empty composable_kernel directory as CK-free and records those
modules as skip-no-ck, keeping pass/fail for results that are actually
about gfx1250-strict.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Pin PYTORCH_ROCM_ARCH in the build driver

Setting GPU_ARCHS alone does not reach the compiler. torch's cpp_extension
takes --offload-arch from PYTORCH_ROCM_ARCH, so with GPU_ARCHS=gfx1250 the
modules still compiled for torch's own default list -- observed in a ROCm
10.0.0 container as

  --offload-arch=gfx90a ... --offload-arch=gfx1151

with no gfx1250 anywhere. Every row of the matrix would have been a result
for the wrong architectures while looking like a validated one. The driver
now derives PYTORCH_ROCM_ARCH from GPU_ARCHS; with that fixed,
module_aiter_unary builds for gfx1250 and build.ninja carries exactly one
--offload-arch.

Failures also kept the wrong 15 lines: ninja echoes the whole compile
command, which pushes the diagnostic out of a plain tail, so a failing
module recorded only the Python traceback. The recorded tail now leads with
up to five "error:" lines.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Record what ROCm 10.0.0 does and does not provide for strict

Checked in rocm/atom-dev:latest-rocm10.0 -- ROCm 10.0.0, AMD clang
23.0.0git (ROCm/llvm-project 8f497e0992fb), HIP 7.15.26333. hipcc compiles
gfx942 and gfx1250 and rejects gfx1250-strict as an unsupported HIP gpu
architecture. The processor list is gfx1250 and gfx1251, and neither
libLLVM nor amdclang contains the string gfx1250-strict or
__gfx1250_strict__ at all.

The only A0/B0 notion in that toolchain is the AMDGPU subtarget feature
gfx1250-b0-specific, and it is not reachable from the driver: not a
processor, rejected inside a target id, and ignored as a clang target
feature.

So the build matrix cannot be filled from the public ROCm 10 container --
the plan's toolchain dependency is unmet rather than satisfied -- and there
is a question worth settling before the identity model is locked in. If the
mechanism that ships is a subtarget feature on gfx1250 rather than a
separate processor name, an A0 and a B0 object both carry the target id
gfx1250, which is exactly what _so_offload_archs reads, so that guard would
need a different discriminator. The survey records the evidence and the
question without presuming the answer.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [JIT] Lead the recorded failure tail with the real compiler diagnostic

The error capture grabbed the first five lines containing "error:", which
on a failing build are usually the Python RuntimeError and
CalledProcessError wrapper lines, not the compiler's own message. Prefer
"file:line:col: error:" frontend diagnostics when present, fall back to any
"error:" line otherwise (backend errors such as the gfx1250 DPP rejection
have no file:line prefix), and de-duplicate -- clang repeats each
diagnostic once per offload arch.

Verified against a real ROCm 10 matrix run: the ck_tile "extraneous closing
brace" / "template exec" and ck "operator[] in Tuple<>" errors now lead
their tails instead of the wrapper, and the opus DPP "broadcasts are not
supported on GFX10+" backend error still surfaces via the fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Record the measured gfx1250 build matrix on ROCm 10.0.0

Ran the full 135-module matrix in rocm/atom-dev:latest-rocm10.0 with
GPU_ARCHS/PYTORCH_ROCM_ARCH=gfx1250: 102 pass, 21 fail, 12 skip. Strict
itself does not compile in this toolchain, so this is the gfx1250 baseline
-- anything that fails for gfx1250 cannot build for strict, which is gfx1250
plus an A0 code-object identity.

Every failure was rebuilt for gfx942 as a control, which corrected my first
read of them. They are not a ROCm-10/clang-23 regression: 18 of 21 build
cleanly on gfx942 and fail only on gfx1250, and the 3 FMHA-bwd modules that
timed out on gfx942 were compiling without error (module_mha_bwd from the
same family finished and passed). Every failure is a genuine gfx1250
porting gap:

- DPP broadcast dpp_ctrl modes GFX12 removed (moe_sorting_opus,
  moe_mxfp4_aux)
- MFMA / buffer-load-LDS intrinsics GFX12 lacks (iq2r_moe,
  mha_fwd_native_splitkv)
- a wavefrontsize64 request on a wave32 part (chunk_gdr_fwd_h)
- warp-size and gfx950-trait static assertions (topk_plain, moe_opus)
- CK's ck_tile TDM path, selected on gfx1250 by
  CK_TILE_USE_BUFFER_ADDRESSING_BUILTIN=0 (the cktile/blockscale GEMMs,
  activation, sample, the ck_tile FMHA fwd/prefill)
- fmha-v3-bwd asm configs not generated for gfx1250 (the mha_bwd family)

The inventory now carries the result table with the gfx942 control column
and the per-module cause, as the workstream-2 porting worklist.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Correct the strict macro model and inventory __gfx1250__ guards

The plan claimed the strict target defines both __gfx1250_strict__ and
__gfx1250__, so existing __gfx1250__ guards keep compiling. ROCm 10.1's
actual behaviour is the opposite: strict defines __gfx1250_strict__ and
does NOT define __gfx1250__ (ROCm/rocm-systems#12068). A __gfx1250__-only
device guard therefore compiles its body away on a strict agent -- a silent
empty kernel, the upstream TDM_Basic_load_2d failure, with no build error.
JAX hit the matching compiler-side fact and dropped strict from its ROCm
10.0 defaults (jax-ml/jax#41187), and ROCm 10.1 adds gfx1250-strict as a
distinct --offload-arch target across the stack (RCCL, CK, rocSHMEM), which
confirms this PR's distinct-name identity model and the .so guard that keys
on it.

Fixes, docs only -- no source guard is touched, because the change must not
break the shipping ROCm 7 build, whose compiler knows only __gfx1250__ and
has no strict target:

- plan and inventory legend now state the real macro behaviour and the
  backward-compatible fix, `defined(__gfx1250__) || defined(__gfx1250_strict__)`,
  whose strict arm is simply never taken on ROCm 7.
- the ROCm 10.0 survey's open "name vs feature" question is resolved: 10.1
  ships a distinct target name; the 10.0 gfx1250-b0-specific subtarget
  feature was an early-LLVM artifact.
- ws2_gfx1250_dispatch_sites.py now also inventories the __gfx1250__
  preprocessor guards (95 across 24 csrc files) as a generated review table,
  flagging which already combine with ||/&& to read first. This is the class
  the earlier string-comparison scan did not cover.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Make every __gfx1250__ device guard also fire on strict

Non-asm operators are meant to run on both MI450 SKUs (A0 = gfx1250-strict,
B0 = gfx1250); only the shipped asm is B0-only. But the strict compiler
defines __gfx1250_strict__ and not __gfx1250__, so every
`#if defined(__gfx1250__)` device guard took its #else branch on a strict
build -- a silent wrong path that still compiles. Read on A0 this is:
get_smem_size returning 64 KB instead of 320 KB, mhc falling back to fp32
instead of the WMMA path, make_gmem returning the 0xffffffff sentinel so
stores drop, and the TDM sync counters using the legacy lgkmcnt/vmcnt
instead of the split dscnt/loadcnt.

Rewrite all 97 `defined(__gfx1250__)` occurrences across 24 csrc files to
`(defined(__gfx1250__) || defined(__gfx1250_strict__))`. The parentheses
keep it correct in every context: positive guards, `!(...)` exclusion
lists (strict is excluded exactly as gfx1250 is), and `||`/`&&` family
lists. The strict arm is never taken on the shipping ROCm 7 build, which
has no strict target, so that build is unaffected.

Compile-verified on ROCm 10.1 (clang 24.0.0git) for both gfx1250-strict and
gfx1250 on module_mhc and module_top_k_per_row; both pass for both targets
at low parallelism (the earlier full-matrix failures for these were -j179
contention, not real). Runtime correctness on A0 is left to the daily A0
op-test once the modules are built as gfx1250-strict.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Add strict to the compiled-path gfx1250 dispatch comparisons

Non-asm operators run on both MI450 SKUs, and strict is gfx1250 (A0)
hardware, so a `get_gfx() == "gfx1250"` dispatch that selects a compiled
path must also fire on gfx1250-strict -- otherwise A0 silently takes the
generic fallback and, where the gfx1250 branch picks an arch-specific
layout (wave32 tiling, LDS budget), gets a wrong result, not just a slow
one.

Rewrite the 101 compiled-path comparisons across 51 files from
`== "gfx1250"` / `in ("gfx1250",)` to `in ("gfx1250", "gfx1250-strict")`.

Deliberately NOT changed: the one asm-selecting dispatch,
gemm_op_a4w4.py `if gfx_arch in ["gfx1250"]`. Adding strict there would
route A0 into the f4gemm asm path, which the asm gate then throws on --
and the policy is that asm is simply unavailable on A0, so strict must keep
missing that comparison and fall to the compiled path. The classifier that
split compiled from asm sites flagged exactly this one site.

py_compile, ruff and black clean (topk.py's pre-existing fmt:skip parse
issue aside); the CPU-only arch/dispatch tests still pass. Multi-element
arch allowlists (gluon_archs, SUPPORTED_ARCHS) are left for a follow-up --
those are a capability/feature gap on strict, not the correctness-level
layout divergence this commit closes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Cover != "gfx1250" and post-merge dispatch sites for strict

The first dispatch pass only rewrote == and single-element `in (...)`
comparisons, so `!= "gfx1250"` negations were left behind -- on strict
`arch != "gfx1250"` is True and the kernel takes the non-gfx1250 branch,
the same silent-wrong-path class the == sites had. The main merge also
added fresh gfx1250 comparisons (flydsl pa_decode, triton quant/mla,
mla backend plan).

Fix the 30 compiled-path sites: `!= "gfx1250"` ->
`not in ("gfx1250", "gfx1250-strict")`, `== "gfx1250"` -> `in (...)`.
Three asm-selecting sites are deliberately left (attention.py:1752,
mha.py:3779, mla_sparse_prefill.py:100) so strict keeps missing them and
A0 errors on asm rather than loading it, per the policy that asm is
unavailable on A0.

py_compile, ruff and black clean; CPU-only arch tests pass. Only the three
asm sites now compare against the bare "gfx1250" literal.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Add strict to the C++ arch_id == "gfx1250" dispatch comparisons

get_gpu_arch() in aiter_hip_common.h keeps the full target id, so a strict
device reports "gfx1250-strict" and every `arch_id == "gfx1250"` branch in
csrc misses -- the same silent-wrong-path class the Python and __gfx1250__
guards had. has_tdm_arch() returned false on strict even though A0 has TDM;
mha_bwd picked the wrong launch geometry; and so on.

Rewrite the 28 comparisons across 14 files: `X == "gfx1250"` ->
`(X == "gfx1250" || X == "gfx1250-strict")`, `X != "gfx1250"` ->
`(X != "gfx1250" && X != "gfx1250-strict")`, where X is a plain identifier
or get_gpu_arch(). The asm-dispatch sites are included too: the actual asm
load still funnels through require_gfx1250_asm_or_throw, which throws on A0,
so computing the dispatch as gfx1250 is safe and A0 still cannot load asm.

The already-strict-aware asm gate in aiter_hip_common.h is left untouched.
Paren balance verified; the gfx942/gfx950 C++ build in CI compiles it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Add strict to the multi-element arch allowlists

The capability allowlists -- gluon_archs, SUPPORTED_ARCHS, _SUPPORTED_GFX,
DEVICE_ARCH tuples, the triton tuning kernel decorators -- list gfx1250 as
a supported arch but not gfx1250-strict, so strict (which is gfx1250
hardware) was treated as unsupported: no gluon path, excluded from the
tuned kernel sets, etc.

Add "gfx1250-strict" next to each "gfx1250" element in those arch tuples
and lists (41 across 22 files), skipping the substring-match helper
(quick_all_reduce's `gfx in arch`, where "gfx1250" already matches
"gfx1250-strict") and any asm-selecting context. With the gemm_a4w4 path
main restructured, the gfx1250 branch now routes plain MXFP4 to FlyDSL and
the rest to asm, so strict correctly gets the FlyDSL path and the asm gate
still handles A0.

ruff and black clean; CPU-only arch tests pass. This closes the last
aiter-side strict dispatch gap; what remains is A0 runtime validation and
the Opus .co rebuild.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Pin flydsl to 0.4.0.dev973 for gfx1250-strict LDS support

FlyDSL's arch handling is otherwise strict-ready because it matches by
prefix (arch.startswith("gfx1250") / "gfx12"), which gfx1250-strict
satisfies -- WMMA instruction selection, warp_size (32) and the compile
target all come out right. The one gap was the LDS-capacity map, keyed on
the exact "gfx1250" string, so on strict the lookup missed and
check_smem_capacity silently skipped the overflow guard.

0.4.0.dev973 adds "gfx1250-strict": 327680 to SMEM_CAPACITY_MAP (now in
flydsl.runtime.device), closing that gap. Bump the pin in requirements.txt
and setup.py (the version assertion and auto-install both derive from
FLYDSL_VERSION). Revert to the default release once the fix ships there.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Clean up: drop investigation tooling, tidy strict macro guards

Self-review cleanup, no behaviour change:

- Remove the ws2_* enumeration/matrix scripts and the generated
  kernel-inventory doc. Those were one-off investigation flow (build
  matrix, dispatch-site enumeration) and do not belong in the repo; nothing
  in aiter imports them.
- Drop the dangling "former hotswap path" bullet from the enablement plan;
  the term exists nowhere in the tree.
- Flatten the redundant parentheses the strict sweep left behind: the
  mechanical `defined(__gfx1250__)` -> `(defined(__gfx1250__) ||
  defined(__gfx1250_strict__))` wrapped the pair even inside OR chains.
  Unwrap it where the context is pure-OR (90 sites); keep the parentheses
  only where they are load-bearing -- negation `!(...)` and `&&` operands
  (7 sites). Compile-verified on ROCm 10.1 for both gfx1250-strict and
  gfx1250 (module_mhc, module_top_k_per_row); CPU-only arch tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: pin flydsl build-system dep to 0.4.0.dev973 to match setup.py

pyproject.toml build-system.requires still pinned flydsl==0.4.0 while
setup.py (FLYDSL_VERSION) and requirements.txt use 0.4.0.dev973. Under
build isolation pip installed 0.4.0 as the build dep, then setup.py's
version assertion rejected it and the build failed. Align all three.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: asm-gate error message covers both A0 detection routes

The gate blocks B0 asm on A0 via two routes: gcnArchName == gfx1250-strict,
or gcnArchName == gfx1250 with asicRevision 0. The message hardcoded
'gfx1250-strict/A0', which misleads when A0 is caught by the asicRevision
route (device name is literally gfx1250, rev 0). State both forms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: strict Opus codegen + 4 CI-red CPU tests

gen_instances: GPU_ARCHS=gfx1250-strict looked up KERNEL_REGISTRY by the
strict name, which has no registry key, so Opus codegen emitted an empty
header and module_deepgemm_opus failed to build (the only strict-specific
failure of the strict build matrix). Fold the registry key to the gfx1250
family (mirroring chip_info._detect_native) while keeping the gfx1250-strict
build target, so hipcc still compiles for mach 0xeb. Strict now resolves to
256 CU, same as gfx1250.

Tests (Draft CI had skipped these):
- test_opus_co_profile load_chip_parsers: keep the _GFX_ARCH_PATTERN constant
  in the extracted AST namespace (the strict PR added it; parsers NameError'd).
- test_build_targets preserve->normalize: _detect_native now folds strict to
  gfx1250 for dispatch; assert the new behavior.
- test_launcher_does_not_pin_the_first_device: use the first declared local
  kid instead of hard-coded global kid 21016 (removed by #6937).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: strict Opus codegen emits the gfx1250 family (routes>0), not an empty module

The earlier fix only folded the target list; the real route generation still
queried the registry by the strict name and produced routes=0 (empty
module_deepgemm_opus). Apply the gfx1250 family name at every registry/namespace
lookup -- available's 'if gfx in arches', get_registry, default_compiled_keys --
and at the OPUS_BUILD_HAS_* macro (C checks #ifdef OPUS_BUILD_HAS_GFX1250, and a
hyphenated STRICT macro is invalid C). KernelKey and the build target keep the
gfx1250-strict spelling, so hipcc still offloads for mach 0xeb.

Verified: GPU_ARCHS=gfx1250-strict now yields routes=228 (== gfx1250) with
OPUS_BUILD_HAS_GFX1250; CPU tests stay green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [JIT] Opus codegen: normalize gfx1250-strict targets to the gfx1250 family at the source

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: bump flydsl pin to 0.4.0 to match main (dev973 would downgrade it on merge)

main pins flydsl==0.4.0; this PR still carried the 0.4.0.dev973 prerelease,
so merging would silently downgrade the whole repo. 0.4.0 is a superset of
dev973 (contains the gfx1250-strict LDS fix) and is what main already uses.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test: drop redundant test_strict_resolves_through_all_three_tables

test_every_offline_target_resolves_through_all_three_tables already loops
over GFX_CU_NUM_MAP, which contains gfx1250-strict, so the strict-specific
case was an exact duplicate of one loop iteration.

* fix: avoid 'in' tuple test in gluon kernel constexpr (unsupported by gluon)

The strict-allowlist sweep turned 'ARCH == "gfx1250"' into
'ARCH in ("gfx1250", "gfx1250-strict")' inside gluon kernel bodies/constexpr.
Triton's gluon compiler does not implement the 'In' AST operator, so these
kernels failed to compile ('AST comparison operator In is not implemented'),
breaking test_pa_mqa_logits_2d_context_lens[gluon*] on gfx942/gfx950. Use
'(x == a or x == b)', which gluon supports, in kernel scope. Host-side Python
'in' checks are unaffected and left as-is.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Preserve exact gfx1250-strict identity; map to gfx1250 family only at dispatch

Per the ROCr rollout contract (all SW consumes the exact GFX ID ROCr reports),
global normalization in _detect_native() is the wrong boundary. Once ROCr
reports gfx1250-strict for A0, folding it to gfx1250 there makes
_needs_arch_rebuild() treat a strict .so as not covering a strict device and
rebuild in a loop; it also remixes A0/B0 in tuned configs, caches, and logs.

- chip_info._detect_native: drop the strict->gfx1250 fold; return the exact
  ROCr-reported identity. get_gfx_runtime()/get_gfx() now report gfx1250-strict
  on A0.
- build_targets.py: add the single source of truth for family folding --
  GFX_BASE_ARCH, base_gfx_arch(), is_gfx1250_family(). Torch-free, so build
  scripts and tests import it without side effects.
- Opus: replace its two private strict->gfx1250 folds (gen_instances
  _registry_arch, opus_gemm_common _get_registry_records/get_registry/
  default_compiled_keys) with base_gfx_arch(), so there is no second mapping.
  hipcc still gets --offload-arch=gfx1250-strict and the .co stays mach-0xeb.
- mega_moe _require_gfx1250: restore the gfx1250-family guard (via
  is_gfx1250_family) that main's #6430 refactor collapsed to bare gfx1250.
- Build/cache/tuning/.so/.co/ASM keep the exact identity: _needs_arch_rebuild
  and _so_offload_archs already key on it, so A0 never loads a B0 object.
- Pre-existing gfx1250-only dispatch sites authored by other PRs stay exact;
  with the fold gone they correctly distinguish strict (fall back) instead of
  silently reusing a B0 path.
- Tests: flip the native-detection test into a regression lock that strict
  identity is preserved; add family-helper and 4-way code-object rebuild-guard
  tests (runtime/built strict x gfx1250 -> accept/reject).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Apply ruff import sort and black formatting to the identity refactor

Fixes the pre-checks (ruff I001 import order in mega_moe, black reformat of
mega_moe and test_build_targets_architecture) that gated check-signal and
skipped the Triton/Aiter test runs. No logic change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* black: wrap the long gfx1250/gfx1250-strict dispatch conditions in the gluon kernels

The in->or fix in the pa_mqa_logits / unified_attention_2d gluon kernels left
two over-length boolean conditions that Black wraps. Formatting only; the
gluon compiler still sees the same (x == a or x == b) expression.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Define Opus base_gfx_arch locally instead of importing build_targets

The cross-package `from build_targets import base_gfx_arch` (via a
__file__-relative sys.path insert) breaks the Aiter wheel build:
gen_instances.py runs from a staging tree (aiter_meta/csrc/opus_gemm) where
../../aiter/jit/utils does not exist, so module_deepgemm_opus failed with
ModuleNotFoundError: No module named 'build_targets'. Duplicate the one-line
helper locally in opus_gemm_common (documented to mirror
build_targets.base_gfx_arch) so the standalone Opus codegen has no cross-tree
import dependency. gen_instances keeps importing it from opus_gemm_common.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(jit_cache): seed _cluster_launch_target in the build_module sandbox

test_jit_cache_transaction AST-extracts build_module into a sandbox namespace
with CPU deps injected. Since the gfx1250-strict work added a
_cluster_launch_target(get_gfx) call inside MainFunc, the sandbox hit
NameError: name '_cluster_launch_target' is not defined (25 TestBuildPublication
errors on MI35X). This surfaced only now because the earlier Opus wheel-build
failure skipped the standard tests. Inject the dependency like the others; for
the gfx942 test context the real function returns False, so the mock matches.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: zufayu <[email protected]>
Co-authored-by: Claude Code <[email protected]>
Co-authored-by: root <[email protected]>
* optimize the mxfp8 op for decode shape

* retune mxfp8 tables with optimize decode shape

---------

Co-authored-by: solin <[email protected]>
…nergy (#6970)

* [Tuner] Rank accuracy-qualified kernels by package energy

Add --select power so shared tuners keep the lowest runtime times PPT watts. The accuracy gate is unchanged, and latency remains the default.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Satisfy black and ruff on the power-selection change

Format the tuner edits and replace the NaN self-comparisons and bare exception handlers that the pre-check jobs reject.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Keep latency order when package power is missing

Sort power candidates by energy and then latency so an unread sensor cannot drop the fastest kernel. A single AITER_POWER_PATH is rejected when more than one tuner process is running.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Keep power-tuned rows apart from latency tables

Power tunes of shipped tables now write to aiter/configs/power_configs/, which loads only with AITER_SELECT=power and replaces only the shapes it covers. Each power row records perf level, power cap, and SCLK range, and the config merge refuses to auto-resolve power rows against latency rows or rows tuned under different conditions. Power mode is marked experimental.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Isolate power-kernel selection from the tuner and JIT path

Ranking, package-power measurement, and power_configs loading each have one owner. Latency CSV columns stay unchanged unless --select power.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Measure power with the same call the timer uses

The replay was passing run_perftest keywords into the kernel, so watts came back NaN and the row was still stamped select=power. A batch with no finite watts stays a latency result, and --select power is rejected on tuners that do not record it.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Give the MXFP4 power retime test a supported shape

Main now rejects an MXFP4 row before the scan unless dtype and quant fields match the port. The energy-ranking fixture was missing those fields, so it never reached the retime.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Format the power-selection files with Black

CI skipped the GPU tests because Black rejected these three files.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Keep the wheel build from importing the aiter package

setup.py loads jit.core before aiter exists. Importing the power overlay from that path ran aiter/__init__.py while module_aiter_core was still being registered.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Decide latency or power in one policy and measure in one place

A tuner builds a SelectionPolicy from --select and asks it for the
candidate rank, frame order, pair energy, accurate-pass count, and the
power sample. Tuners no longer branch on the select mode or write
AITER_SELECT; that variable only picks the tables jit/core loads.
mp_tuner reads the policy TunerCommon.run activates.

package_power.measure_kernel is the one power read. mp_tuner hands it
the kernel launch with the run_perftest options removed, so the window
replays the kernel back to back. Replaying run_perftest itself left the
GPU idle for most of the window.

The duplicate-shape dedup in jit/core sorts by lowest us without
importing the aiter package when setup.py loads it as jit.core.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Fix power-tune paths found by end-to-end runs on MI355X

- TunerCommon.run wrapped its body in _run, which IQ2R already defines
  as its kernel launcher, so every IQ2R tune failed. Use _run_selected.
- The a16w16 tuner built gradlib's Gemm without the policy, so hipBLASLt
  was never power-measured and always ranked last. Pass the policy, and
  default Gemm and the K5 sweep to the active policy.
- The power window queued launches without bound. IQ2R graph replays
  crash inside the HIP runtime when hundreds are queued. Keep a few
  events in flight, one per ~200 us of work, so the GPU never drains.
- IQ2R times a captured CUDA graph; sample power from that graph too.
- Staged MXFP4 logs each pair's watts like the other loops.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Correct the power sample for host launch gaps

A kernel whose Python launch takes longer than its GPU time leaves the
GPU idle between launches, so the window read close to idle and the
kernel looked efficient (split-K FlyDSL GEMMs at 256x4096x4096 read
~370 W against ~990 W replayed from a CUDA graph, and won power mode).

Every measurement site now passes the call's timed us. When the loop
never waited on the GPU, the window's busy fraction is launches * us /
window, and the reading is scaled to active power over the between-launch
baseline (a one-element kernel loop, ~300 W on MI355X). A window that
waited on the GPU kept it saturated and stands as read. Under 20% busy
the candidate stays unmeasured.

Co-authored-by: Cursor <[email protected]>

* [Tuner] Keep latency profiles as main and write only measured power rows

- MoE latency tunes write the -o2 profile and profile_fmoe.csv with
  main's columns and row order. Stage watts, rank, energy, and
  tflops_per_w appear only with --select power.
- A power tune drops rows whose watts were not measured instead of
  writing latency picks to power_configs/. Those shapes stay untuned
  and are retried by the next power tune.
- The AITER_SELECT=power overlay uses only rows stamped select=power,
  so an older or hand-copied table cannot replace shipped rows.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: yzhou103 <[email protected]>
…7214)

* FMHA gfx1250: per-tensor fp8 descales for the a8w8 kernel

Accept the q/k/v descales the gfx950 fp8 FMHA takes -- fp32, one element,
on q's device -- instead of declining them and falling through to CK.

They are scalars, so no scaled WMMA is involved. V_WMMA_SCALE_F32_16X16X128
carries an E8M0 scale, which is a power of two and cannot represent an
arbitrary fp32 descale, and the kernel already applies softmax_scale to the
fp32 logits after QK precisely because 8-bit Q cannot carry it. So the split
is the one fmha_gfx950/pipeline.py:init_descale uses:

  q_descale * k_descale  ->  folded into softmax_scale, hence into _s_scale,
                             which row_max already multiplies -- so it reaches
                             the LSE through m with no change to that line
  v_descale              ->  folded into the epilogue's per-row inv_denom,
                             scaling O alone and leaving the LSE untouched

Loaded on device from the tensors, as gfx950 does; reading them host-side
would mean .item() and a device sync on every call.

has_descale is compile-time and part of the build key, so the no-descale build
is unchanged: same 6692 instructions, same 69 SGPR / 410 VGPR / 0 spills, with
only kernarg offsets shifted by the three unused pointers.

All three must be given together, as gfx950 requires; a partial set is
ambiguous, so the gate declines it rather than assuming 1.0.

Checked: descale 1.0 is bitwise identical to the no-descale path; q*k descale
4 against softmax_scale/4 is bitwise identical to baseline; v_descale 4 scales
O by exactly 4; against an fp32 reference that dequantizes first, error is fp8
quantisation noise (3.6% non-causal, 1.4% causal); the existing fp8 sweep is
16/16 clean.

* FMHA gfx1250: black formatting for the a8w8 descale change

* FMHA gfx1250: let descale calls reach the FlyDSL varlen path

flash_attn_varlen_func gated its FlyDSL hook on `not has_all_descales` and did
not forward the descales, so a prequantized fp8 call could never reach the
a8w8 kernel even now that it handles them -- it went straight to CK.

Drop that condition and pass the three through. The FlyDSL gate already
declines what it cannot serve (16-bit inputs, a partial set, a non-scalar or
non-fp32 descale) by returning None, so anything unsupported still falls
through to CK exactly as before.

Verified through the public entry, not the internal one: the FlyDSL path is
called and serves the request, and v_descale=4 scales O by exactly 4.0000.
No regression -- fp8 16/16 and bf16 32/32 clean, the latter all at err 0.

* FMHA gfx1250: route batched descale calls to the FlyDSL kernel too

flash_attn_func took no descales at all, so the bshd half of the a8w8 descale
support was unreachable. Add the three parameters, forward them to the FlyDSL
hook, and validate the all-or-none rule the varlen entry already enforces.

Unlike varlen, neither batched fallback consumes descales: the CK varlen path
takes q/k/v_descale, but FlashAttnFunc and the Triton batch entry do not. A
request that reached them with descales would be served unscaled, so raise
instead of returning a wrong answer. That keeps the rule that a backend either
honours an option or declines the call.

Checked through flash_attn_func: served with the right shape and dtype,
v_descale=4 scales O by exactly 4.0000, a partial set raises ValueError, and
bf16 + descale raises rather than silently dropping the scaling. fp8 16/16 and
bf16 32/32 clean, varlen route unaffected.

* FMHA gfx1250: guard the fallback, not the dispatch, for ENABLE_CK=0 descales

flash_attn_varlen_func rejected every descale call up front when ENABLE_CK=0,
before the FlyDSL hook ran. That was right when CK was the only backend that
could consume descales, but the a8w8 gfx1250 kernel now can, so a supported
fp8 request was refused for a reason that no longer applied to it.

Move the rejection to the Triton fallback it actually protects. FlyDSL gets
first refusal; only a request that falls past it, to a backend with no descale
support, raises.

With ENABLE_CK=0: fp8 + descales is now served by FlyDSL, and bf16 + descales
still raises instead of reaching Triton and being computed unscaled. With
ENABLE_CK=1 nothing changes -- varlen and batch routes and the fp8 sweep are
unaffected.

* FMHA gfx1250: test coverage for the fp8 per-tensor descales

A third sweep beside thd and bshd, with its own table. Besides the usual error
against a reference that pre-scales q*qd, k*kd and v*vd, it checks three
invariants that pin the fold itself and do not depend on fp8 noise:

  identity     descales of 1.0 reproduce the no-descale path bit for bit
  v_scale_ok   v_descale=4 scales O exactly (x4 shifts the bf16 exponent and
               leaves the mantissa, so round(4x) == 4*round(x))
  qk_fold_ok   q/k descale 2*2 against softmax_scale/4 is bitwise the baseline

Those matter because a wrong fold shows up as an error that reads like
quantisation noise; bitwise columns cannot be mistaken for it.

Descales are a8w8-only, so the sweep takes just the 8-bit dtype pairs and
self-skips when none is requested, leaving the existing two sweeps and their
--max-cases sampling untouched. --descale 0 turns it off.

64/64 rows across fp8/bf8, hdim 128 and 192/128, causal and not, batch 1 and 3,
GQA 1x and 4x: all three invariants true, err 0.

* FMHA gfx1250: bound the descale sweep with --max-cases too

The descale sweep iterated its product directly, so --max-cases bounded the
two layout sweeps but not it: a partial-axis request still paid for the whole
hdim x shape x fp8-dtype x causal product first, defeating the point of the
bound.

Split the indexed sampler out of _cases into _sample(axes, label) and route
all three sweeps through it. _cases keeps the hdim filtering that makes its
index space exact; the descale sweep passes its own four axes.

--max-cases 1 now yields one row per table and three sampling lines, and
--max-cases 0 still runs the full 64-row descale sweep, all invariants true
and err 0.
…7314)

* Bind TDM builtin groups to either signedness across LLVM builds

* Add gfx1250 MLA v4.1 a8w8 sparse prefill kernels

* Rebuild the gfx1250 MLA v4.1 code objects for the separate prefix and extend strides

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
…code. (#7347)

* [Triton] [Config] Tune gfx950 gemm_a8w8 for Llama 3.1 8B FP8 decode.

* Updated configs up to  M=256
… --full (#7318)

The default entry point swept 602 cases (1131 s on MI355X standard CI,
run 41382065915). Each case costs ~1.9 s regardless of token count, so
the time is a fixed per-case cost rather than kernel work.

Run a 46-case covering set by default: one case per kernel instantiation
the full matrix reaches (<head_size, neox, interleaved, KV dtype> for
MRoPE, <head_size, neox, KV dtype> for RoPE), with token count, head
count and return-kv rotating so every head size runs bf16 and fp8 KV with
return-kv on and off, plus the strided vLLM KV view, partial-rotary
RoPE/MRoPE and GemmaRMSNorm cases (incl. Qwen3.8-27B TP1, 24 q / 4 kv).

The previous matrix is unchanged behind --full. Sweep-axis flags
(-n/-t/-hd/-hs/-i/-k) now error out without --full instead of being
silently ignored; -d/-m apply to both, and default token counts are
clamped to --max_positions.

Signed-off-by: Vorapol Assavasangthong <[email protected]>
…il mask (#7197)

Only a sequence's last tile reads rows past its context, and the task
guard guarantees part_start < part_end, so the tile loop now runs
[part_start, part_end - 1) without the V tail mask and the task's last
tile is peeled to carry it. Single-tile plans keep the masked tile.

The runtime mask branch was also a basic-block boundary that kept the
scheduler from sinking page64/128 V loads next to their PV MFMAs; the
unmasked tiles place sched_barrier(0) there to keep the loads early.

Signed-off-by: fsx950223 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
* [FlyDSL] Tune DSv4.1 EP8 A8W4 MegaMoE

* [FlyDSL] Preserve compile-time staging in prepare lint checks

* [FlyDSL] Replace DSv4.1 final LDS inline asm with typed copy
… tune (#6692)

* [CK] [Bugfix] FMoE tuner: use all sources for shapes FlyDSL v2 cannot tune

Since #5045, TUNE_ONLY defaults to flydslv2. gen_flydsl_v2_2stages_task
only covers bf16-out per_1x32 g1u1 shapes, so with TUNE_ONLY unset every
other shape gets 0 candidates and the run fails with "no shape to tune or
no solution found".

With TUNE_ONLY unset, keep flydslv2 for shapes it has candidates for and
use all sources (as TUNE_ONLY=) for the rest. Explicit TUNE_ONLY is
unchanged.

Signed-off-by: Oliver Yu <[email protected]>

* fix(tuner): reuse FlyDSL v2 probe tasks

Signed-off-by: Oliver Yu <[email protected]>

---------

Signed-off-by: Oliver Yu <[email protected]>
…y the HIP runtime (#7185)

* [OPUS] Fall back to regular COs when A0 strict is unsupported

HIP runtimes before 7.16.26385 reject gfx1250-strict code objects, which broke A0 nodes on older ROCm (e.g. ATOM CI 7.16.26315: invalid device function). On ASIC Revision 0, preflight the strict image with hipModuleLoadData and fall back to the same symbol regular gfx1250 image when the runtime rejects it, warning once per process. Missing files and wrong ELF profiles remain hard errors, and strict stays preferred on HIP >= 7.16.26385. Validate compute/wl/wlr regular COs on A0 hardware against a CPU golden and add profile/cache regression tests.

* [OPUS] Treat gfx1250-strict as gfx1250 at the CO call

ROCr reports the strict ISA id on A0 by default while rocm_agent_enumerator still reports gfx1250 during the transition. Keep arch detection untouched (real id everywhere): only the OPUS BF16 GEMM CO call ignores the distinction. The CO loader accepts both ids for image selection and old-runtime regular fallback, and A16W16 launch planning resolves CO kids through the base gfx1250 family while non-CO kids keep the real id. Shared JIT probes, registry keys, GPU_ARCHS build targets and codegen are untouched.

* [OPUS] Name the A0 strict CO profile gfx1250-strict

The A0 images are compiled with --offload-arch=gfx1250-strict, so the profile directory, build_co default output and build metadata should use that name instead of the misleading gfx1250-a0. Rename gen_co/gfx1250-a0/ to gen_co/gfx1250-strict/, set target_profile=strict, update the CO loader, docs and tests. The loader still reads a legacy gfx1250-a0/ directory when gfx1250-strict/ is absent.
…oken conv1d update (#6925)

* [Triton] Allow a strided feature dim in conv_state for single-token conv1d update

causal_conv1d_update_single_token and
fused_reshape_causal_conv1d_update_single_token asserted
conv_state.stride(-2) == 1 when validate_data=True. The kernels read and
write conv_state through all three strides, so a (lines, dim, state_len)
cache with stride(-2) == state_len (vLLM VLLM_SSM_CONV_STATE_LAYOUT=DS)
is correct but failed the assertion. Remove the assertion, as in the vLLM
causal_conv1d_update reference, and test both layouts against a torch
reference.

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Andreas Karatzas <[email protected]>

* [Triton/Gluon] Trim the conv_state layout tests to the layouts the change affects

Keep one shape per kernel and run it with both conv_state layouts: the
feature-contiguous one that was already supported and the state-contiguous
one this change allows. Reuse ref_causal_conv1d_update_single_token instead
of a second reference. 56 parametrized cases become 4.

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Andreas Karatzas <[email protected]>

---------

Signed-off-by: Andreas Karatzas <[email protected]>
Co-authored-by: Claude <[email protected]>
…5938)

* fix(jit): keep detached-head advice local to third-party clone

Signed-off-by: Xucheng Zhou <[email protected]>

* test(jit): document trusted function execution for CPU coverage

Signed-off-by: Xucheng Zhou <[email protected]>

---------

Signed-off-by: Xucheng Zhou <[email protected]>
…rix to perf mode (#7331)

The standard CI command runs this file with no arguments, so the complete
Wan2.1/Qwen-Image performance matrix ran inside a shard: 109 benchmarked rows,
each timing both torch and FlyDSL through 101 profiled iterations. On the
Aiter Test run for 09b616c this one file took 603.193 s.

Leave the shared runner, sharding and timing aggregation untouched and split
the behaviour at this file's own entry point instead. With no arguments the
script now runs a correctness-only suite: the six Wan families that cover the
distinct kernel paths (conv_in at the real 368x544, so the exact production
tuned row and the compile parameter it selects are both verified, the other
five at 64x64), six keyword regressions for the reuse, gating and split-K
paths, and the unfiltered compile-key isolation and static-extent checks. Each
row does two warmups and ten directly checked calls, keeping the existing
rtol=atol=2e-2 bar with zero mismatched elements and an explicit finiteness
check. There is no profiler, no run_perftest and no torch performance baseline,
so no throughput columns are reported for these rows.

--mode perf keeps the previous matrix, resolutions, tables and statistics
unchanged; the new manual workflow dispatches exactly that command.

Add a manual-only MI35X workflow for the full sweep: it resolves the requested
physical GPU through ROCm SMI unique ID and PCI address, refuses anything but
gfx950, requires 30 s of idle time before starting, monitors for external
processes and stops only its own container. Its logs are a separate artifact
and never feed the standard timing table.

Add pure-CPU regression tests for the argument/mode split, the direct-call
runner and the host split-K and reuse plans; they import no torch, aiter or
FlyDSL and need no GPU.

Test plan:
- python tests/test_conv3d_ci_modes.py (19 tests, stdlib unittest only)
- black --check and ruff check on both Python files
- YAML, Bash and embedded-Python syntax validation of the new workflow
- python op_tests/test_flydsl_conv_implicit.py --help, confirming argument
  parsing happens before any backend import

Measured wall-time comparison of the old and new default entry point on an idle
gfx950 card is still pending; this commit makes no speedup claim.
zhiding512 and others added 28 commits November 4, 2026 11:46
…for E=384 decode (#7359)

#5987 made gfx950 dispatch_policy=0 (auto) pick the multi-phase Opus MoE
sort for E>=385 at every token count, and for E>=256 from 8 tokens;
#7134 added E>=128 from 17 tokens. E=384 falls one expert below the
all-M bound, so it stays on the one-shot sort at M<8.
E=384 is DeepSeek-V4-Pro's routed-expert count (top-6) when the shared
expert is not fused into the routed MoE.

In a gfx950 diagnostic with E=384, top-6 and block_m 32 under CUDA-graph
timing, the forced multi-phase sort (dispatch_policy=2) is faster than
the one-shot sort that auto selects at M=1, 2, 4 and 7; at M=8 auto is
already multi-phase. Valid-region outputs were identical. To measure it,
run op_tests/test_moe_sorting.py -e 384 -t 6 -dp 0 1 2 at those token
counts.

Lower the expert bound from 385 to 384. Only gfx950 auto dispatch at
E=384 with M<8 changes; forced policies, other architectures and every
other (E, M) keep their current kernel.

Tests: E=384 now expects multi-phase at every listed token count in the
host boundary test, a new E=383 row keeps the E=256/257 expectations to
pin the new lower side, the non-gfx950 branch asserts E=384 stays
one-shot, and (1, 384, 6) is added to the auxiliary-output and local-ID
tests that check newly multi-phase auto routes.

Signed-off-by: Yaakoub El Khamra <[email protected]>
Co-authored-by: Yaakoub El Khamra <[email protected]>
* [MLA] test_mla_v4_nm: make the script perf sweep opt-in

Running `python3 op_tests/test_mla_v4_nm.py` with no arguments (how
aiter_test.sh runs op_tests) launched the full perf sweep: 10 batches x
6 kv lengths, each timing ref / asm kernel / asm total for 50 iters.
That took ~2000 s in CI against an ~870 s timing estimate.

The sweep now runs only with --full-sweep, or with an explicit
-b / -c / -q to sweep a subset. With no arguments the script prints a
skip notice and exits 0. The gfx950 guard, the --oob-worker subprocess
paths used by the pytest OOB tests, the sweep defaults, and every
pytest test are unchanged.

* [CI] aiter_test.sh: run test_mla_v4_nm.py through pytest

With the perf sweep opt-in, `python3 op_tests/test_mla_v4_nm.py` exits 0
without running anything, and the file's smoke / determinism / kernarg /
OOB suite only runs under pytest. Add the file to a pytest dispatch
branch so standard CI executes those 50 cases instead of reporting an
empty run as success.
…s them (#7418)

With per-request qo lengths (uni_seqlen_qo -1) and more than one qo tile per
request, mla_v12_compute_sum_blocks asks mla_v12_num_qo_tiles for a batch's
tile count, which reads the batch's qo length from LDS, before it stores that
length there. kn_get_mla_metadata_v1_2 then sizes its per-CU budget from
whatever the previous kernel left in LDS. Identical calls (128 heads, qlen 3,
one request of 10k KV tokens) planned 0, 177, 243 or 256 works, so some plans
were empty or left qo tiles out, and others were stable but barely split
(96 heads, four requests of qlen 1-5: 13 works with every tile whole, 199 once
the length is stored first).

The order dates from #1626, which multiplied each batch's blocks by its qo
tile count; before that the sum did not depend on the qo length, so storing it
after the sum was harmless.

Store it first. Each lane reads back only the batch it stored, so no barrier is
needed. The parallel planner (one tile per request) and the XCD planner
(uni_seqlen_qo only) do not read it there.

test_metadata.py gains test_varlen_qo_matches_uniform: 96 and 128 heads, fp8
and bf16, qlen 3, 5 or 6, with and without cp round robin. A batch whose qo
lengths are all equal must get the same plan with uni_seqlen_qo -1 as with
uni_seqlen_qo = qlen. Without the fix all 96 shapes differ.

Co-authored-by: Cursor <[email protected]>
…mily (#7379)

GPU_ARCHS=gfx1250-strict matched zero FlyDSL tuned rows and printed
"All compilations succeeded" -- a silent empty wheel -- because the AOT job
filters compared the tuned-row arch (gfx1250) against the exact requested
target (gfx1250-strict) and dropped everything. chunk_gdn_h ignored GPU_ARCHS
entirely and compiled gfx942 kernels while labelling the run strict.

gfx1250-strict (MI450 A0) and gfx1250 (B0) are one source/kernel family, so a
gfx1250-tuned row should serve a gfx1250-strict build and be compiled for the
exact strict target (ELF mach 0xeb, not gfx1250 0x49). Add
common.resolve_target_arch (family-match + retarget to the exact requested
arch) and common.assert_targets_covered (fail loud when a family present in the
tuned data produces no job). Every AOT entry now honors GPU_ARCHS for strict:

- gemm.py / conv.py: keep family-matching rows, retarget the compile.
- chunk_gdn_h.py: honor GPU_ARCHS (previously unfiltered -> gfx942), retarget.
- moe.py: family-match + retarget in both the orchestrator and the per-arch
  replay worker; the GateMode/quant gfx1250 checks become family-aware.
- mega_moe.py / fmha_fp8.py / mxfp4_moe.py are gfx950-only; they now skip a
  strict build instead of emitting gfx950 kernels into it (mega_moe already
  did; fmha_fp8 and mxfp4_moe gained the same GPU_ARCHS guard).

FlyDSL compiles the strict target as of flydsl 0.4.2.dev1008 (bare gfx1250 to
MLIR Chipset::parse, full gfx1250-strict to LLVM codegen), landing in the
0.4.2 release; the pin bump is tracked separately. Verified on real MI450 A0: a
gfx1250 row compiled for gfx1250-strict yields an artifact with rocdl
chip=gfx1250-strict and ELF e_flags 0x4eb (mach 0xeb).

Co-authored-by: zufayu <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…ted preshuffle kernels (#7317)

* feat(gemm): tune narrow-N MXFP4 with CSV-selected preshuffle backends

* fix(gemm): address preshuffle tuning review feedback
…n count (#7294)

* [FlyDSL][MoE] gemm2: bound atomic rows by the sort's valid token count

With num_local_tokens, moe_sorting fills each expert block with the pad
sentinel MOE_SORTING_MOCK_ID(tokens, topk), whose token id is the REAL token
count. When the caller's M is padded (cudagraph), that id is still < M, so
the a16w4 and mxfp4 atomic gemm2 epilogs (bounded by token_id < M) scatter
every pad slot into row `tokens`.

Add use_valid_token_count to both kernels: rows are bounded by
min(cumsum[1], M), as the v2 dispatcher already does. fused_moe_2stages
enables it whenever num_local_tokens is passed. Off by default; the compiled
kernels are unchanged when it is off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [CI] Shard and run gemm2 valid-token-count test under pytest

op_tests/flydsl_tests/ is outside split_tests.sh discovery, and the file has
no __main__, so add it to the explicit list and the pytest branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: ganyi <[email protected]>
* [FlyDSL] Add skinny A16W16 policy for GLM-5.2 o_proj decode on gfx950

New "sk" HGEMM policy: one workgroup per N slab with the full K, fp32
partials reduced in LDS, no split-K scratch. Retune ten N=6144 K=2048
rows (M <= 32) to it: 1.08-1.27x per call on MI355X.

* [FlyDSL] Preload A16W16 kernargs; skinny rows for GLM-5.2 qkv_a_proj M <= 8

Enable kernarg preload in gemm_a16w16_gfx950 (1.017x geomean over 363
tuned rows). Retune qkv_a_proj (N=2624 K=6144) M=1/2/4/6/8 rows to the
skinny policy: 1.07-1.21x per call.

* fix(flydsl): base the skinny B descriptor at the workgroup slab

The DMA voffset is a single 32-bit VGPR and the offset is cast to a
signed i32, so a tensor-based descriptor wraps once n0 * k * 2 passes
2 GiB and the load reads whatever is mapped there. Fold n0 into the
64-bit base, make the voffset slab-relative, and bound the descriptor
with num_records so an offset bug returns zeros instead of faulting.

Also reject host tensors up front -- the launch hands the kernel raw
pointers, so a CPU a/b/out was a GPU memory fault, not a Python error.

* refactor(flydsl): move the skinny kernel onto the typed fx API

Raw arith/scf/index plumbing becomes fx values and plain Python control
flow: constant_vector -> fx.Vector.filled, index_cast -> fx.Int32/Int64,
truncf -> .to(), cmpi + scf.IfOp -> if. The three raw boundaries that stay
-- the DMA inline asm, the mfma intrinsic and the LDS buffer_ops addressing
-- are the hand-scheduled parts that have no builder form, and the module
docstring now says so. .ir_value() appears only where one of them needs an
unwrapped operand.

No functional change: 48 benchmark rows reproduce with err 0, the 7 policy
rejects and the 2 GiB weight case still pass.

---------

Co-authored-by: Yutao Xu <[email protected]>
* Add gfx950 Q256 fused MXFP4 prefill pipeline

Integrate the universal assembly producer and supplied Triton route reducer through AITER with guarded dispatch and an opt-in configuration. Preserve the public fused_moe API and reuse the Opus inverse route map.

Validated on gfx950 at 8k, 16k, and 32k tokens with 512 routed experts plus a shared expert, including graph replay, independent producer launch checks, and comparison with the FlyDSL pipeline.

* Use compact hybrid Q256 contributions with shared FlyDSL reduction

* Fix Ruff and Black checks for compact Q256 integration

* Fix Q256 scheduling at shifted shared-expert boundaries

* Use weighted M128 scheduling for Qwen Q256 prefill

Install the matching weighted M128 producer and GPU routing planner from the 2026-10-16 PyISA package. Pass its 1024-entry map at ABI offset 128 and select it directly for compact Qwen 8K geometry, retaining the shared FlyDSL reducer.

Validated on SMCI355 gfx950 PCI 0000:05:00.0: exact compact/sorted contributions; reference NRMS 0.00273150; graph/eager, prequantized and caller-output parity; weighted/map profile confirmed. Full-API graph median 1156.51 us (7 x 50 replays). CPU contracts and ABI assertions passed.

* Select weighted Q256 producer explicitly from config

Name the weighted producer in the validated Qwen 8K/D8192 CSV row and carry kernelName through Q256 dispatch. Retain compact producer selection for the other rows and reject unsupported weighted geometry. Record the selected kernel in the existing integration test.

SMCI355 gfx950 PCI 0000:15:00.0: exact compact/sorted contributions, reference NRMS 0.00273150, graph/eager/prequantized/output parity, and all 20 config collision checks passed. Full-API median 1125.49 us. Kernel trace evidence incomplete: PyTorch trace had no kernel events; rocprof capture blocked by competing KFD process.

* Constrain Q256 scheduler to production ABI and add coverage

Preserve the M128 production map while removing unused scheduling options. Add a category wrapper, trace representation, independent CPU/GPU tests and a preallocated-output benchmark.

Validated on gfx950: 7 tests and 55 subtests pass; all 12 benchmark cases match the independent oracle.

* Fix Q256 dispatch boundaries and recover shared-route prefill performance

Move scratch allocation and producer/reducer orchestration below shared MoE dispatch. Keep semantic guards in Python, validate tensor contracts in the CU launcher, and remove the unused sorted-output path.

Consolidate model configurations and replace the broken standalone harness with shared-expert, random-control, boundary, graph replay and independent-reference coverage. Retain explicit weighted selection and limit streaming reduction to the exact 8K Qwen shape.

Validated on gfx950 with FlyDSL 0.4.0: six shared shapes, random control, five token boundaries and 26 config checks pass. Captured routes with synthetic activations and weights improve full-API latency by 7.84%, 6.35% and 5.40% versus main across seven rounds of 50 graph replays.

* Remove internal Q256 notes and unused sorted-output code object

Retain only the compact and weighted producers selected by the current launcher.

* Simplify Q256 tests and restore the generic MoE harness

Restore the existing single-candidate timing and sweep behavior. Consolidate Q256 case setup, expected-error checks and scheduler GPU fixtures while retaining shared/random routing, token boundaries, graph replay, producer selection and independent numerical checks.

Validated on gfx950: all 12 Q256 cases, 7 scheduler tests and 55 subtests, and the normal CLI startup pass. Full configured Ruff 0.16.0 and Black checks pass without new suppressions.

* Enforce Q256 sorting layout and preserve automatic dispatch fallback

Validate the effective block_size_M before sorting. Discard incompatible automatic Q256 configurations before backend selection, while retaining rejection for incompatible dedicated configurations and preserving prequantized A1 support.

Honor FP8 intermediates in the two-stage fallback. Add unmocked public-dispatch regressions for incompatible block overrides, FP8 intermediates and supplied A2 scales, including profiler and independent-reference checks.

Validated on gfx950: all 12 existing Q256 cases, both override-before-sort checks, both two-stage fallback checks and four CLI startup regressions pass. Full Ruff 0.16.0 and Black checks pass.

* Potential fix for pull request finding 'Reject interleaved weights before selecting Q256'

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Require shuffled Q256 projections and restore MoE test device state

Use the normalized both-projection shuffle flag for Q256 eligibility while preserving the interleaving guard and legacy metadata fallback. Cover either missing projection tag through real two-stage dispatch.

Scope GPU test entry points so they restore the caller default device on success and exceptions without changing benchmark argument logging.

Validated on gfx950 with fresh native caches: all 12 Q256 cases, four fallback cases and device-state regressions pass. Full Ruff 0.16.0 and Black checks pass.

* Preserve default FlyDSL MoE reduction load constructors

Keep the original no-argument BufferCopy64b and BufferCopy128b constructors when streaming is disabled. Apply the explicit non-temporal policy only to the streaming variant.

Validated on gfx950 with the existing FP8 masked-reduction test and the configured MoE shape sweep.

* Move Q256 scheduler fixtures into test utilities

Share the independent CPU inputs and oracle through test utilities instead of importing a test module from the benchmark. Remove the unittest script entry point and keep pytest coverage unchanged.

Validated on gfx950: all 7 tests and 55 subtests pass, and the benchmark matches the oracle for both selected cases.

* Simplify Q256 launcher plumbing and complete script-driven coverage

Remove unused reverse-sort forwarding and native validation while retaining the shared sorting contract and producer argument layout. Clarify output allocation and separate compact constraints from weighted geometry.

Reuse the kernel-name constant and run random-route and device-state checks from the script entry point. Keep the existing model-table selection, configuration override and scale handling.

Validated the actual gfx950 script entry with six shared shapes, random routing, five boundaries and four real fallbacks. The producer argument block remains 448 bytes and the code objects are unchanged. Ruff and Black pass; the exact MI300X linear-attention comparison remains pending access to its failure log.

* Rename Q256 fused experts and align assembly kernel names

Replace the producer entry point with fmoe_q256_fused_experts and use a new JIT module namespace. Align compact and weighted ELF exports, metadata, code-object filenames and model selectors with the fmoe naming family.

Keep the existing selector spellings as compatibility aliases for AITER_CONFIG_FMOE overrides. Update tests and diagnostics to use the fused-expert names.

Both code objects preserve their exact machine-code bytes, 448-byte kernel arguments and resource settings. Verified canonical HIP lookups, fresh native exports, all 12 Q256 cases, four fallback cases and both legacy selectors on gfx950. Ruff and Black pass; unrelated SwiGLU startup comparison warnings reproduce on the pre-rename head.

* Use standard FMoE launcher and drop weighted Q256 scheduling

Launch the self-contained compact producer through the existing assembly manifest and reduce token/top-k partials with FlyDSL. Remove the Triton job-map planner, custom Q256 launcher, weighted code object and pre-merge selector aliases.

The in-kernel scheduler matched all 81,920 diagnostic slots but was 6.16% slower than compact on the exact 8K shared-expert shape. Final gfx950 correctness passed six configured shapes, random routes and token boundaries; maximum NRMS was 0.00017653. Config collision, Ruff and Black checks passed.

* Limit Q256 config changes and inline kernel selection

Restore the existing Qwen CSV schema and unrelated rows so its PR diff contains only the three prefill selections. Compare the canonical kernel name directly in fused_moe and remove the separate moe_op helper.

Config collision guard passes all 30 tests; Ruff, Black and syntax checks pass.

* Compute Q256 weighted schedules inside assembly

Rebuild the weighted producer with wave-local key exchanges, one cross-wave LDS exchange and four register-cached jobs shared by dispatch and prefetch. The standard FMoE launcher passes no job map, and the kernel never reads the smoothing-scale pointer.

Select weighted M128 scheduling for qualifying routed boundaries 576 through 960; retain the compact M32/M64 path for smaller layouts, invalid suffixes and over-capacity schedules. Keep direct dispatch checks and the three-row CSV diff.

Validated 113 policy cases and 115712 slots with zero mismatches, production Q256 integration and forced larger-token fallback. Captured routes 029/046/049 improve 6.6-9.5% against compact and 3.1-7.2% against FlyDSL. The matched-allocation timing follow-up remains blocked by GPU availability.

* Store weighted Q256 code object without executable permissions

* Clarify ASM route-partial dispatch and populate tuned timings

Adapt the PR style patch to both compact and assembly-weighted producers. Select the partial-output branch before the generic G1U1 branch, enforce its tile size locally, and simplify equivalent FlyDSL copy constructors.

Populate the six existing prefill rows from validated timing receipts without changing CSV schemas or unrelated rows. Retain tested eligibility, FP8 fallback, reference and import-safe test contracts.

Validated 30 config collision tests, 22 old/new host-call cases, eight installed FlyDSL copy-type comparisons, Ruff and Black. Assembly code objects are unchanged.

* Select ASM post-reduction through manifest mode 3

Use the flat column to distinguish sorted, no_sort, emsort and sorted post-reduction producers. Replace kernel-name classification with mode checks, preserve host sorting and standard launch geometry for mode 3, and update model and assembly manifests.

Keep post-reduction entries out of the direct-output tuner and account for sorting according to mode. Cover all four sorting/output modes with CPU tests.

Validated 30 config tests, both CPU mode tests, 12 Q256 integration/profile checks, four emsort rows and ten no-sort rows on gfx950. Assembly code objects are unchanged.

* Use named ASM MoE modes and canonical sorting semantics

Define AsmMoeMode with the existing CSV values and a requires_host_sort property. Normalize numeric modes at dispatch boundaries, derive tuner mode groups from the enum, and use matching named constants in the C++ launcher.

Preserve numeric CSV serialization and legacy boolean inputs. Three CPU mode tests, 30 config tests, codegen contracts, Ruff, Black and fresh standard ASM compilation pass. GPU revalidation was blocked by device activity; assembly code objects are unchanged.

* Remove Q256 test scaffolding and use ordinary route sorting

Return the op test to its normal CSV sweep with only post-reduction row selection and settings. Remove producer mocks, profiler assertions, model-specific suites and pytest-only mode tests.

Use the standard 256-row Opus sort without auxiliary indices, remove the one-stage atomic detour and has_a2_scale plumbing, and retain only weight-layout eligibility. Zero partials when filtering can leave route slots unwritten.

Validated all six configured shapes through the real script, exact captured-route outputs, local-token graph replay and masked local-expert mapping. Captured routes improve 8.61%, 5.88% and 5.40% versus FlyDSL; config, Ruff and Black checks pass.

* Skip output zero-fill for ASM post-reduction

Give the sort an empty buffer and let the reducer overwrite the final output, including masked rows. Revert the unrelated FP8 fallback changes.

* Tune ASM post-reduction producer and reducer together

Include POST_REDUCE candidates with shuffled MXFP4 inputs and report their combined cost as us1 without an extra intermediate quantization charge. Reset merged candidate indices so winner selection emits one valid CSV row.

* Format POST_REDUCE tuner conditionals

* Refresh ASM post-reduction tuning timings

Use measured producer-plus-reducer costs for each configured kernel and explicitly record zero stage-two cost. Keep the weighted 8K row matched to its own measurement.

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
* add qsa attention support

* relax kvcache 4G restrictions to single request(TP1 4M  tokens, TP2/4/8 8M tokens)

* apply review comments

* revert non-exist nan case

* simplify attention_prepare interface

* qsa union: use SALU for DMA addresses, effective target-features, RNE P pack
- set -packed-fp32-ops via llvm.target_features; passthrough was dropped
- compute K/V DMA rows on the SALU, removing VALU address math in stage A
- _pack_bf16: one v_perm_b32 per pair (5 instructions instead of 6)
- P uses _pack_bf16 (RNE) like O

* qsa: drop most inline asm, unroll the union phase loop by two

- _maximum, _center_one, _cross, LDS writes, the mask prefetch and the union
  K/V DMA use fx/rocdl ops instead of inline asm
- pin the centered scores so LLVM keeps their FMAs inside the stage
- unroll the union phase loop by two: the running max alternates registers,
  so no copy lands in a memory stage and _advance_max goes away
- _read_address stays asm (reasons in its comment); outputs are bitwise identical
- union: H12 unchanged, H6/H3 up to +0.5%/+0.9%

* qsa: split the union K/V LDS, read LDS with LLVM loads, drop ds_read asm

- split the union's 64 KB LDS into K and V variables: the module LDS
  lowering gives each its own alias scope, so a read no longer waits on
  in-flight DMAs into the other buffer
- read K/V and the O tiles with volatile LLVM loads through the LDS
  variables (_load_lds); volatile keeps the hand-written read/DMA order.
  _read_address and its inline asm are gone
- _keep_vgpr: an empty asm that only reads the loaded words keeps them in
  VGPRs (MFMA-only uses leave them AV-class and the scheduler reverts the
  QK interleave) without the s_nop a tied pin's def costs
- sched_barrier(0) after both cross() calls, so the ds_bpermutes issue
  before the reads that the hand-written lgkmcnt counts
- the shared _output (union and both direct kernels) takes the LDS
  variables; the V half's +32768 folds into the ds_read offset
- V DMA offsets are relative to the V buffer; for HK > 1, packets 1-3
  put the step in VOFFSET as K already does
- outputs bitwise identical; vs HEAD: prefill 0.1-1.2% faster (4096
  0.6-0.9%; 12000 H12/H6/H3 0.3/0.7/0.9%; 32768 H3 1.0-1.2%, H12 0.1%),
  chunk_1024 unchanged; the union phase loop takes 1.2-1.4% fewer cycles

* qsa union: restructure the pipeline body

* use float MAX_FLOOR instead of hard code -1e30

* fix ci checks

* apply review comments

* apply review comments: 1, check scaled range 2, avoid not release non-cached workspace 3, wait stream before execution new kernel

* use fx.generic_load for LDS reads, centralize target features, trim pins

* rename prefill attention to sparse_prefill, add aiter.ops.qsa entry

* qsa sparse prefill: kv_slots, 1M-token contexts, >4 GiB coverage

- kv_slots: read K/V in place from a paged token pool (four-token blocks
  on four rows starting at a multiple of 4; table <= 4 GiB - 1 MiB).
- K2 builds unions in LDS, so 1M-token contexts need no dense scratch;
  K3 maps pool blocks and lists the raw direct groups to run.
- Direct packs only while PK/PV fit 32-bit offsets.
- Op test: >4 GiB packed K/V, per-request limit, kv_slots pools,
  over-limit rejection, skips on low free memory.
…e interconnects (#5461)

* Land INT4 quad-fanout QR in aiter FlyDSL ops with a TP8 correctness test.

* Use layout views for LDS pack and ST inbox without regressing ST=8 wall.

Drop unused wave-join and single-wave fanout compiles; default and test the fp16 codec.

* Stop QR INT4 tests and host from mutating COMPILE_ONLY.

Compile-only and cache warming belong in developer scripts, not pytest or QRInt4QuadFanout.compile.

Co-authored-by: Cursor <[email protected]>

* Model local HBM payload as FlyDSL views; keep remote NT stores explicit.

inttoptr + make_buffer_tensor (nbytes OOB) and BufferCopy128b tiled copies replace the tile/atom/tid arithmetic for local dwordx4 loads and stores. IPC/XGMI fanout stays global_store_dwordx4 nt.

* New QR kernel/host/test files should use aiter MIT + AMD 2026 only; they were not FlyDSL-main originals.

* Drop the quad_fanout variant suffix from the only INT4 QuickReduce pipeline so the public API is QRInt4.

* Default QRInt4 to ST=8 and keep only ST∈{1,8} so the host matches the measured keeper; drop unused codec/force_super/bf16 ALU and qr_int4_mem, compiling via flyc.compile.

Co-authored-by: Cursor <[email protected]>

* Skip color 0 after wrap so it never matches the unset sentinel (HIP QR does the same), and time QRInt4 with run_perftest.

* Compile QRInt4 WORLD∈{2,4,8} via HIP-style kRankAtoms so TP4/TP2 work; WORLD=8 stays kRankAtoms=1.

Co-authored-by: Cursor <[email protected]>

* IPC helper is a FlyDSL copy so keep Apache-2.0 copyright 2025; match aiter vendored dual header.

Co-authored-by: Cursor <[email protected]>

* Replace QR INT4 packed-math inline asm with native FlyDSL f16x2 ops.

gfx942 already lowers vector<2xf16> to v_pk_max/min/mul/add/fma, so the
llvm.inline_asm helpers and f32 absmax round-trip are unnecessary.

* Spell out QR INT4 RS/AG and lower the flag wait as a Python while.

The two-shot NT fanout and last-sector handshake are unchanged; gfx942 SQNR vs fp32 all-reduce still passes at TP 2/4/8.

Co-authored-by: Cursor <[email protected]>

* Reduce torch surface in qrint4 kernel

* Join ST sub-tiles before LDS reuse and tighten QRInt4 host checks.

TP2 ST=8 was packing the next tile into LDS while wave 0 still loaded the previous one. Also match aiter FlyDSL dtype/device checks and stop sorting IPC group ranks.

Co-authored-by: Cursor <[email protected]>

* Assert QRInt4 SQNR on every rank.

Each rank already scored vs its local fp32 NCCL all-reduce. The parent
kept rank 0 only, so a broken all-gather on a non-zero rank could pass.

Co-authored-by: Cursor <[email protected]>

* Apply suggestions from ruff

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Match black wrapping and apply small Copilot host/test guards.

Fail SQNR on NaN or a zero-power reference with error. Drop the NCCL
fallback for Gloo object gather. Reject a rank or world_size that does
not match the process group.

Co-authored-by: Cursor <[email protected]>

* Enable gfx950 FlyDSL QRInt4 with configurable grid cap.

Extend arch support to gfx950, parameterize inbox/launch grid_cap (default
1216 to match HIP QR), and tighten the canonical test bench with --grid-cap
and optional JSON export.

Co-authored-by: Cursor <[email protected]>

* Run black on qr_int4_kernel.py after merging main.

* Reject NCCL and multi-node groups in QRInt4 with explicit errors.

IPC inbox setup needs CPU broadcast_object_list and node-local HIP IPC
handles. Fail fast before allocating buffers, matching QuickAllReduce.

* Shorten QRInt4 process-group rejection messages.

Co-authored-by: Cursor <[email protected]>

* Fix QR INT4 launch safety and validation

Clamp persistent grids to conservative residency limits, harden resource cleanup, and validate lossy collective results across ranks.

Co-authored-by: Cursor <[email protected]>

* Address QR INT4 review feedback

Co-authored-by: samremes <[email protected]>

* Apply Black formatting after merging origin/main.

Fix CI Black failures in qr_int4_kernel.py and test_flydsl_qr_int4.py.

Co-authored-by: Cursor <[email protected]>

* Fix QR INT4 E4M3 boundary encoding

* Reject >32bit offset

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Add automatic QRInt4 cleanup

* Avoid QRInt4 AOT import cycle

* Harden QRInt4 validation and test collection

* Fix QR INT4 E4M3 reserved-zero underflow after exponent clamp.

Reserve byte 0x00 for true +0 only after packing so clamped positive scales cannot collapse, and add TP2 fill cases for underflow, overflow, and zero.

Co-authored-by: Cursor <[email protected]>

* Drop duplicate QRInt4 lazy-import key after merging main.

Co-authored-by: Cursor <[email protected]>

* Spawn QRInt4 test ranks instead of re-entering the file with --rank.

Match HIP QR: Pool + spawn, return row dicts, keep argparse on main() only. Drop PYTHONPATH/arch env overrides and out.zero_(); time spawn workers with cuda.Event.

Co-authored-by: Cursor <[email protected]>

* Make QRInt4 test comments self-contained.

State what each threshold, fill, and CLI flag does today, and record why the
spawn ranks must time with cuda events instead of the profiler timer.

Co-authored-by: Cursor <[email protected]>

* Resolve the QRInt4 device index before set_device.

torch.cuda.set_device rejects torch.device("cuda") without an index, so the
current-device fallback in _cuda_index was unreachable. Resolve the index
first, select that integer, and keep self.device as the resolved cuda:N.

Co-authored-by: Cursor <[email protected]>

* Rename FlyDSL QR INT4 to QuickAllReduceInt4 and drop leftover globals/asm.

Move host and IPC out of kernels/, export QuickAllReduceInt4 only, and keep
module constants that actually couple host tile math, LDS, and codec layout.
Use fx.min, llvm.StoreOp(nontemporal=True) for NT fanout, llvm.amdgcn.s.setreg
for FP16_OVFL, and inline readfirstlane at the inbox descriptor.

Leave buffer_inv sc1 as inline asm: the flag poll is a non-atomic sc1
buffer_load (L2 bypass, not L1), so the miss path still needs an L1
invalidate, and llvm.amdgcn.buffer.wbinvl1.sc cannot select on gfx942/gfx950.

* Format QuickAllReduceInt4 host and tests with ruff and black.

* Move FlyDSL QR INT4 tests to multigpu_tests and fix HIP alloc rounding.

Collect the suite with the 8-GPU job instead of single-GPU op_tests.
Round uncached HIP mallocs to 4 KiB so small grid_cap inboxes still
export, and feed MODE setreg through as_ir_value instead of fx.arith.

* [FlyDSL] Extract quick-allreduce transport and codec into shared modules

The ring and one-shot schedules that follow need the same tile geometry,
inbox cache policy, peer store/load primitives and wire codec that the
mesh kernel had inlined. Split them out so all three agree byte for byte
rather than carrying three copies of the same magic numbers:

  quick_allreduce_shared  geometry, _INBOX_POLICY, peer store/load, LDS
  quick_allreduce_codec   INT4/INT6/FP16 wire formats and the E4M3 scale

The mesh kernel becomes codec- and inbox-policy-generic as a result, and
is renamed to match its new module. Two behavioural changes ride along.

Fix the buffer cache-modifier encoding. These are LLVM CPol bits, which
the backend renames for CDNA: bit 0 (GLC) prints as `sc0`, bit 1 (SLC) as
`nt`, bit 4 (SCC) as `sc1`; bit 2 exists in the encoding but CDNA has no
use for it and it emits nothing. The previous values were 4 for "NT" and
2 for "sc1", so the payload load carried no cache hint at all and the
flag spin load got `nt` instead of bypassing L2 -- a spin that can be
answered from a stale line. They are now 2 and `sc0 | sc1`.

Make the flag spin load bypass L1 as well. `sc1` alone only bypasses L2;
`sc0 sc1` is what LLVM emits for a system-scope load and is what lets the
retry loop run without a fence in its body.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Add inbox memory modes, codec selection and an ST ladder to the host

The uncached IPC inbox the host has always allocated is right on xGMI and
catastrophic on PCIe: peer writes into uncached memory serialize per
destination, so throughput collapses as the fanout widens (MI350P, INT4
mesh: 55 GB/s to one peer, 4.45 to two, 1.44 to three, against 33.5
fine-grained). Give the host an `inbox_memory` knob over the kernel's
existing cache-policy table, defaulting to "auto", which reads the real
per-peer link type out of KFD rather than guessing from the arch string
-- MI350X and MI350P both report gfx950 and want opposite answers.

With a cacheable inbox a publish costs an L2 writeback, so the super-tile
that was a fixed constructor argument becomes a payload-size ladder:
`_pick_st` selects a rung, `_grid_x` hands each block a whole super-tile
so the batching is real, and `_MIN_BATCH_BLOCKS` stops it trading the
whole machine away at small sizes (MI350P, 32x7168, TP4: 61.95 us
unbounded against 23.98 with the grid left alone).

Also adds `rs_codec`/`ag_codec` with an AITER_ALL_REDUCE_CODEC override,
`min_bytes` gating with `is_beneficial`, `variant()` for reporting which
binary a size actually runs, and `has_xgmi_peer_links` for the dispatcher.

The IPC heap grows a device check on every allocation. Several
byte-identical copies of libamdhip64 are typically mapped into one
process and they do not share device state, so the first one resolved by
soname can allocate on the wrong GPU -- every peer write then crosses to
the wrong device. Pick the mapped copy that reports torch's bound device,
and assert the allocation landed where it was meant to.

The page rounding hipIpcGetMemHandle needs moves from alloc_uncached to
alloc, which is where the inbox is now allocated from.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Add the ring schedule for quick-allreduce

The mesh writes to every one of the N-1 peers on both laps. On a PCIe
host a GPU has one shared x16 uplink, so those interleaved destinations
contend for it; the ring instead makes every step a single contiguous run
into exactly one peer's inbox. Same wire volume -- 2(N-1)/N of the
payload, which is bandwidth optimal (Patarasuk & Yuan, JPDC 69(2), 2009)
-- traded for per-destination locality, over 2(N-1) hops instead of two.

The ring pays for that in accuracy: its reduce-scatter lap requantizes
the running partial N-1 times where the mesh requantizes once, and the
partial's extremum grows with the contributions folded in. Hence the
per-lap codec knobs -- the reduce-scatter lap widens to INT6 at TP8 to
hold the 18 dB SQNR floor, while the all-gather lap forwards received
bytes untouched and stays INT4.

Registered as algorithm="ring" alongside the mesh, with its own
super-tile set (1, 8, 16, 32) and payload-size ladder. It is not the
default and is structurally worse at decode sizes and on xGMI; the
dispatcher that follows picks between them.

clamp_grid_cap now falls back to the smallest measurement for a world
size when a super-tile is not in the residency table, instead of raising:
the table was measured on the mesh and does not cover ST=16 or ST=32.
Under-launching a persistent kernel is always safe, so the fallback errs
small; an unknown arch or world size still raises.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Add the exact one-shot all-reduce and the schedule policy table

Both quantized schedules are two-shot, so their latency floor is two
serialized fabric traversals plus a grid-wide handshake between the laps.
At decode sizes that floor dominates and the quantization buys nothing --
the collective is not the bottleneck there, and INT4 charges ~36 dB of
SQNR for microseconds.

OneShotAllReduce is the decode-regime answer: one round, no grid-wide
barrier, bf16 in, fp32 accumulate, bf16 out, no codec. Each rank pushes
its whole tile into every peer's inbox, publishes a colour flag, waits
for N flags, then reduces N copies out of its own inbox. That trades wire
volume for round trips -- (N-1)*S pushed against a two-shot's 2(N-1)/N*S
-- so where it stops paying is a function of N, which is what max_bytes
gates on. It needs no LDS: thread t's 16 B lands at the same offset in
every destination, so it pushes straight from registers.

It reuses the IPC inbox, peer table and cache-policy table from the
quantized schedules verbatim, which is what the shared transport module
was extracted for.

allreduce_policy holds the size boundaries between the three families,
per (link, world_size), fitted from measurement. It is a pure table plus
env overrides -- no kernels, no torch -- so the dispatcher and the hosts
can both read it without an import cycle. Accuracy defaults to "exact",
which makes the quantized families unreachable until a caller opts in
with AITER_FLY_AR_ACCURACY=fast.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Dispatch the FlyDSL all-reduce family from CudaCommunicator

FlyDSLAllReduce owns one engine per reachable schedule and routes a
payload to the family allreduce_policy picks for its size, link type and
world size. CudaCommunicator consults it ahead of quick-reduce and custom
all-reduce.

It leads the chain because, at the default AITER_FLY_AR_ACCURACY=exact,
the only reachable family is the exact one-shot -- fp32 accumulate, one
bf16 rounding, comparable with cross_device_reduce rather than quantized
-- and it declines every payload above that ceiling, so the caller falls
through unchanged. AITER_FLY_AR_ACCURACY=fast unlocks the quantized
mesh/ring for larger payloads.

The whole path is opt-in: with AITER_FLY_AR unset the dispatcher
disables itself in its constructor and the chain is exactly as before.
Every unsupported condition -- no flydsl, wrong arch, NCCL group,
multi-node group, unsupported world size -- is an early return that
leaves `disabled` set, and should_fly_all_reduce is a pure predicate that
answers False rather than raising.

A communicator built with reuse_from borrows the engine rather than
owning it, so destroy() only closes the IPC inboxes on the group that
built them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Add codec, policy and one-shot all-reduce tests

test_flydsl_allreduce_policy is CPU-only: it checks that the family
boundaries partition by size, that the ladders are ascending and reach
every super-tile they name, and that the env overrides apply where the
tables say they do.

test_flydsl_quick_allreduce_codec runs on a single GPU with no IPC, so it
covers the wire formats in isolation from the transport: INT4/INT6/FP16
round-trips, the E4M3 scale at both ends of its range, and the codec
resolution rules.

Two of its cases move with the E4M3 fixes rather than against them. They
were written against an encoder that saturated the exponent field alone,
so 512 encoded as 256 and an outlier decoded *smaller* than the ceiling
it passed; and against one where a positive extremum small enough to
encode as 0x00 collided with the reserved-zero byte and took its whole
group to zero at 1e-3. Both now assert the fixed behaviour -- monotonic
saturation past the ceiling, and a sub-floor extremum that rounds
coarsely instead of vanishing -- plus that exact zero still encodes as
exact zero.

test_flydsl_one_shot_allreduce spawns real ranks and checks the one-shot
is bit-identical to a torch all-reduce, not merely close, at TP2/4/8. It
lives in multigpu_tests because it needs more than one GPU.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Cover both schedules and the transport in the INT4 all-reduce test

The test gated only on SQNR, which cannot tell a transport bug from a
codec one: a chunk-addressing or flag-protocol fault and a codec
regression both show up as a worse number. Run the same cases over the
fp16 passthrough wire format, where the whole reduce is lossless on an
exact-grid input, and gate those on bit-identity with the fp32 reference
instead. A ring variant with one lap fp16 and the other int4 names which
lap is responsible when only one of them is.

Every case now runs on both the mesh and the ring. The ring's
reduce-scatter lap requantizes N-1 times where the mesh requantizes once,
so its SQNR falls with N -- 22.2 dB at TP2, 18.7 at TP4, ~15 at TP8
all-INT4. Defaulting that lap to INT6 at TP8 lifts it to ~21 dB, so one
18 dB floor now covers both schedules; the all-INT4 TP8 configuration is
still reachable through AITER_ALL_REDUCE_CODEC and keeps its own case at
the floor it actually delivers.

Cases that share a (world_size, algorithm, super_tile) group now ride a
single spawn and are memoized for the session. _run_rank already looped
over a list of shapes; this just stops calling it with one-element lists,
which is most of the wall time back on a file that is now 46 cases.

Adds a degenerate-input case (all-zero and far-sub-floor groups) that
pins the encode-reciprocal clamp: a zero extremum decodes to a zero
scale, and before the clamp that reached the codec as Inf and 0 * Inf
poisoned the whole tile. INT6 has four times less headroom there than
INT4, so it is the schedule that needs it.

The predicted super-tile now compares against the engine's clamped ST=1
grid rather than the requested grid_cap, which is what the host's own
selection compares against.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [FlyDSL] Add the all-reduce benchmark, roofline and policy-fitting scripts

bench_comm_allreduce sweeps every all-reduce candidate available on the
host -- RCCL, custom all-reduce, HIP quick-reduce, and the three FlyDSL
schedules -- over a shape list, on one process group, and reports
latency, achieved bandwidth and SQNR per candidate. Candidates that
cannot run a given shape are reported as declined rather than silently
skipped, so a sweep says which alternatives a winner actually beat.

transferbench_roofline turns a TransferBench point-to-point measurement
into a per-schedule lower bound: each family's wire volume as a function
of payload and world size, divided by the measured fabric rate. That is
what separates "this kernel is slow" from "this kernel is at the wire".

fit_allreduce_policy consumes a sweep and emits the family boundaries in
allreduce_policy's format, so the tables there are reproducible from
measurement rather than hand-maintained.

The shapes/ CSVs are the sweep lists the current policy tables were
fitted from: a small and a large payload sweep, and one that holds the
payload fixed while varying hidden to separate size effects from shape
effects.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Improve benchmarking script to run in fast mode by default.

* Fixed heuristics for the exact mode.

* Fix bugs in the benchmarking script.

* Update heuristics for xGMI interconnect.

* Fix classification of FlyDSL auto-deducted kernel in benchmarking script.

* Remove unintended Git modules.

* Add two new tuning knobs: workgroup size and ability to read ranks own contribution from registers instead of IPC inbox (self-skip).

* Update PCIe heuristics.

* Refactor FlyDSL all-rduce kernels integration to comms dispatcher.

* [FlyDSL] Scope OneShotAllReduce to its device instead of set_device

Mirrors what #4970 did for QuickAllReduceInt4: construction, launch and close
run under torch.cuda.device(), so building the engine no longer changes the
caller's current device.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] Address agent review feedback on the all-reduce dispatch

- Add a GPU-free regression test for the P1 finding: both FlyDSL selectors
  must decline a weakly- but not strictly-contiguous tensor (a full-storage
  transpose) instead of letting the engine raise after dispatch committed.
- Document the host-wide xGMI detection and the uniform-node assumption it
  relies on (P3).
- Drop a stray argument from the quick-reduce FlyDSL init log call; it had
  one more argument than placeholders.
- Re-run black (trailing whitespace, assert formatting back to main's) and
  suppress SIM102 on a const_expr guard, matching the other FlyDSL kernels.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] Move all-reduce tooling out of the multi-GPU test directory

The multi-GPU CI job runs every .py under op_tests/multigpu_tests/ as a
script, so tooling there ran as tests: fit_allreduce_policy.py failed on its
required argument and bench_comm_allreduce.py ran a full sweep.

- Remove fit_allreduce_policy.py and the sweep shape CSVs it was fed.
- Move bench_comm_allreduce.py and transferbench_roofline.py to
  op_tests/op_benchmarks/flydsl/, which CI does not execute, and update
  their usage text. --shape-csv stays as a user option.

Co-Authored-By: Claude <[email protected]>

* Remove fragile tests. Refactor multi-GPU tests for all-reduce to follow Aiter testing guidelines. Add the full kernel information to human readable kernel name.

* Black and ruff fixes. Improve comments about the use of CUDA events in the FluyDSL all-reduce tests.

* Add self-skip and block tunign knobs to two-steage mesh all-reduce.

* Use fx.generic_load, fx.generic_store, and fx.memory_fence to replace the inline ASM.

* Use system scope memory fence for releasing inboxes.

* Use uncached memory on PCIe when world size is two.

* Update aiter/ops/flydsl/kernels/quick_allreduce_int4.py

Address GitHub bot feedback.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Remove probe from 1-stage kernel.

* Remove the legacy buffer_ops.buffer_load and buffer_ops.buffer_store. Extract shared layout definition. Clen-up code.

* Ensure communicator initialization only compiles the relevant all-reduce instances.

* Trim the test suite for one-shot and quick all-reduce kernels.

* Collect shared all-reduce host wrapper assets to a shared module.

* Heuristics for xGMI interconnect.

* Update PCIe heuristics after the latest run.

* Add more cases to the benchmarking script.

* Addres black and ruff findings.

* Remove the custom logic for loading the HIP runtime library.

* Optimize memory fences for PCIe TP=2 case when uncached IPC memory is used.

* Fix a wrap-around bug in one-shot all-reduce.

* Improve benchmarking script such that it doesn't have bias towards FlyDSL instances.

* Optimized syncscope for xGMI interconnect.

* Update PCIe heuristics for TP=2 and for TP=4.

* Update xGMI heuristics. Introduce an env variable to override the min message size for FlyDSL one-stage all-reduce.

* Use _preload_compiled from TensorShim to run JIT compilation outside HIP graph capture.

* Black and ruff fixes.

* Add a Lamport (flagless) variant of the FlyDSL one-shot all-reduce.

The payload is its own flag: inbox slots hold a sentinel (bf16 NaN 0xFFFF in
every half-word) until a peer's data lands, the receiver polls all of its
sources together until no half-word is the sentinel, then re-arms the slot
two rounds ahead in a 3-buffer rotation. Senders rewrite a sentinel
half-word in their own payload to 0x7FFF, which is still NaN. That removes
the vmcnt(0) drain, both barriers and the flag round trip from every tile.

- kernel: `lamport` const_expr in make_one_shot_allreduce_kernel; uncached
  inbox only. The poll re-reads through relaxed system-scope atomics
  (_poll_v4i32) so the spin cannot be deleted. The first tile is peeled so
  its input load overlaps the colour load.
- IPC: UncachedIpcHeap.alloc takes a fill byte and synchronizes after the
  memset, so a late fill cannot erase a peer's first push.
- host: `lamport` is the 7th ONESHOT_LADDER field and an OneShotAllReduce
  knob; AITER_FLY_AR_ONESHOT_LAMPORT=0|1 pins it from the environment.
  Every shipped rung keeps lamport=False in this commit.
- tests: --lamport knob, Lamport spot configs at TP2/TP8, and a 300-call
  fresh-input stress checked bit for bit against a rank-order reference.
- bench: fly_1stage_lp and _lp variants of the pinned fly1s grid.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Ship the Lamport one-shot on xGMI and drop the one-shot floors there.

Sweep on 8x MI325X (gfx942), graph timing. Best Lamport config vs the flag
one-shot: TP2 -3..-23%, TP4 -3..-14%, TP8 -19..-41%. It ties or beats
cross_device_reduce down to 2 KiB at every world size, so the xGMI
min_bytes floors (56/48/112 KiB) go to 0.

ONESHOT_LADDER xGMI, all skip_self + lamport, atoms=1, cap 128:
  TP2  b128 to 256 KiB (one round), then b256
  TP4  b256
  TP8  b128

PCIe rungs stay on the flag variant (not measured).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Make Lamport all-reduce the default and add heuristics.

* Make self-skip default on one-shot and two-shot mesh algorithms. Redeuce the number of benchmarked configurations.

* Remove redundant/obsolete instances from benchmarking.

* Transferbench roofline fixes.

* Clean-up TransferBench runner script.

* Benchmarking script fixes.

* Move FlyDSL communication kernels into a single directory.

* Black & ruff fixes.

* Address first part of the code review feedback.

* Remove separate benchmarking scripts.

* Expand test scripts to run the benchmarking.

* Add gfx950/xGMI all-reduce policy rows; never pick the ring there.

The FlyDSL family policy was measured on gfx942 for xGMI. On gfx950/xGMI
(MI355X) the bench scenario of the all-reduce op tests shows:

* The ring never beats the mesh: 1.03x-1.16x slower at TP2 up to 512 MiB,
  2.2x-5.7x slower at TP4/TP8. The 128 MiB mesh_max sent large payloads to
  it; mesh_max is now unbounded there.
* cross_device_reduce's 2-stage kernel beats both the one-shot and the
  mesh over a wide middle range at TP4/TP8, so the one-shot ceiling drops to
  cdr's 2-stage switch and the mesh floor rises to where the mesh overtakes
  cdr (960 KiB at TP4, 1600 KiB at TP8). At TP2 the one-shot beats cdr up
  to 3 MiB and the mesh up to 448 KiB.

Rows measured on one arch live in ARCH_FAMILY_POLICY, keyed by
(arch, link, world_size), and replace the FAMILY_POLICY row on that arch
only; gfx942 keeps its rows. The resolvers and max_payload_bytes take an
optional arch, defaulting to this host's.

End to end through CudaCommunicator.all_reduce under graph capture (INT4
regime), against the old rows: never slower (within noise), 1.17x-1.54x at
TP4/TP8 mid-range, 2.47x (TP4) and 5.44x (TP8) at 256 MiB. Against stock
production with FlyDSL off: >= 0.99x at every size.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Make the all-reduce tuning ladders and policy records dataclasses.

Review feedback on #5461: ladder rungs were bare tuples, so every reader had
to know the field order.

* OneShotRung (min_bytes, atoms, grid_cap, fanout, block) and TwoShotRung
  (min_bytes, super_tile, grid_cap, block) replace the tuples of
  ONESHOT_LADDER, MESH_ST_LADDER and RING_ST_LADDER, and pick_rung() is the
  one implementation of "last rung at or below the payload" for both hosts.
* The records live in kernels/comm/allreduce_shared.py next to the rungs:
  FamilyPolicy, OneShotPolicy and QuantPolicy move there from
  allreduce_policy, with NO_MAX. allreduce_policy re-exports them.
* The mesh ladder comment described an older table; it now matches the
  rungs.
* OneShotAllReduce dropped a grid_cap ceiling branch that could not run:
  any grid_cap pins the configuration.

No behaviour change. Verified with the policy unit tests and both
multi-GPU verify scenarios on gfx950 (TP2/4/8).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Make the all-reduce heuristics readable from one module.

allreduce_policy.py now holds every tuned decision, in two levels, with a
module docstring that draws the payload axis:

* Level 1, which kernel: FamilyPolicy fields are renamed to say what they
  bound, in payload order -- oneshot_min, oneshot_max (was
  oneshot_max_exact), quant_min (was oneshot_max, which was not a one-shot
  maximum but the mesh floor), mesh_max, quant_max (was max_bytes).
  route() composes the two slots in CudaCommunicator.all_reduce order and
  returns oneshot / mesh / ring / fallback; the policy unit tests and the
  INT4 bench use it instead of private copies. The bench's copy reported
  "oneshot" for payloads that go to cross_device_reduce.
* Level 2, which configuration: ONESHOT_LADDER, MESH_ST_LADDER and
  RING_ST_LADDER move here from the kernel modules, which never used them.

No behaviour change: the rows keep their values under the new names. The
environment overrides keep their meaning. Verified with the policy unit
tests (plus a route() test for the gfx950/xGMI rows) and both multi-GPU
verify scenarios on gfx950.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Collect the all-reduce limits and shared constants in one place.

Review feedback on #5461: limits were restated across modules, and the ring
had a payload floor of its own that mirrored the policy by hand.

* kernels/comm/allreduce_shared.py has a "Limits" section: SUPPORTED_ARCHS,
  SUPPORTED_WORLDS, LINKS, SUPPORTED_BLOCKS, PAYLOAD_ALIGN_BYTES,
  MAX_PAYLOAD_BYTES, QUANT_MIN_PAYLOAD_BYTES and NO_MAX. The policy, the
  hosts, the codec, the one-shot kernel, CustomAllreduce, QuickAllReduce and
  the op tests import them instead of keeping their own copies (three
  SUPPORTED_ARCHS, two SUPPORTED_BLOCKS, two SUPPORTED_WORLDS, and the
  "pcie"/"xgmi" literals).
* The ring's standalone floor (_RING_MIN_PAYLOAD_BYTES_BY_WORLD, 4-12 MiB)
  is gone. It claimed to mirror mesh_max but matched no policy row, and
  production never used it (dispatch passes min_bytes=0). Both schedules
  now refuse the same thing on their own: payloads under
  QUANT_MIN_PAYLOAD_BYTES, the accuracy guard.
* The tuned constants MIN_BATCH_BLOCKS and RS_INT6_MIN_WORLD move to
  allreduce_policy with the rest of the tuning.
* The hosts' identical payload checks, link resolution, arch check and
  group checks become shared helpers: check_payload, resolve_link,
  require_arch, check_world_size and _validate_ipc_process_group.

Verified with the policy unit tests, both multi-GPU verify scenarios and
bench smoke runs on gfx950.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Code clean-up after refactoring the family policy and rungs for tuning ladders.

* Refactor FamilyPolicy to use explicit windows per algorithm. Clean-up the host wrappers to simply how the rungs of tuning ladders are used.

* Run only the production configs by default in the all-reduce tests.

* Clean-up comments and doc strings in ring all-reduce kernel.

* Ensure ring all-reduce gives bit.identical output for every rank. Add tests that execute production all-reduce dispatch. Fixed one-shot all-reduce window handling for th exact mode. Add an env variable to specify the interconnect type. Fix other small review findings.

* Rename factory for quick reduce ring kernel.

* Fix black issues, improve tests, and fix exact one-shot all-reduce window.

* Simplify handling of the one-shot all-reduce window.

* Rename all-reduce host side assets to have host prefix in the filename.

* Fix black and ruff.

* Small re-tune for PCIe.

* Add op_tests/multigpu_tests/flydsl_allreduce_bench.py on the test skip list since it contains no actual tests, only infrastructure.

* Address co-pilot review feedback.

* Remove dead code.

* Fix black & ruff.

* Ruff fix.

* Update tuning ladders for gfx950/xGMI after tuning sweep.

* Fix black and ruff.

* Ensure all ranks agree on which FlyDSL all-reduce needs to be built. Add CPU test to verify the rank agreement logic and append to GPU tests to have  a case where one rank has FlyDSL all-reduce disabled.

* Load all-reduce kernels onto device at initialization. This ensures that possible HIP graph capture doesn't include module loads. Add tests where first call takes place inside a graph capture (no wram-up).

* Remove ring ladders that are not shipped.

* Fix black & ruff.

* Fix performance regression for fused all-reduce + RMSNorm.

* allow fused all-reduce + RMSNorm inside the HIP graph capture.

* Update TP=2 ring algorithm window policy for gfx950/xGMI.

* Fix failing policy test.

* Address Copilot code review findings.

* Fix black and ruff.

* Fix Aiter bot findings.

---------

Co-authored-by: Sami Remes <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: samremes <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…nel with workgroup clusters (#7390)

* Fold gfx1250 MLA v4.1 sparse prefill split-K in-kernel with workgroup clusters

* Merge the opus MLA prefill kargs headers and tidy comments
…ine (#7303)

* review-pr: publish the card as a PR review with findings anchored inline

Today the bot posts card.md as one top-level issue comment. Across the 61
real cards it has published on this repo, those carry 229 findings; 120 of
them (52%) cite a `file:line`, and 65 of those lines are inside the PR's own
diff. Those are findings a reader would rather meet next to the code than
half-way down a wall of prose.

_publish.py now POSTs `/pulls/{pr}/reviews` with `event: "COMMENT"` -- never
APPROVE or REQUEST_CHANGES, this bot stays advisory and gates nothing. The
findings whose citation checks out and lands in the diff go up as `comments[]`
on their lines; everything else stays in the review body, together with a
one-line index of the ones that went inline. The index is not decoration:
without it a reader of the summary cannot tell whether findings exist
elsewhere or none do, and an invisible finding reads exactly like a finding
that was never made.

Anchoring is a privilege a finding earns. check_citations.py (ported from
ATOM, where it was built) is now wired in as run_one.sh step 3c: it writes
citations.txt, _lib.py collects it, and _publish.py refuses to anchor any
finding carrying a citation the checker flagged -- a top-level card that
cites a wrong line is a flaw the reader works around, but an inline comment
on a wrong line lands in the author's working view and is visibly wrong. With
no citations.txt at all nothing anchors and the whole card stays in the
summary, which is exactly what this bot posts today. The checker never gates
the run: it ran 1-for-2 on real cards, and a heuristic that withholds correct
reviews costs more than the defect it catches.

A review is all-or-nothing -- one anchor GitHub will not take fails the whole
call, summary included, which is worse than the comment this replaces. So a
refusal retries the same endpoint with the anchors folded back into the body
and says so. A review that silently sheds half its findings reads exactly
like a review that only had the other half.

Measured on ten of those real cards, replayed against the diffs they were
written for: the summary a reader meets first drops from 33,025 to 24,173
characters, 27% shorter, with 11 findings moved onto their lines.

Adapted from ATOM rather than copied: aiter's card writes `Review (advisory):`
where ATOM's writes `Review:` and adds a `Perf` line ATOM has no counterpart
for, so the summary matches on the bare word and keeps all three; the dedup
marker stays a literal `aiter-bot` instead of being derived from the
overridable AITER_BOT_NAME, and still searches issue comments as well as
reviews, so the markers already sitting on live PRs are not reposted over.

check_prompts.py gains three guards: the event stays COMMENT with exactly one
POST call site, the --post closure stays matched to the workflow's
permissions, and the anchoring wiring (run_one -> citations.txt -> _lib ->
_publish) cannot be half-removed in silence. selftest.sh now runs
_publish_test.py, and says out loud when pytest is absent rather than
passing over it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: anchor a finding to the section it cites, link what cannot be anchored

Inline anchoring attached a finding to a single line. Two things that costs, both
measured on this bot's own archived cards:

Spans. 25 of 221 archived findings cite a line *range* -- `layernorm.py:1002-1012` --
and every one was anchored to line 1002 alone, so the reader saw a comment pinned to
one line of a block the finding is about, which reads as a claim about that line.
GitHub takes a span as start_line..line with a side for each end; cite a range and it
is now anchored as one. Both endpoints and everything between must be commentable,
which is exactly "inside one hunk" -- checking the ends alone would accept a span
across the gap between two hunks, and one malformed entry fails the whole review,
summary and all other comments with it. When only part of the span is in the diff the
end that is gets a single-line anchor, rather than the finding being dropped.

The span pattern is deliberately tight: an ASCII hyphen with no whitespace. A loose one
reads the real card sentence "flash_kda.py:381 - 6 published tuning candidates" as the
backwards span 381..6. Over 221 findings the tight form matched 25 spans and no false
positive; the loose form added that one sentence and nothing true.

Permalinks. A citation whose line the diff does not reach cannot be anchored -- GitHub
is right to refuse it -- and used to sit in the summary as bare `moe.py:5220` text the
reader had to go and find. It now also gets a blob permalink pinned to the head SHA,
alone on its own line, which is the only place GitHub expands one into the code it
names. Pinned and not a branch: a link that drifts off the code it was written about is
a wrong anchor arriving late. The finding's own text is untouched -- the link is in
addition, never instead.

Neither is invented. Both run through the same gate anchoring already had: a citation
check_citations.py flagged, or a card it never ran on, gets no anchor and no link, and
a path that does not resolve to a file this PR touched gets no link either. A blob URL
built from an unresolved basename is a guess, and a link to the wrong code is worse
than no link for the same reason a wrong anchor is.

Verified by replaying eight real cards against the diffs they were written for: of 37
findings, 11 now take a span anchor, 16 a single line, 2 a permalink only, 8 nothing.
Auditing every span citation in the 57-card corpus, 23 of 35 span-anchor cleanly, 1
falls back to an endpoint, and 11 resolve to no file in the diff and so are left alone.

Replaying also turned up a defect in the index line this change introduced: when a span
collapses to one endpoint the index strips `path:563` and leaves the opening "-569". Fixed
and pinned by a test.

_publish_test.py gains 16 cases (spans, the hunk gap, the prose false positive, the
permalink gates, and a refused *range* review degrading with its text intact);
check_prompts.py gains two drift checks that build a review over a synthetic two-hunk
diff and assert the shape GitHub will take rather than the source that produced it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: the two bugs that made inline anchoring do nothing at all

Found by running the reviewer on this PR, on box 8, end to end. Seven gates green, 33
unit tests passing, and the payload it produced carried zero inline comments. Either
bug alone is enough to erase the feature; both were present.

**Citations resolved against the wrong tree.** check_citations.py picked one tree for
every citation and preferred merge-target, which fetch.sh checks out at BASE_SHA -- the
code before the PR. Citations into lines this PR added could never resolve there:
`_publish.py:221 -- file has 171 lines`, 171 being the length on base. All six were
hard-failed. head/ holds the PR's version of each changed file, merge-target/ the
pre-PR tree for everything else, so neither alone is right; resolution now tries them
in order per file. The reviewer found this one itself and graded it 🔴.

**A 50%-precision heuristic vetoed the feature.** flagged_citations() counted both
halves of the checker's output, so a proximity note disqualified a finding exactly as a
hard failure did. They are not the same claim: a hard failure means the citation
resolves to nothing, while a note says a quoted symbol is not within five lines of the
cited one -- a quality hint the checker's own docstring puts at ~50% precision. Only
hard failures disqualify now. A heuristic that silently switches off what it guards is
the worse failure: a wrong anchor is visible and correctable, an absent one looks
exactly like a review with nothing to say.

Verified on the real card from that run, with the trees rebuilt from the PR's own head
and base: **0 anchors and a 4163-character summary before, 5 anchors and 990 after**.
Three tests pinned the old veto rule and failed, which is what they are for; the veto
test's fixture now uses a hard failure, and a new test pins that a note leaves the
anchor in place.

Still unverified: whether GitHub accepts these payloads. No code here has made a live
review call.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: rejected validation evidence degrades the review instead of deleting it

Ported from ATOM, where this failed for real. The first live auto-validation
run got as far as invoking the validator, then died: the consumer that checks
a validation report runs under errexit, and `import jsonschema` failed on the
runner. No card was produced at all.

aiter's consumer has the same shape -- 33 fail-closed checks, any one of which
aborts fetch.sh -- so it has the same failure available to it. A review that
vanishes reads, to the human waiting on it, exactly like a bot that is down,
and a missing optional dependency is not evidence that anything about the PR
is wrong.

The integrity checks stay fail-closed: evidence that does not match this PR's
head, base or patch is still never consumed. What changes is the consequence
of rejecting it -- the rejection is captured, its reason recorded in
auto_validation_outcome.txt, and the review falls through to the no-evidence
branch, so the card says validation did not run and names why.

_degrade_test.sh extracts the real consumer region out of fetch.sh by its line
markers and drives those bytes with a report for the wrong head, asserting all
four things the live failure got wrong. Collapsing `set +e` back reproduces
that failure exactly -- verified in both repos before committing.

Not ported: ATOM also had to make its validator print why a non-PASS verdict
happened, because it printed the verdict alone and the report evaporated with
the scratch dir. aiter's validator already names its output file, so that is a
different situation and is left alone rather than changed on spec.

selftest: 85 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: a run that dies in fetch says so, and says what to do about it

Ported from ATOM, where this happened twice in a row on a live run. The log
ended mid-sentence and said nothing further:

    [run_one #2889] fetch...
    GraphQL: API rate limit already exceeded for user ID 349247671.

Two defects, both present here in the same shape. errexit aborts run_one
inside the fetch pipeline, before the line that classifies a failed fetch can
run; the status is then written by the EXIT trap, which wrote the file and
printed nothing -- so the one place the reader already was said the least.
The traps now say their piece out loud, and the fetch status is taken as a
value and classified.

The classification it would have reached was also wrong for this cause:
"check gh auth/token, network, git and disk" sends someone hunting a broken
credential when the credential is fine and a quota is empty. A quota resets on
GitHub's own clock and the only correct response is to wait and re-run, so it
is named separately, quoting the refusal, and it states that nothing about the
PR was examined -- a run that looked at nothing must not be mistaken for a
review that found nothing.

_fetchfail_test.sh drives that classification with a fetch that fails two
ways, asserting the quota is named, the non-examination stated, and that a
non-quota failure still falls through to the generic cause.

selftest: 86 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: say when the quota comes back, not "within the hour"

"The quota resets on GitHub's own clock (an hour at most)" is not something
anyone can plan around -- it means the same thing one minute before the refill
and fifty-nine minutes before it. GitHub's /rate_limit endpoint does not count
against the quota, so the exact refill time is readable even while the quota
is spent. The line now names it:

  GitHub's API quota for this bot is spent (the token is fine) -- it refills
  at 06:26 UTC, in about 25 min; re-comment then. Nothing about this PR was
  examined.

What is wrong, how long, what to do, and that nothing was looked at. The vague
wording survives as the fallback for when the reset time cannot be read -- a
wrong number would be worse than no number.

The test caught a real defect while being extended for this: the reset lookup
ends in a grep, which returns non-zero when it matches nothing, and under
errexit that killed the run outright -- so the fallback line could never be
reached. Fixed, and both paths are now asserted, along with a non-quota
failure keeping its own cause.

ATOM 97 green / 0 red, aiter 86 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: tell a restricted account apart from a throttled one

Measured on the bot's own token today: rocm-atom-bot reports core 58/60 and
graphql 0/0. An authenticated account gets 5000/5000 -- 60 with GraphQL at
zero is the profile GitHub leaves on an account it has restricted. That is
what has been failing every run, and it is not a quota that refills.

I had this wrong twice in a row, and told a person to wait an hour for it. The
message shipped an hour ago would have said the same: it reads the reset
timestamp and promises a refill. For a restricted account that promise sends
someone to wait for something that never arrives, which is worse than the
vague wording it replaced.

So the two are now distinguished by what only one of them looks like -- a
60-call cap with GraphQL disabled -- and the restricted case says plainly that
waiting will not clear it, and that the account needs unflagging or the bot
needs a different one. Both still say that nothing about the PR was examined.

Test covers all four paths now: refill time readable, refill time unreadable,
restricted account, and a non-quota failure keeping its own cause. Removing
the restricted branch makes it fail on both of its assertions.

ATOM 97 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: the citation checker never ran, and the tests that said it did used the wrong flags

Found by this bot reviewing its own PR. All three findings held up under my
own verification; two of them are about code committed today.

1. check_citations.py's main() called tree_for(); only trees_for() exists, and
   it then passed a `trees` it never assigned. Every invocation raised
   NameError. run_one.sh's `|| true` swallowed the crash, citations.txt
   carried a Python traceback, and _publish.py's flagged_citations() read that
   traceback as "nothing flagged" -- so findings were anchored inline with
   zero citation checking, which is the exact failure this checker was added
   to prevent. The proof is this PR's own run: reports/PR-7303/citations.txt
   is a traceback, and the gate was green.

   The 34 pytest cases all exercise check(). Nothing called main(). A
   function no test calls is a function that does not work yet, so
   _citations_test.sh now runs it end to end on a resolvable and an
   unresolvable citation; restoring the NameError fails all four assertions.

2. Every fetch-failure classification added today was unreachable in
   production. run_one.sh runs `set -euo pipefail`, and
   W="$(grep ... | tail | cut)" is a fatal assignment when grep matches
   nothing -- the script died there, before any classification. The region
   tests passed only because they ran the extracted bytes under bare `set -e`.
   Measured both ways: `set -e` writes the status file and names the cause;
   `set -euo pipefail` exits 1 silently with no status at all.

   That is the defect this project exists to catch, sitting in my own test. All
   region tests now run under the flags the scripts actually use, and removing
   the guard fails eight assertions instead of passing.

3. The same unguarded shape in fetch.sh's rejection handler (also
   `set -euo pipefail`), which would kill the handler whose whole purpose is
   to keep the review alive. Guarded in both repos.

ATOM 98 green / 0 red, aiter 87 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: a traceback in citations.txt is not a clean verdict

Found by this bot reviewing this PR, and it is the half of its own earlier
finding that I fixed badly. That finding asked for two things: stop
check_citations.py crashing, and stop flagged_citations() reading a crash as
"nothing was flagged". I did the first and left the second, so the crash was
gone but the defence against the next one was never built.

The module docstring already promised this behaviour -- "when citations.txt is
missing or the checker could not run, nothing is anchored" -- while the code
did the opposite for the one case that actually happened: a file with content
but no CITATIONS verdict line returned an empty set, which means "every
citation checks out", so every finding anchored with no checking at all.

Absence of a verdict line is now treated as "the checker did not run",
however the file got that way. The test feeds the real traceback this PR
produced two revisions ago; removing the guard fails it.

aiter 35 pytest cases, ATOM 33.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: untrack the review outputs that a careless `git add` swept in

b841de1 staged `.claude/skills/review-pr/` as a directory, which picked up
the eleven files a review run had just written to reports/PR-7303/. They are
not part of this change: they are one run's output, about one commit, and
`run_one.sh` regenerates them. A tracked card is also wrong the moment the PR
moves -- the one committed here reports a finding that is already fixed at
head, and it cites a crashed citations.txt as evidence.

A .gitignore in the skill directory stops the next one, because the mistake
is `git add <dir>` and that will happen again.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: a refused post must not exit 0

main() returned 0 whether the review went up or was refused. It printed
"❌ failed to post" and then told the caller everything was fine -- so a
refusal would be invisible to the workflow step, on every run, while each card
was quietly lost.

That matters most for the one refusal the degrade path cannot cover. The
anchored-then-summary fallback handles a bad anchor; it cannot handle a token
that may post issue comments but not create reviews at all (`Issues: write`
without `Pull requests: write` on a fine-grained PAT). Both attempts fail, and
until now the step stayed green.

This is not hypothetical here: aiter-bot has `read` on this repo and has
created zero reviews across the PRs checked, where it has posted an issue
comment on each. That is equally consistent with "the scope is fine and it has
never tried" and with "the scope is missing" -- the two are indistinguishable
from the outside, which is the whole shape this pipeline exists to break. The
holder says the scope is sufficient; this makes being wrong about that cost
one red step instead of every card.

The test pins the refusal the API actually sends and asserts its words reach
the operator. Writing it caught a second defect in itself: stubbing every API
call made the gate skip on PR metadata, so the test passed without reaching
the code it names. It now refuses only the review POST.

aiter 36 cases / 97 green, ATOM 34 cases / 98 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: a citation of untouched context was judged an invented path

Both defects found by @zoe-cop in review; both verified before changing
anything, and both hold.

The basename fallback searched trees[0], which is head/ -- a sparse tree
holding only the files the PR changed. A citation of real context code by
bare basename (moe.py:5220 in a file this PR never touched) therefore matched
nothing and was reported as "no such file in the tree", i.e. an invented path,
rather than the ambiguity note it was meant to get. _unflagged_cites then
forfeits the whole finding's anchor AND permalink on any single hard failure,
including a correct, fully-qualified, in-diff citation in the same sentence.
So citing context code switched anchoring off silently -- the failure this
checker was added to prevent, produced by the checker.

It now searches merge-target/, the full tree at BASE_SHA. Fixing that exposed
a second half: hits[0] could come from the diff (present in head/) or from the
basename search (present in merge-target/), while resolution assumed one tree,
so a single hit landed on "is in the diff but not the tree". Resolution now
follows whichever tree actually holds the file. Verified on all three verdicts:
a lone context file resolves, several of the same name give a note, an
invented path still fails.

Second: the summary-only retry appended the folded findings to a body still
carrying build_review's "N finding(s) posted inline, on the lines they are
about" index. True of the attempt GitHub refused, false of the one being sent,
where comments[] is empty -- so the degraded review pointed the reader at
lines carrying nothing and then listed the same findings again. That is the
inverse of the silence this fallback exists to prevent. The index is now
stripped before folding.

@zoe-cop also diagnosed why the existing test could not catch it: it asserts a
retry happened and that comments[] emptied, never what the body says, so it
passes on the stale index alone. The new test asserts the anchored body
carries the index and the degraded body does not.

selftest 97 green / 0 red, 37 pytest cases.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: the drift check died outside a git checkout

Found by running this PR's own verification the way its description tells a
reviewer to: on a clean `git archive HEAD` export, not the working tree.

    $ python3 check_prompts.py
    FileNotFoundError: '.claude/skills/review-pr/SKILL.md'

_skill_md asked git for the repo root. `git rev-parse --show-toplevel` prints
an empty string when there is no repo, and Path("", ".claude", ...) is then a
RELATIVE path resolved against the caller's cwd -- so the check that exists to
catch prompt drift could not run at all in the one place a reviewer would run
it. It passed every time it was tried because every trial was inside a
checkout, including a "fresh /tmp worktree", which is still a git tree.

SKILL.md sits next to check_prompts.py. It reads it from there and asks git
nothing.

The guard reproduces a real export -- `git archive HEAD | tar -x` of the
tracked tree, no .git -- and asserts exit 0 from a cwd outside it. Writing it
the obvious way first (copy the skill directory alone) asserted something the
project does not promise and failed on an unrelated missing workflow file; a
guard has to test the thing that was promised, which here is the export.

Restoring the git-root lookup turns it red in both repos.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: the guard for leaving a checkout could not itself leave one

The guard added a moment ago built its fixture with `git archive HEAD`. Run
from a working tree that passes; run the suite from a clean export -- which is
what this PR's description tells a reviewer to do -- and there is no repo to
archive from, so the guard failed and the suite went red for a reason that had
nothing to do with the code under test.

A guard that only works inside a checkout cannot test leaving one. It now
builds the fixture directly: the skill tree at its repo depth plus the workflow
file the check reads, in a directory with no .git. No git involved, so it
behaves the same inside a checkout and outside one.

This also closes the loop the previous commit opened. The whole suite now runs
green from inside a clean export in both repos -- aiter 98/0, ATOM 99/0, drift
clean, pytest passing -- which is the state the verification instructions have
been describing all along and that nothing had ever checked.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: raising the per-agent timeout alone silently starves the refuter

Hit while re-reviewing ATOM#2762, whose diff grew past the 40-minute worker
budget after main was merged in. Raising AGENT_TIMEOUT is the obvious response
and the timeout message names that exact knob -- but a review runs two agents
in series, and the gate that starts each one refuses to begin an attempt that
cannot finish inside RUN_BUDGET. So with AGENT_TIMEOUT=5400 against the
default RUN_BUDGET=7200, the worker runs, the refuter cannot start, the
`independent` gate reds, and the review is withheld after an hour of work --
reported as a timeout whose named fix makes it worse the next time.

The constraint is AGENT_TIMEOUT x 2 <= RUN_BUDGET, and nothing enforced it.
It is checked now before any work is spent, with an error that names both
numbers and both ways out. Exit 2, distinct from the review's own failures.

Verified on three pairs: 5400/7200 refused, 5400/14400 accepted, and the
shipped defaults (2400/7200 here, 2400/6000 on aiter) unaffected. Removing the
check turns the selftest red.

ATOM 100 green / 0 red, aiter 99 green / 0 red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* review-pr: drop the import the git lookup left behind

CI's "Lint the skill for real errors" step runs ruff with --select F,E9 --
the rules that catch actual mistakes rather than style -- and it went red on
F401: `import subprocess` became dead when _skill_md stopped shelling out to
`git rev-parse` in 058dfd0.

My own ruff run used the repo's default rule set, which does not include F401,
so the check I ran and the check CI runs were not the same check. ATOM is
unaffected: its check_prompts still calls subprocess elsewhere.

selftest 99 green / 0 red, ruff --select F,E9 clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: zufayu <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
… gfx1100 table (#6770)

* [Triton/Gluon] fav3_sage: keep V in FP16 on archs without FP8 matrix cores

fav3_sage quantizes V to FP8 for the P*V product. RDNA3 (gfx11) has no
FP8 WMMA, so Triton converts the FP8 V tile and the FP8 P tile to FP16 in
software in the inner loop. On gfx1100 this limits the kernel to about
8 TFLOP/s for every tile size.

When arch_info.is_fp8_avail() is False, sage_quant now writes V as FP16
with the same per-channel scale. The kernel takes its P*V type from V,
so it runs FP16 WMMA. The archs that have FP8 (gfx942, gfx950, gfx12,
gfx1250) keep the FP8 path.

* [Triton/Gluon] [Config] [gfx1100] Add a tuned fav3_sage table

gfx1100 has no fav3_sage table, so it used the gfx942 table:
BLOCK_M=256, BLOCK_N=128, num_warps=8. With wave32 and 256 VGPRs per
lane, this tile spills more than 1000 VGPRs at head dim 128 (183 at
head dim 64). With FP8 V it ran at 5-6 TFLOP/s, and the first call
compiled for 9 minutes (4608 tokens) to 40 minutes (32760 tokens).

The new table uses BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=1,
waves_per_eu=1. This tile does not spill. It was the best single tile in
a sweep over BLOCK_M, BLOCK_N, num_warps, num_stages, waves_per_eu and
PRE_LOAD_V on a Radeon PRO W7900, for head dim 64 and 128 at 4608 and
32760 tokens. fwd_a3_tuned has the same values, so a3_tuned does not
change the launch on gfx1100.

* [Triton/Gluon] fav3_sage: pass a 16-bit V through instead of scaling it

With an FP16 V, sage_quant still computed the per-channel amax, divided
V by it in the quant kernel, and the attention epilogue multiplied the
scale back. For a 16-bit type this costs an amax, a full read/write pass
over V and an extra rounding, with no precision benefit.

sage_quant now quantizes V only when v_dtype is FP8. For FP16/BF16 it
returns V as is (cast to v_dtype if needed) with a v_scale of ones and
launches no V programs; sage_quant_kernel guards the V branch with a
QUANTIZE_V constexpr (it replaces the unused FP8_MAX). The FP8_TYPE /
FP8_MAX / v_fp8 names become v_dtype / v_dtype_max / v_out.

fav3_sage_wrapper_func takes a v_dtype argument (default: FP8 when the
arch has FP8, else FP16), so the 16-bit V path is tested on every arch.
New tests: sage_quant pass-through, accuracy for each V type, and
non-dense inputs with an FP16 V.

gfx1100 (W7900), Triton 3.8: sage_quant 1.04-1.06 -> 0.74-0.79 ms at
(1, 24, 4608, 128) and 4.2 -> 3.0-3.1 ms at (1, 12, 32760, 128); output
unchanged (same cosine, rel. L2 and max abs vs fp32 SDPA). gfx942: FP8
path unchanged.
…7439)

* tune bmm and mxfp8 together ,update related tuned csv

* refine code

---------

Co-authored-by: solin <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: solinzby1 <[email protected]>
…KV-head PS path (#6244)

* [Triton/Gluon] Gluon PA decode: allow query_length > 4 on the single-KV-head PS path

pa_decode_gluon rejected query_length > 4 and query_length *
query_group_size > 64 before choosing a kernel. With PS and a single KV
head the launch spreads the query tokens over the grid's middle axis, so
one program's query tile is max(16, next_pow2(group)) rows at any
query_length. The guard therefore blocked speculative decoding deeper
than 3 draft tokens (e.g. MTP-7, query_length 8) on a path whose tile
never grows.

Bound the tile per path instead. On the single-KV-head PS path only the
group bounds the tile (<= 64 rows, the largest the QK layout has register
bases for). Every other kernel holds every query token of a sequence in
one tile and keeps both old limits. The launch wrapper, this guard and the
asymmetric Q/K and V head check get the PS kernel choice from one helper,
_uses_ps_kernel.

The narrow-group split (group < 16) derived its tokens per program as
cdiv(next_pow2(query_length), splits), which is not a power of two for
e.g. query_length 5 at group 8 (3 tokens, a 24-row tile) and fails to
compile in define_layout. _ps_query_split packs
min(next_pow2(query_length), 16 // group_pow2) tokens per program instead.
For every input accepted before, the grid and constexprs are unchanged.

Tests: the ps_long_query_accuracy case set covers query_length 5 and 8 on
(8, 1), (16, 1) and (64, 1), fp8 and bf16, multi-split 2048/8192 contexts,
with and without a sliding window. test_unsupported_query_shape_is_rejected
keeps the one-tile paths and a 128-row group rejected before launch.

* [Triton/Gluon] Gluon PA decode: reject windows not longer than the query on the single-KV-head PS path

The PS sliding-window kernels give each query token sliding_window -
query_length keys. When sliding_window <= query_length, all keys are
masked and the output is not valid attention. The single-KV-head PS path
now takes query_length > 4, so it rejects these windows before launch.
test_unsupported_query_shape_is_rejected adds query_length 8 with an
8-token window.

The multi-KV-head PS kernel and the 1024-token-block kernel use the same
window but keep query_length <= 4, so their behavior does not change. The
non-PS kernel gives each query token sliding_window keys.

Update the pa_decode_gluon docstring and aiter/ops/triton/gluon/README.md
with the query limits of the single-KV-head PS path.

* [Triton/Gluon] test_pa_decode_gluon: cover one-partition long queries with ps=False

With one context partition, pa_decode_gluon selects the PS kernel also
for ps=False, and the kernel stores the output directly. Large batches
also take this path, because get_recommended_splits can return 1. Add a
ps_long_query_accuracy phase with ps=False, context length 256, groups 8
and 16, and query_length 5 and 8.

* [Triton/Gluon] test_pa_decode_gluon: use ragged lengths in the one-partition long-query phase

CI run 41613999935 failed 5 of the 16 cases of the one-partition phase of
ps_long_query_accuracy, all without a sliding window. In each case, 0.01%
or less of the output was out of the 5e-4 (bf16) or 5e-3 (fp8)
tolerance. The kernel rounds the probabilities to the compute type
before the PV MFMA. A 256-token context gives larger outputs than the
2048- and 8192-token contexts of phase 1, so this rounding is more than
the tolerance. A CPU emulation of these numerics gives the same failure
rate at 5e-4, and no failures at 5e-3 with the lengths of this phase.

Use ragged KV lengths of at most 256 tokens. They keep one partition and
get the kv_varlen tolerance of run_pa_gluon_test. A wrong direct store
changes full output rows, so this tolerance still finds it.
…ger clip (#7258)

The quick all-reduce codec (mesh and ring, INT4 and INT6) stores each
16-value group's scale as signed E4M3 with bias 7, which spans
[2**-7, 480]. A group whose extremum is above 480 clips to about 480, both
when a rank quantizes its partial and when the reduced sum is requantized;
the ring requantizes at every hop, so sums of a few values near 300 clip
too. MiniMax-M3 all-reduce outputs reach 6400-16800, and vLLM routes BF16
INT4 quick reduce here whenever AITER is on, so MMMU on MI355X drops from
about 0.66 to 0.27-0.31 at TP2/4/8.

Store the scale as E5M2 with bias 12 instead, spanning
[2**-12, 1.75 * 2**19]: same byte, same wire layout, same instruction
count, and every fp16 extremum fits. INT6 divides by 32 instead of 8, so
its smallest scale is floored at 2**-10 to keep the fp16 encode factor
finite (Codec.scale_min_e5). The scale has 2 mantissa bits instead of 3:
INT4 rounds it to nearest and loses about 0.3 dB in-range SQNR; INT6 rounds
it up (Codec.scale_rounds_up), which avoids clipping the group extremum by up
to 1/8 (four INT6 steps) and keeps INT6 at E4M3's SQNR.

The ring requantizes its partial sum at every hop, and at TP4 an all-INT4
ring had only 0.26 dB of margin over the 18 dB floor (18.26 dB with E4M3);
with E5M2 it lands at 17.89 dB. Default the ring's reduce-scatter lap to INT6
from TP4 instead of TP8 (RS_INT6_MIN_WORLD = 4). On PCIe this sends up to
26/18 of the reduce-scatter bytes at TP4; a precision-preserving scale
(per-slice E4M3/E5M2) would let it move back to TP8.

FlyDSL does not hash the codec helpers into its disk cache key, so add
SCALE_CODEC_TAG to both kernels' launch names; without it a warm cache
keeps loading E4M3 binaries.

Tests: the codec tests assert that large extrema no longer clip (instead of
asserting saturation at 480), with the analytic bound widened to the 2-bit
scale mantissa; the op test adds a fill above 480 on every rank for the
mesh and the ring, and the divisor test now requires divisor 1 to reach the
SQNR floor and divisor 8 to cost at most 1 dB. A pinned int6/int4 ring case
runs at TP8.

Signed-off-by: Vorapol Assavasangthong <[email protected]>
…oducers (#7174)

Routes bench_sage to the hd256 MXFP4/MXFP6 producers from #7173 and adds an aiter_fp8 comparator using FMHA v3 per-tensor FP8.

Signed-off-by: jcaraban <[email protected]>
* mha_v4: split short sequences over the keys with kv_splits

A dense launch runs one work-group per (batch, head, 256-row query
tile), so a short sequence with few heads leaves most CUs idle:
[1, 4352, 3, 128] fills 51 of MI355X's 256. mha_v4(kv_splits=n) folds
n equal key ranges into the batch of one launch, Q repeated as a
stride-0 view and K/V cut as views, then merges the partials by their
LSE in a new Triton kernel (lse_merge). Operands are quantized before
the split, so per-tensor scales and the LSE bias stay global and
cancel in the merge. kv_splits="auto" takes the largest n that keeps
the grid in one wave, divides Sk and leaves ranges of at least 512
keys (mha_v4_kv_splits); a grid that already fills the GPU gets 1.

Supported for BF16, BF16/FP8, INT8/FP8 and FP8/FP8 on gfx950, without
block_mask or seqlens_k; the MX recipes pack K/V in tiles no key range
can be cut from. Explicit counts outside that raise, "auto" falls back
to the unsplit call. The default stays 1.

At [1, 4352, 3, 128] under HIP graphs, BF16 goes from 74 to 36 us,
BF16/FP8 from 63 to 37 us and FP8 from 132 to 121 us, with the same
error against FP32 attention. At 32 heads auto picks 1 and costs
nothing; any split there is slower.

Eager calls to the launch custom ops now run their bodies directly
and keep the op for torch.compile. A mutating custom op's Python
dispatch cost ~55 us per call, most of the host time of a launch;
BF16 mha_v4 drops from 72 to 15 us of host time.

Also fix _restore_k_mean_in_lse under GQA: it applied a K-head mean to
Q heads, so return_lse failed for any quantized K with fewer KV heads.

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

* mha_v4: gate kv_splits "auto" on the LSE gate, fix explicit counts

kv_splits merges its key ranges by their LSE, so where it may split is
where MHA v4 exports one. "auto" asked for gfx950 by name instead; it
now asks the LSE gate for the call's Q and V formats, which admits the
same four per-tensor recipes on gfx950 as before. An arch whose LSE is
validated later gets auto with it, without another arch check here.

An explicit count crashed with a TypeError: _resolve_kv_splits called
_check_lse_capable() without its operands. It now passes Q and V, so a
count on an arch or recipe without LSE raises the gate's
NotImplementedError.

mha_v4_kv_splits sizes the split from the device's own CU count, so
each SKU and partition mode gets its own: [1, 4096, 1, 8192] splits 16
ways on MI300X and MI355X, 8 on MI300A and 4 on MI308X. A test pins
that, and another checks auto and the explicit count against a refused
LSE gate.

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

* mha_v4: let kv_splits leave a remainder on the last key range

kv_splits needed a count that divides the key length, so a prime or
odd Sk could not split at all and "auto" settled for a smaller
divisor: [1, 4352, 3] on 256 CUs fits 5 ranges in one wave but took 4.

Range i now starts at key i * (Sk // n) and spans Sk // n + Sk % n
keys, so the ranges overlap by the remainder and the last one ends at
Sk. A per-range seqlens_k cuts every other range back to Sk // n, so
each key is attended once. The fold stays a view when B is 1 or n
divides Sk. Otherwise K and V are copied once, as Q already is for
B > 1. An even split passes no seqlens_k and runs as before.

This needs a dense row that takes per-batch key lengths: BF16 and
BF16/FP8 on gfx950. mha_v4_kv_splits gains ragged=False, which auto
sets for those operands. INT8/FP8 and FP8/FP8 still need a divisor and
raise a ValueError saying so. A count above the key length now raises
too. _varlen_capable is split out of _check_varlen_capable so auto can
ask without raising.

Also drop the comment about the gfx942 code objects from
_lse_unsupported.

The tests cover a fold that reproduces every key once and is a view
only when it should be, the ragged heuristic, and uneven counts
(splits=3, and a B=2 GQA shape with Sk=1001) in the unsplit-accuracy
test.

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

* mha_v4: fix kv_splits under torch.compile and its sparse fallback test

_fold_key_ranges built the overlapping key ranges with as_strided, whose
storage_offset() Dynamo cannot trace, so kv_splits broke a fullgraph
compile. unfold gives the same view without it.

test_mha_v4_kv_splits_auto_leaves_unsupported_calls_unsplit built its
block mask for a 256x64 tile; the gfx950 BF16 sparse row is 256x128.

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

* mha_v4: follow main's per-batch key lengths in kv_splits

Main extended seqlens_k to the FP8/FP8 and INT8/FP8 rows, so on gfx950
every recipe kv_splits accepts can now end its last key range short,
and a count no longer has to divide the key length.

- Correct the docstring, which still limited the remainder to BF16 and
  BF16/FP8.
- Cover the divisor requirement with a row whose per-batch key lengths
  are patched away, since no gfx950 kv_splits recipe hits it any more;
  drop the FP8 case that expected the error.
- Bound the split LSE error relative to the unsplit one. Splitting
  moves it by noise on the order of the recipe's own quantization
  error: under 0.001 nats for BF16, but up to 0.036 for FP8 Q/K against
  an unsplit error of ~0.55, on even splits as well as uneven ones.

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

* mha_v4: size the kv_splits fallback test's block mask from the KV tile

Derive the key-tile count from mha_v4_kv_tile(), as the other sparse
tests do, rather than restating gfx950's 256x128 geometry.

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

* mha_v4: compute lse_merge offsets in 64 bits

The merge reached split i at i * stride_po_b, which Triton computes in
the stride's 32 bits, so it faulted once (splits - 1) * S * H * D passed
2^31. The row offset rows * stride_po_s overflowed the same way within
a single partial once S * H * D passed 2^31, even with one split.

Make the batch, head and row offsets 64-bit and reach each split by
stepping the pointers. Speed and output are unchanged. Add a test at
both sizes that puts all weight on the last split, so the merge must
return it exactly.

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

* mha_v4: prefer kv_splits="auto" counts that divide the keys

Since main let all four split-capable recipes take per-batch key
lengths, auto took the largest count that fits one wave and let the last
range take the remainder: 5 at [1, 4352, 3, 128], where 4 divides the
keys. A remainder builds seqlens_k with two kernels per call (~3 us
replayed, ~14 us of host time), and past batch 1 the key ranges stop
being a view, so K and V are copied: [2, 4352, 2] ran 86 us at 3 splits
against 70 us unsplit.

Take the largest dividing count that fits, and fall back to a remainder
only at batch 1 when no count divides. Across batch-1 shapes on MI355X
a divisor above half the fit was faster replayed and eager; below half,
replayed BF16 gained up to 17 us from the extra splits, while eager calls
and replayed FP8 still favoured the divisor. At [1, 4352, 3, 128] auto
now replays in 41 us instead of 46 us for BF16.

Document that auto minimizes device time and is meant for graph-replayed
or compiled callers: a split adds ~35 us of host time per eager call.

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

* lse_merge: read BLOCK_M and num_warps from a tuned config

The tile was a literal 32 x 4 with no record of how it was chosen. Move
it into configs/gfx950/triton/attention/lse_merge/DEFAULT.json, read
through get_tuned_kernel_config, so a sweep can see and change it.

Swept BLOCK_M 8/16/32/64/128 x num_warps 1/2/4/8 on MI355X with graph
replay, over the kv_splits shapes of mha_v4 ([1, 4352, 3] at 2/4/8
splits, [1, 8192, 3] at 2, [1, 3586, 1] at 7, [1, 5000, 2] at 5,
[2, 4352, 1] at 4) and [1, 16384, 8] at 4, each with and without the
merged LSE. 16 x 4 was within 1.7% of each shape's best on average and
32 x 4 8% behind, up to 27% at [1, 3586, 1] x 7 (2.55 -> 2.01 us).
Other archs keep 32 x 4 as the fallback until measured.

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

* mha_v4: test lse_merge directly on empty key ranges

mha_v4 gives every key range real keys, so the merge's guards for a
range without any (LSE -inf) were never run. Test the merge against a
torch reference with a range empty for every row, rows empty in only
some ranges, and rows empty in all of them, which must merge to a 0
output and LSE -inf rather than NaN. Dropping either guard, on the max
or on the total weight, makes it fail.

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

* lse_merge: reject partials holding no key range

Zero partials divide evenly into any batch, so splits came out 0 and
the merge silently wrote a 0 output and LSE -inf. Raise ValueError
instead. mha_v4 only merges with kv_splits >= 2, so this only reaches
direct callers.

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

* mha_v4: bound explicit kv_splits by one KV tile per range

kv_splits="auto" already leaves every range at least 512 keys, but an
explicit count was only checked against the key length, so it could
cut ranges down to a single key. That stays accurate: on MI355X even
3-4 keys per range match the unsplit call. But a range shorter than a
KV tile still costs a whole tile, so those splits only add work-groups
and merge traffic. Q [1, 1000, 3, 128] over 1024 BF16 keys takes 25 us
unsplit, 28-31 us at 4-16 splits, 40 us at 64 and 128 us at 256. The
merge also unrolls over the split count, and its cold compile grows
from 2.2 s at 64 splits to 13.4 s at 128; kv_splits=1024 had not
finished compiling after two minutes.

Reject explicit counts above key_length // mha_v4_kv_tile(), so every
range holds at least one KV tile, test the bound and its inclusive
edge, and document it.

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

* mha_v4: benchmark kv_splits with graph-replay and eager timing

benchmark_mha_v4 only timed the unsplit path, so the kv_splits table in
the PR description could not be regenerated. Add kv_splits and timing
parameters, with --kv-splits (ints or "auto") and --timing
(profiler|graph|eager) in main():

- graph: median of 100 replays of a HIP graph holding 10 calls
- eager: median of 50 samples of 20 calls, issue to synchronize, plus
  the time to issue them alone as "host us"

Split counts other than 1 time only the recipes that split, and "auto"
records the count it picked. Calls write into a preallocated out. The
profiler timing stays the default.

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

* mha_v4: gate per-batch key lengths on the live GPU arch

_varlen_capable used get_gfx(), which follows GPU_ARCHS, while the
launcher dispatches on the live device. Use get_gfx_runtime() instead,
behind a torch_compile_guard op, the same way get_gfx() hides its
rocminfo probe: called directly, it makes torch.compile(fullgraph=True)
fail on the subprocess.

The new test reports a different build arch and checks that the gate
still follows the GPU, eagerly and under fullgraph compile.

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

* lse_merge: do not read the partial output of empty key ranges

A range with LSE -inf for a row weighs exp(-inf - max) = 0, but the
merge still loaded its partial output and multiplied it in, so a NaN
or Inf there turned the merged row into NaN (0 * NaN = NaN). Mask the
value load to rows the range reached.

The empty-range test now fills every empty row's partial output with
1e4, NaN or Inf; the NaN and Inf cases fail without the mask.

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

* lse_merge: add pytest coverage and a Triton benchmark

aiter/ops/triton/README.md asks for a unit test under
op_tests/triton_tests/ and a bench_<op>.py for each Triton wrapper.
lse_merge only had tests in the standalone mha_v4 script.

- op_tests/triton_tests/attention/test_lse_merge.py: compare with a
  torch merge over shapes, head dims, output dtypes and with and
  without the merged LSE; strided views; empty ranges with NaN and Inf
  partials; offsets past 2^31 elements; and each rejected argument.
  The three direct lse_merge tests move here from test_mha_v4.py.
- op_tests/op_benchmarks/triton/bench_lse_merge.py: CUDA-graph timing
  over rotating buffers through do_bench_aiter_triton, on the shapes
  kv_splits="auto" makes or one --shape, with and without the LSE.

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

* mha_v4: read the varlen gate's arch from arch_info

arch_info.get_arch() caches the live device's arch at import, so
Dynamo reads it as a constant. That makes the torch_compile_guard op
around get_gfx_runtime()'s rocminfo probe unnecessary. It still
ignores GPU_ARCHS, which is what the gate needs.

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: Zhuo Su <[email protected]>
* ci: pin FlyDSL to v0.4.1.dev1005

* ci: upgrade FlyDSL to v0.4.2.dev1007

* ci: bump FlyDSL pin to v0.4.2

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: jli-melchior <[email protected]>
Co-authored-by: Cursor <[email protected]>
* [Config] Add gfx950 a8w8 blockscale GEMM tunings for Qwen3-14B-FP8

vLLM runs the non-preshuffled op on gfx950, where this table had gfx942 rows only.

Signed-off-by: xiaofei.zheng <[email protected]>

* [Config] Add the untuned shape list for the gfx950 Qwen3-14B-FP8 a8w8 blockscale rows

Signed-off-by: xiaofei.zheng <[email protected]>

* [Config] Retune the gfx950 Qwen3-14B-FP8 a8w8 blockscale rows against main's dispatch, with FlyDSL

Signed-off-by: xiaofei.zheng <[email protected]>

* [Bugfix] Keep the untuned dispatch for FP16 split-K and non-E4M3 calls in gemm_a8w8_blockscale

Signed-off-by: xiaofei.zheng <[email protected]>

* [Bugfix] Restrict split-K blockscale rows to BF16 output and run their dispatch tests in CI

Signed-off-by: xiaofei.zheng <[email protected]>

* [Bugfix] Run split-K blockscale rows without split-K for non-BF16 output

Signed-off-by: xiaofei.zheng <[email protected]>

---------

Signed-off-by: xiaofei.zheng <[email protected]>
…U and SwiGLU (#6552)

* [FlyDSL] Register a16wmix a16w16 (bf16×bf16) so gfx942 SwiGLU can honour swiglu_limit.

The kernel already clamped SwiGLU; compile/registry never emitted the bf16-W
variant, so Cohere-style QuantType.No fell through to CK and dropped the bound.
Untuned heuristic selects this port when a finite limit is set. gfx942 stage2
keeps main's fx.atomic_add. SiLU is unchanged: its epilogue still ignores the limit.

Signed-off-by: jatseng-ai <[email protected]>
Co-authored-by: Cursor <[email protected]>

* [FlyDSL] Clamp SiLU in a16wmix gemm1 so bf16×bf16 swiglu_limit binds.

Copy mixed_moe's clamp-then-silu_mul_batch into the a16wmix epilogue; do not
put the clamp inside the shared helper. With the a16w16 dtype gate already
open, a finite SiLU limit now routes to this kernel instead of CK.

Co-authored-by: Cursor <[email protected]>

* [fused_moe] Do not log "using 2stage default" when bf16 reroutes to a16wmix.

get_2stage_cfgs logged the CK/1-stage choice before the a16wmix return, so a
limit-set bf16 call printed "using 2stage default" and then launched FlyDSL.
Compute the reroute decision once, skip that line only when the reroute will
return (it logs its own kernel names), and reuse the same flag for the return.
Every other path logs exactly as before.

Co-authored-by: Cursor <[email protected]>

* [tuner] Enumerate a16wmix a16w16 (bf16×bf16) under TUNE_ONLY=flydsl.

gen_flydsl_2stages_task returned early for anything but per_1x32 fp4/fp8
weights, so no tuned row could name the bf16 a16w16 kernels the runtime
selects for BF16 QuantType.No with an active swiglu_limit.

- Admit BF16 QuantType.No SiLU/SwiGLU (g1u1, no doweight) and enumerate
  get_flydsl_stage{1,2}_kernels_a16w16 through the existing a16w-mix branch.
- Time stage1 with waves_per_eu=None, which is what the runtime passes for
  these registry entries (the tuner default of 3 would time another build).
- Stage2 data: build the sorted bf16 intermediate for a16w16 as for a16w4.
  CK stage2 gets the same a2_qt/a2_scale as before.
- Post-process: CK also enumerates these keys, and a16w16 stage1 writes a
  sorted intermediate CK stage2 cannot read. Add an a16w16 marker to the
  dedup and stage1/stage2 merge keys (like v2) so pairs stay homogeneous and
  dedup cannot leave only a mixed pair. Dropped before the CSV.

Co-authored-by: Cursor <[email protected]>

* [test] a16wmix bf16 clamp at H=4096 I=512 E=128 top-8; pin sentinel route.

The bind tests ran at H=256 I=128 E=4 top-2. Add kernel tests at the per-rank
shape the clamped server ran (32 tokens, t16 tile):
- limit=7 vs clamped / unclamped references, with the bound shown reachable
  (routed gate and |up| > 2x limit) and limit=1e9 matching the unclamped ref;
- gate -25 at limit 1.0 matches the asymmetric reference, not symmetric.
Sentinels (None / 0.0 / +inf) now assert ck_moe_stage1 and run_1stage=False
rather than only "not FlyDSL". Black-format the file.

Co-authored-by: Cursor <[email protected]>

* [test] a16wmix bf16 clamp: dict literals for ruff C408

Co-authored-by: Cursor <[email protected]>

* [tuner] Stop enumerating a16w16 stage2 reduce kernels.

bf16 stage2 has no reduce epilogue, so those names atomic-scatter into an unzeroed buffer and fail accuracy.

* [fused_moe] Keep a16w16 atomic when FORCE_REDUCE is set.

BF16 stage2 has no reduce epilogue. Treating it as honoring the runtime
override skipped the output zero-init and the atomic added into stale memory.

Signed-off-by: jatseng-ai <[email protected]>
Co-authored-by: Cursor <[email protected]>

* [fused_moe] Gate a16w16 to gfx942/950 and close the AOT/f16 holes.

Keep sentinels on CK with no AITER_* override. Reject a caller block_size_M
that disagrees with the kernel tile before stage1 runs on the wrong layout.
Register bf16 a16w16 names only, and give AOT a QuantType.No bf16 recipe so
PREBUILD_KERNELS=1 survives the first tuned row.

Co-authored-by: Cursor <[email protected]>

* [test] Fold a16w16 clamp coverage into the existing dispatch file.

Drop the extra test module. Keep the dispatch gates, one small-shape bind
per activation, the Command A shape, and the host tile mismatch.

Co-authored-by: Cursor <[email protected]>

---------

Signed-off-by: jatseng-ai <[email protected]>
Co-authored-by: Cursor <[email protected]>
* [FlyDSL] Add gfx1250 implicit-GEMM conv3d (TDM im2col + WMMA).

Host pre-pads to NDHWC with C/groups aligned to 32; A uses rank-3 TDM
boxes (optional kH×kW patch reuse), B uses 2D TDM tiles, and compute is
WMMA 16x16x32 bf16. Wire flydsl_conv_implicit to the new backend and
extend the op_test keyword surface for gfx1250 tiles and tail blocks.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: BIG_OUT, split-K, dyn_hw, policy/tuner/AOT.

Extend the MVP TDM+WMMA path with 64-bit stores, fp32 atomic split-K,
variable-resolution extents, gfx1250 tile policy, tuned-table lookup
(block_rows), and AOT dispatch; ship a small smoke tuned CSV.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: add wan21/qwenimage VAE tuned configs.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: drop smoke CSV and fix black/ruff.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: cap blocks at 4 waves and make the tuner gate strict

Blocks of 8 or 16 waves return wrong results on gfx1250: re-running the 38
shipped 8/16-wave winners gave wrong elements on 35 of them, a different subset
on every run, while the same shapes are exact with 4-wave tiles. Until the
kernel is fixed, MAX_WAVES = 4 rejects such tiles in
validate_launch_config_gfx1250, the tuned-table lookup ignores them with a
one-time warning, and the heuristic ladder and DEFAULT_TILE drop to 2x2 waves.

The tuner now scores candidates with strict_compare (1.0 on any element outside
tolerance): mp_tuner rounds the error ratio to 4 decimals, which let thousands
of wrong elements pass as errRatio=0. Borrowed candidates must also be legal
gfx1250 tiles. The op test maps the gfx950-sized pinned tiles to the widest
legal gfx1250 tiles, and the tuner README documents the strict gate.

The tuned CSVs are re-tuned under the cap in a follow-up commit.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: match the gfx1250 GEMM pipeline, lift the 4-wave cap

The tap main loop issued the next tile's TDM before the barrier, into the
buffer other waves were still reading (WAR race with num_buffers=2). That is
why 8/16-wave blocks returned a different set of wrong elements on every run.

Replace both bodies with one pipeline that mirrors compile_gemm_a16w16:
prologue of B-1 TDM tiles, an scf.for main loop carrying accumulators and
register-prefetched fragments, tensor_wait((B-2)*2), a drain, and
sched_barrier(0) before the epilogue when B>2. num_buffers (2..8), variant
(bandwidth_bound / compute_bound) and main_loop_unroll are now real knobs,
passed through run_conv3d_gfx1250 and clamped to the LDS / K-tile budget.
_body is @flyc.jit so the AST rewriter lowers the yield-carrying loop; as a
plain helper it is a Python generator and the kernel traces empty.

The kH x kW patch-reuse body is removed for now (patch_reuse is accepted and
ignored on gfx1250), MAX_WAVES goes back to 16, the heuristic ladder regains
a 2x4-wave tile, and the op test runs the pinned tiles unmapped.

Verified on gfx1250 against an fp32 CPU reference, zero elements outside
rtol=atol=2e-2, 3 runs per config: Wan2.1 down_0_1 @368x544, all 918
policy configs; and all 76 shapes of both gfx1250 tuned CSVs, 20313 configs
(CSV tile plus 24 policy tiles x num_buffers 2/3/4 x 3 variants, including
8/16-wave, split-K 2/4 and dyn_hw on/off).

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: retune the VAE tables on the GEMM-matched pipeline

Re-tune both gfx1250 tables (Qwen-Image VAE, Wan2.1 VAE) against the
pipeline from 01509cf.

Every candidate the tuner enumerates for the 76 shapes (7444 configs,
including 2164 8-wave and 689 16-wave) ran 10 times against an fp32 CPU
reference, each output NaN-filled before it was freed: zero elements
outside rtol=atol=2e-2, no NaNs, no hangs.

Per shape, the 5 fastest passing configs by CUDA-event screening plus the
previously committed tile were re-timed with run_perftest, the tuner's own
measurement (conv3d_tune agrees with it to within 1% on two rows). Against
the previously committed tiles on the new pipeline, the winners are 5.5%
(Qwen-Image) and 9.0% (Wan2.1) faster in sum; 8-wave tiles win 19/32 and
17/44 rows, and one Wan2.1 row takes a 16-wave tile.

The us column is high in absolute terms: the card measured the same
kernels 1.0-2.6x slower than it did on 2026-10-21 (same harness, same
toolchain), so the ranking holds but the times do not compare with the
previous table.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: share the N-tail dyn_hw rule with AOT

The runtime turned dyn_hw off when (K / groups) % tile_n != 0 after
calling _dyn_hw_ok_gfx1250, but AOT only called the helper. On the K=3
output convs of both tuned tables (Qwen-Image 1024^2, Wan2.1 482x834) AOT
therefore built a dyn_hw kernel the runtime never requests: those rows
raise under FLYDSL_RUNTIME_RUN_ONLY=1 and JIT on first call otherwise.
Move the rule into _dyn_hw_ok_gfx1250 so both sides use it.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d AOT: build one artifact per row for dyn_hw

gfx1250 dyn_hw launchers still close over the full param, geometry and
launch args, and FlyDSL keys a launch on its closure scalars, so every
resolution and batch size is its own artifact. Deduping dyn_hw jobs
across N/D/H/W left 4 of the 76 tuned rows without one (Qwen-Image 1328^2
rows 16 and 30, Wan2.1 N=4 rows 25 and 40). Key gfx1250 dyn_hw jobs on
the whole row until the launcher is shape-agnostic.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] conv3d test: make 3d_splitk2 tile-aligned for the split-K tail gate

The 32x32 input under a 2x2x2 filter with no padding gives Ho = Wo = 31, so
npq = 2883 is not a multiple of tile_m = 64 and the explicit splitk=2 hit the
split-K tail assertion on gfx950 (and the 2D block tail check on gfx1250).
Use a 33x33 input so Ho = Wo = 32 and the tile divides the problem.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d tuner: prepare operands outside the timed call

On gfx1250 the tuner timed flydsl_conv_implicit on raw operands, so every
timed call also paid run_conv3d_gfx1250's host-side zeros pad, channel pad
to a multiple of 32 and weight pack. The weight pack is memoized, but
run_perftest rotates weight copies, so it missed on every iteration while a
deployed layer pays it once. The GEMM and MoE tuners hand their timed call
ready-made (quantized, shuffled, sorted) operands instead.

Add prepare_operands_gfx1250, which runs those three steps once with the
dispatcher's own helpers, and an optional packed_weight argument to
run_conv3d_gfx1250 that skips the pack. gfx1250 tuner tasks now generate
the prepared operands in generate_data_gfx1250 and time run_conv3d_gfx1250
on them with padding=0; the reference still uses the raw operands. gfx950
is unchanged.

The kernel param is unchanged: for all 7440 candidates of the 76 tuned
shapes the old and new calls build equal params on CPU, and on gfx1250 the
76 tuned configs return bitwise-equal outputs both ways, 3 runs each, with
no element outside rtol=atol=2e-2. The timing A/B against the old call is
still to be measured; the tuned tables are not re-tuned here.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: align the tuner with the GEMM tuners and retune

Align conv3d_tune with the GEMM tuners:
- Time with --warmup/--iters (5/101 by default), which the GEMM tuners pass
  to run_perftest; it ran run_perftest's default of 2 warmups. run_config
  does the same.
- Check against fp32 F.conv3d with an fp32 bias, rounded to bf16 once, the
  reference of op_tests/test_flydsl_conv_implicit.py and the GEMM tuners. It
  was bf16 F.conv3d with the bias rounded to bf16 first.
- run_config uses the base class's err-ratio limit and status format;
  strict_compare still turns any element outside rtol=atol=2e-2 into 1.0, so
  the limit's margin does not loosen it.
Kept as is: errRatio=0 with strict_compare, shape_grouped always on, and the
best-of-3 run_config. Preallocated outputs with NaN init would need an out=
argument on run_conv3d_gfx1250 and are left out.

Retune both gfx1250 VAE tables with this tuner (prepared operands from
3f7d146, so `us` is the kernel alone): all 7440 candidates of the 76 shapes
are within rtol=atol=2e-2 of the fp32 reference, none failed or timed out.
The winner changes on 8/32 Qwen-Image and 18/44 Wan2.1 rows; in the same run
the previous tiles time 0.2% slower in sum on both tables (at most 6.4% on a
row).

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] conv3d tuner: report the tuned kernel time in run_config

With --run_config <tuned_csv>, report each row's tuned `us` as kernel_us
next to the end-to-end time, as the MoE tuner does; the base class then
prints Kernel(us) and E2E(us) side by side. On gfx1250 the two differ by up
to 4.8x on padded shapes, where the entry point's host-side pad dominates.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d tuner: NaN-fill a preallocated output per candidate

run_conv3d_gfx1250 takes an optional out= (written in place; behavior is
unchanged without it). The gfx1250 tuner preallocates the NDHWC output and
passes output_keys=("out",), so mp_tuner NaN-fills it before every candidate
and a kernel that leaves elements unwritten fails strict_compare instead of
inheriting the previous candidate's result.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] gfx1250 conv3d: honor split-K and the shared host contracts

The gfx1250 backend accepted splitk in its public signature but the entry
point never forwarded it, and the tuner adapter deleted it before the call.
The tuned row could therefore record a split-K that was not the one executed,
while AOT compiled a third value from that row.

- Forward the public splitk argument to the gfx1250 backend.
- Resolve split-K in one gfx1250 helper that applies the tile-tail and
  BIG_OUT gates and distinguishes a caller's explicit request from a
  tuned/automatic value; use it from the runtime, the tuner and AOT so the
  tuned metadata, the executed kernel and the prepared artifact agree.
- Keep the compile-only gate in the gfx1250 dispatch so a launcher warmed in
  the same process is not dispatched with the AOT CPU probe arguments.
- Require a zero strict error count in run_config instead of letting the
  historical CSV error ratio forgive a current mismatch.
- Reject gfx1250 grid.y values above the shared MAX_GRID_YZ limit, as the
  gfx950 grid builder already does.

Verified on gfx1250 (FlyDSL 0.4.1): strict accuracy on representative NDHWC
and NCDHW shapes with no split-K, bitwise-identical outputs against the
unmodified kernel for those cases, and graph-replay time unchanged within
noise. The added host-side resolution costs a few percent on ~10-40us
launches only.

* [FlyDSL] gfx1250 conv3d: pin the split-K contract in op_tests

Every numerical case in this file compares values, so a split-K that changes
between the tuned row, the launched kernel and the AOT artifact was invisible
to it. Add one assertion set to the existing script, run unfiltered like the
compile-key and block-rows checks:

- no_tail, x=(1,64,1,8,768): an explicit split-K of 2 must be the value the
  kernel is compiled with, and the automatic value must equal the flat
  resolution the tuner would record.
- row_tail, x=(1,64,1,3,2048): Ho=3 is not a multiple of block_rows=8, so
  split-K must fall back to 1, and an explicit incompatible request must be
  rejected rather than silently changed.

Checked on gfx1250 with FlyDSL 0.4.1: the current tree passes all six checks
(no_tail auto=3 with the kernel at split-K=2; row_tail auto=1 with the kernel
at split-K=1 and explicit 3 raising). The tree before the shared resolver
fails the same function outright, so the check is red on the regression it
targets.

* [FlyDSL] gfx1250 conv3d: keep the split-K contract check on gfx1250

op_tests/test_flydsl_conv_implicit.py runs on every supported arch, but the new check captured the gfx1250 compile hook and the gfx1250 resolver. On gfx950 the same shapes take the MFMA path, whose split-K is derived inside _implicit_param_from_problem, so nothing was captured and the check failed there.

Skip the check when the backend is not gfx1250, with a log line, matching how the file already skips cases it cannot exercise.

* [FlyDSL] gfx1250 conv3d: load operands through the tiled TDM atom

Replace the N-D make_tdm_atom + imm_offset pair with the tiled
make_tiled_tdm_atom + tdm_partition path the other gfx1250 kernels use.

Weights are K-tile aligned, so one descriptor covers the whole channel range,
the N tail is clamped by the view extent, and each round indexes the K tile it
needs. Input taps shift the base by whole rows and columns, which is not a
multiple of the tile, so that side builds its descriptor per issue from a
shifted base.

The LDS tiles are unchanged, which also keeps the padding: make_tiled_tdm_atom
derives pad_interval/pad_amount from the LDS layout, and lds_k already carries
LDS_PAD.

Behaviour changes to measure on gfx1250: early_timeout is not part of the tiled
API, and the input side now rebuilds its descriptor every round.

* [FlyDSL] gfx1250 conv3d: fix tiled weight partitioning

Pass the complete padded B tile as partition mode zero and retain a singleton rest mode, matching the gfx1250 GEMM load path. Keep the A descriptor/offset path while migrating the weight side independently.

Validated two representative shapes on a07 GPU0 and d7 GPU1 with FlyDSL 0.4.1: ten NaN-prefilled accuracy checks per version and three bitwise baseline comparisons per shape. Full configuration coverage and performance testing remain separate follow-ups.

* [FlyDSL] gfx1250 conv3d: load the input gather through the tiled TDM atom

Build the A atom per issue from the runtime tap offset, so the input side no longer uses the legacy N-D atom and no make_tdm_atom call remains in the kernel. B keeps the tiled weight path from the previous commit.

* [FlyDSL] conv3d: provide get_gfx in the runner unit test

_run_ci() now calls check_splitk_contract(), which reads the get_gfx module global that _load_backend() installs. tests/test_conv3d_ci_modes.py drives _run_ci() directly, so the name was undefined and the job failed with NameError on the default-dispatch case.

Patch script.get_gfx to a fixed arch in that test; the contract check is gfx1250-specific and returns early on gfx950, so no GPU backend is needed.

---------

Co-authored-by: root <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: root <[email protected]>
@vgokhale
vgokhale merged commit ad0554a into release/v0.1.28 Nov 5, 2026
@vgokhale
vgokhale deleted the hotfix/v0.1.28-post1 branch November 5, 2026 03:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.