Skip to content

[FlyDSL] Tiled-copy refactor + cleanup: swiglu/silu_fq/qk_norm_rope/fp8_mqa - #4606

Merged
coderfeli merged 6 commits into
mainfrom
flydsl-kernel-cleanup
Aug 7, 2026
Merged

coderfeli merged 6 commits into
mainfrom
flydsl-kernel-cleanup

Conversation

@coderfeli

Copy link
Copy Markdown
Collaborator

Summary

Modernizes four FlyDSL element-wise / per-token kernels onto the layout-API tiled copy (make_layout_tv / make_tiled_copy + partition_S/D), replaces raw MLIR (arith/ArithValue/GTensor) with the fx.* surface, and trims comments/dead code. Net −285 LOC across the touched files.

kernel change correctness perf
swiglu_and_mul scalar dword gather → TV-tiled copy byte-exact ~1.06–1.10× faster (6.0→6.5 TB/s)
silu_and_mul_fq gate/up loads + packed fp4/fp8/bf16 store → TV-tiled copy byte-exact (output + scales) ISA-neutral
qk_norm_rope_quant GTensor → base-folded tiled copy (Q/KV/SWA ring+paged) op-test + byte-exact ISA-identical
fp8_mqa_logits raw dialects → fx.*, comment trim byte-exact ISA-identical

Approach

  • The "interleave" in swiglu/silu is just a (N0, 2, NLANE) layout — gate/up are strided views, output is contiguous; one TV layout partitions all three.
  • GTensor.get_llvm_ptr(off) is base + off; replaced by folding the per-token/row offset into the pointer (inttoptr(ptrtoint(ptr)+off), i32-safe voffsets) + a buffer-tensor view.
  • Cross-thread reductions (shuffle_xor amax / RMSNorm sumsq) are preserved: the TV layout keeps thread t owning contiguous [t*VEC, (t+1)*VEC), so quant-block/head threads stay shuffle-adjacent.
  • Kept raw ops only at genuine boundaries: the emit_mx_e8m0_scale / cvt_pk_fp8_f32 raw-IR builders, rocdl.mfma, index-typed loop bounds, and the single-op integer max/min/ceildiv helpers (fx .select costs 2 ops vs v_max_i32; float .maximumf is wrong for ints). The sparse swizzled E8M0 scale write (1 byte / 32 cols) stays a scalar scatter.

Validation (gfx950, FlyDSL disk cache ON)

Every kernel: byte-exact vs the original (separate-module compile + torch.equal) across its full config matrix, plus ISA diff as the perf gate (the shared GPU is too noisy for wall-clock). swiglu's tiled copy genuinely changes the ISA (scalar→vector, measured faster); the other three are ISA-identical/neutral. qk_norm also passes its op test.

@coderfeli
coderfeli requested a review from a team August 6, 2026 11:05
@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 4606 --add-label <label>

@coderfeli
coderfeli force-pushed the flydsl-kernel-cleanup branch 2 times, most recently from 758a3fe to e08aac8 Compare August 6, 2026 13:25
coderfeli and others added 4 commits August 6, 2026 13:31
make_layout_tv/make_tiled_copy + partition_S/D over the (N0,2,NLANE) interleave:
gate/up strided views, contiguous output, one TV layout for all three -> 128b
gate+up loads, swiglu in f32, 128b store. fx.Pointer (base-folded, i32-safe);
wrapper passes ptr_arg. No raw arith (min via -max(-x,-lim)).

gfx950: byte-exact incl. clamp/tail edges; ~1.06-1.10x faster (6.0->6.5 TB/s).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Gate/up loads (interleaved + separated) and the packed fp4/fp8/bf16 value store
via make_tiled_copy/partition_S/D, runtime per-row base folded into the pointer.
All raw arith/buffer_ops/_to_raw eliminated: constants->fx literals, scalar
loads->indexed fx loads, E8M0 scatter->indexed i8 store; emit_*/cvt_pk wrapped
in fx. shuffle_xor amax preserved (thread t owns contiguous [t*VEC,+)).

gfx950: byte-exact (output + scales) across quant{fp4,fp8,none} x layout x
act{silu,swiglu,situv2} x inter_dim; on-par-to-faster.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace GTensor Q/KV in/out + SWA kv_write (ring+paged) with base-folded
buffer-tensor views + make_tiled_copy/partition_S/D. All raw
arith/buffer_ops/_to_raw eliminated: operators/.select/.to for index math,
fx buffer tensors for scalar loads/stores, emit_*/cvt_pk/rcp args via .ir_value().
shuffle_xor RMSNorm + RoPE preserved.

gfx950: op test passes; byte-exact across quant/group/head-dim/token-tail +
ring/paged; ISA leaner (327->323); perf within ~1%.

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

Convert the whole op surface to fx: maxsi/minsi->.select, ceildivui->unsigned //,
scf.ForOp->range(), scf.IfOp writer-guard->local @flyc.jit (`if pred: helper()`),
all _to_raw removed, index_cast dropped. Drop the per-op arith.MulFOp/addf/maximumf
fastmath annotations and rely on the fast_fp_math compile hint (already set in
_DEFAULT_COMPILE_HINTS) -> arith fully eliminated. Only rocdl.mfma remains
(hand-packed i64 fp8 operands; fx.gemm would require rewriting the operand path).

gfx950: byte-exact vs the explicit-fastmath version across configs (hint applies
the same ambient "fast"); no perf regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderfeli
coderfeli force-pushed the flydsl-kernel-cleanup branch from e08aac8 to 7cd4848 Compare August 6, 2026 13:31
… no kernel")

swiglu_and_mul_kernel now takes fx.Pointer args (matching the tiled-copy
refactor + flydsl_swiglu_and_mul_interleaved), so the AOT epilogue precompile
must pass _ptr_view_safe(x)/_ptr_view_safe(out), not raw tensors — otherwise the
COMPILE_ONLY trace faults (ptrtoint on a memref) and the MOE cktile_epilogue_swiglu
job emits no kernel. The silu path already used pointer views; this aligns swiglu.

Verified: _precompile_epilogue_to_cache("swiglu", inter_dim) now compiles a kernel
for inter_dim 384/512/768 (COMPILE_ONLY, gfx950).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@zufayu
zufayu requested a review from yadaish August 7, 2026 01:26
@coderfeli
coderfeli requested review from lalala-sh and zhiding512 and removed request for yadaish August 7, 2026 03:13
@coderfeli
coderfeli merged commit 62a3308 into main Aug 7, 2026
38 of 42 checks passed
@coderfeli
coderfeli deleted the flydsl-kernel-cleanup branch August 7, 2026 06:19
coderfeli added a commit that referenced this pull request Aug 8, 2026
Resolves the fp8_mqa_logits.py conflict: main's #4606 tiled-copy cleanup
rewrote the file (dropping _to_raw) while this branch moved it into the
kernels/mqa_logits/ subpackage. Kept main's body, re-pathed the shim
import to '..tensor_shim'.
coderfeli added a commit that referenced this pull request Aug 29, 2026
…ndex

Second cleanup pass, byte-exact ISA gated (net -83 LOC on top of the
first pass):

- fused_compress_attn.py / fused_compress_attn_hca.py: collapse the
  explicit arith.AddFOp/MulFOp/subf(fastmath=fm_fast) float layer + its
  feeder vector.extract/arith.extf/ArithValue to plain fx operators.
  Proven redundant: the module already compiles with fast_fp_math=True +
  unsafe_fp_math=True, so plain fx `+`/`*`/maximumf emit byte-identical
  ISA. Verified on 6 kernel variants (hca_main, csa_main ksplit,
  csa_indexer fp8; hca_compress_forward, hca_norm_rope_scatter bf16/fp8)
  -- all 21_final_isa.s byte-identical. Prove-then-apply caught 3 real
  ISA-drift cases, kept raw + documented: GPT-J RoPE subtract (default
  non-fastmath flags -> fx fuses differently, 123-line drift), the
  softmax-padding cmpf(OEQ)+select (unordered-compare+cndmask drift), and
  the fp8/fp4 ue8m0 scale bit-trick.

- flash_attn_func_gfx1201.py: fx.Index -> fx.Int64 where byte-identical
  (12 of 23). Kept 11 that drift or fail to compile: signed<->unsigned
  divide (index udiv/urem vs i64 sdiv/srem), index-typed loop-induction /
  cmpi / select peers. Gated via stage-18 lowered LLVM-dialect MLIR diff
  (RDNA WMMA not executable on gfx950).

Gate: gfx950 correctness err_pct=0 on all non-preexisting cases (the 3
legacy(NW=1)/prefill-bs32 cache_scale failures confirmed pre-existing via
git-stash A/B); per-variant ISA byte-identical; black+ruff clean.

qk_norm fx.copy sites reviewed: the 8 single-atom loads are the skill
§7b degenerate case (kept as fx.copy, not promoted); the tileable ones
were already make_tiled_copy via main's #4606.

Co-Authored-By: Claude Fable 5 <[email protected]>
coderfeli added a commit that referenced this pull request Aug 29, 2026
Third pass (net -72 LOC), targeting _to_raw/ArithValue/.ir_value/raw
arith·vector·buffer_ops. Every change byte-exact ISA gated; anything
that drifted the ISA was reverted (not forced).

- hca: ArithValue 34->0, _to_raw 23->3, arith 71->31, vector 18->8. The
  integer offset math is now fx-typed throughout (buffer_ops natively
  accepts fx Numeric offsets); buffer_ops primitives kept because
  create_buffer_resource's base_byte_offset (64-bit descriptor rebase,
  guards a documented 4 GiB 32-bit-offset overflow) has no
  make_buffer_tensor equivalent. Caught: fx Int32 >> is arithmetic (ashr)
  vs the original logical shift -> fixed via fx.Uint32; no fx int max/min
  -> kept arith.maxsi/minsi.
- fused_compress_attn: vector.*->0, arith.extf->0, arith.trunci->0 (all
  bf16->f32 / fp8 byte-store casts). Proven NOT byte-exact: converting a
  single arith.remui->fx % inside the loop-carried softmax scf.for drifts
  the ISA 533 lines (identical opcode histogram, pure SSA-order/regalloc
  reshuffle) -> reverted. Its offset+buffer_ops layer stays raw by proof.
- qk_norm: dropped 5 redundant .ir_value() bridges into from_elements.
  The 28 buffer_ops are the layer the FlyDSL maintainers' own #4606
  full-fx-surface refactor deliberately retained; kept.
- gfx1201: dropped 7 .ir_value() bridges, rocdl.exp2->fx.rocdl.exp2
  (IR-identical on 3 configs; the high-level fx.exp2 form drifts 35 lines).
- mfma_epilogues: _is_group_b now a plain fx Boolean predicate (@flyc.jit
  if + .select, no .ir_value re-wrap). Remaining .ir_value bridges feed
  raw memref.load/vector.extract in caller callbacks (empirically
  load-bearing); the value-yielding load-select scf.IfOp is irreducible
  (fx.select would double LDS traffic).

What stays raw is now the proven floor: ops that drift the ISA if
converted (loop-carried offset math, RoPE subtract, cmpf(OEQ)+select,
fp8/fp4 bit-tricks, gfx1201 signed-cmp/divide) and genuine no-fx-form
boundaries (buffer_ops base_byte_offset, cvt_pk_fp8, rcp/rsqrt/exp2,
emit_mx_e8m0_scale, raw WMMA, caller raw-memref callbacks).

Gate: gfx950 compress_attn err_pct=0 (3 pre-existing cache_scale failures
unchanged, A/B-confirmed) + qk_norm 465/0; per-variant ISA byte-identical
(compress_attn x4, hca x3, qk_norm x5, mfma_epilogues 20/20); gfx1201
stage-18 IR byte-identical x3 configs; black+ruff clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
coderfeli added a commit that referenced this pull request Sep 1, 2026
* [FLYDSL] attn-aux kernels: fx.* modernization cleanup

Surgical fx.* migration of four FlyDSL attention-auxiliary kernels,
behavior-preserving with byte-exact / ISA-parity gating:

- fused_compress_attn.py: vector.*->fx.Vector, ArithValue index math
  ->fx typed-int operators, dead consts/banner removed (net -25 LOC).
- fused_compress_attn_hca.py: LDS pointer index math ->fx operators
  (ISA byte-identical on all 3 compiled variants).
- qk_norm_rope_quant.py: copy_atom_call->fx.copy (8), fx.Index->fx.Int64
  (7), llvm rcp intrinsic + bare rocdl.*->fx.rocdl.*, dead import dropped
  (ISA byte-identical on all 5 gfx950 variants).
- flash_attn_func_gfx1201.py: ArithValue.select/_bitcast_i32->fx ops,
  dead ArithValue import removed (LLVM-IR parity verified on 3 configs).

Gate (gfx950 local + IR dump for gfx1201):
- compress_attn combined sweep: all main paths err_pct=0; the 2
  legacy(NW=1) failures confirmed pre-existing (identical on base).
- qk_norm: 465 passed / 0 failed; perf equal-or-better.
- gfx1201: RDNA target, not executable here; gated via byte-identical
  fully-lowered LLVM-dialect MLIR (stage-18) diff.
- Perf medians within noise on all gfx950 kernels.

Left legacy on purpose (per skill): buffer_ops scalar-base+per-thread
loads with no layout form, non-default-fastmath arith.*FOp float compute,
raw WMMA/MFMA plumbing, and the gfx1201 to_llvm_ptr AS-change (drifts ISA,
needs real hardware to land).

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

* [FLYDSL] attn-aux: deep fx collapse under fast_fp_math + gfx1201 fx.Index

Second cleanup pass, byte-exact ISA gated (net -83 LOC on top of the
first pass):

- fused_compress_attn.py / fused_compress_attn_hca.py: collapse the
  explicit arith.AddFOp/MulFOp/subf(fastmath=fm_fast) float layer + its
  feeder vector.extract/arith.extf/ArithValue to plain fx operators.
  Proven redundant: the module already compiles with fast_fp_math=True +
  unsafe_fp_math=True, so plain fx `+`/`*`/maximumf emit byte-identical
  ISA. Verified on 6 kernel variants (hca_main, csa_main ksplit,
  csa_indexer fp8; hca_compress_forward, hca_norm_rope_scatter bf16/fp8)
  -- all 21_final_isa.s byte-identical. Prove-then-apply caught 3 real
  ISA-drift cases, kept raw + documented: GPT-J RoPE subtract (default
  non-fastmath flags -> fx fuses differently, 123-line drift), the
  softmax-padding cmpf(OEQ)+select (unordered-compare+cndmask drift), and
  the fp8/fp4 ue8m0 scale bit-trick.

- flash_attn_func_gfx1201.py: fx.Index -> fx.Int64 where byte-identical
  (12 of 23). Kept 11 that drift or fail to compile: signed<->unsigned
  divide (index udiv/urem vs i64 sdiv/srem), index-typed loop-induction /
  cmpi / select peers. Gated via stage-18 lowered LLVM-dialect MLIR diff
  (RDNA WMMA not executable on gfx950).

Gate: gfx950 correctness err_pct=0 on all non-preexisting cases (the 3
legacy(NW=1)/prefill-bs32 cache_scale failures confirmed pre-existing via
git-stash A/B); per-variant ISA byte-identical; black+ruff clean.

qk_norm fx.copy sites reviewed: the 8 single-atom loads are the skill
§7b degenerate case (kept as fx.copy, not promoted); the tileable ones
were already make_tiled_copy via main's #4606.

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

* [FLYDSL MOE] mfma_epilogues: drop dialect-module params, scf.IfOp→@flyc.jit

Replicate the ASM-identical cleanup blueprint (ref 1e0a4da) on the
current shared MoE epilogue helper:

- Drop the injected MLIR dialect-module parameters (arith/vector/gpu/scf/
  range_constexpr) from default_epilog/c_shuffle_epilog/mfma_epilog;
  import them at module scope instead. Update the sole caller
  (mixed_moe_gemm_2stage_common.py): remove 32 pass-through kwargs across
  the default_epilog + 6 c_shuffle_epilog sites.
- arith.constant(index)/cmpi/select → fx.Index/fx comparison/fx.Boolean
  .select; vector.load_op → Vec.load.
- scf.IfOp → @flyc.jit if/else (4 conversions: group-write branch + two
  row-guards). The one value-yielding load-select scf.IfOp is kept
  (documented): @flyc.jit can't merge a both-branch result to the caller.

Left legacy on purpose (matching the reference): the now-unused _if_then
SCF-then compat shim and the always-true `scf is not None` guards.

Gate: 20/20 distinct mixed_moe kernel ISAs byte-identical (21_final_isa.s,
git-stash BEFORE/AFTER), incl. sbm128 split-LDS variants exercising the
group-write @flyc.jit + kept scf.IfOp + row-guards. moe_2stage correctness
green (logits_diff unchanged); black+ruff clean.

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

* [FLYDSL] attn-aux + mfma_epilogues: drive raw IR to the proven floor

Third pass (net -72 LOC), targeting _to_raw/ArithValue/.ir_value/raw
arith·vector·buffer_ops. Every change byte-exact ISA gated; anything
that drifted the ISA was reverted (not forced).

- hca: ArithValue 34->0, _to_raw 23->3, arith 71->31, vector 18->8. The
  integer offset math is now fx-typed throughout (buffer_ops natively
  accepts fx Numeric offsets); buffer_ops primitives kept because
  create_buffer_resource's base_byte_offset (64-bit descriptor rebase,
  guards a documented 4 GiB 32-bit-offset overflow) has no
  make_buffer_tensor equivalent. Caught: fx Int32 >> is arithmetic (ashr)
  vs the original logical shift -> fixed via fx.Uint32; no fx int max/min
  -> kept arith.maxsi/minsi.
- fused_compress_attn: vector.*->0, arith.extf->0, arith.trunci->0 (all
  bf16->f32 / fp8 byte-store casts). Proven NOT byte-exact: converting a
  single arith.remui->fx % inside the loop-carried softmax scf.for drifts
  the ISA 533 lines (identical opcode histogram, pure SSA-order/regalloc
  reshuffle) -> reverted. Its offset+buffer_ops layer stays raw by proof.
- qk_norm: dropped 5 redundant .ir_value() bridges into from_elements.
  The 28 buffer_ops are the layer the FlyDSL maintainers' own #4606
  full-fx-surface refactor deliberately retained; kept.
- gfx1201: dropped 7 .ir_value() bridges, rocdl.exp2->fx.rocdl.exp2
  (IR-identical on 3 configs; the high-level fx.exp2 form drifts 35 lines).
- mfma_epilogues: _is_group_b now a plain fx Boolean predicate (@flyc.jit
  if + .select, no .ir_value re-wrap). Remaining .ir_value bridges feed
  raw memref.load/vector.extract in caller callbacks (empirically
  load-bearing); the value-yielding load-select scf.IfOp is irreducible
  (fx.select would double LDS traffic).

What stays raw is now the proven floor: ops that drift the ISA if
converted (loop-carried offset math, RoPE subtract, cmpf(OEQ)+select,
fp8/fp4 bit-tricks, gfx1201 signed-cmp/divide) and genuine no-fx-form
boundaries (buffer_ops base_byte_offset, cvt_pk_fp8, rcp/rsqrt/exp2,
emit_mx_e8m0_scale, raw WMMA, caller raw-memref callbacks).

Gate: gfx950 compress_attn err_pct=0 (3 pre-existing cache_scale failures
unchanged, A/B-confirmed) + qk_norm 465/0; per-variant ISA byte-identical
(compress_attn x4, hca x3, qk_norm x5, mfma_epilogues 20/20); gfx1201
stage-18 IR byte-identical x3 configs; black+ruff clean.

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

* [FLYDSL] migrate buffer_ops -> make_buffer_tensor (attn + moe_sorting)

Relaxed gate this pass from byte-exact-ISA to correctness + perf-neutral
(median-of-5/CUDA-graph, revert >2%), which unlocks the buffer_ops
migration and the raw-op conversions that only rescheduled the ISA.

buffer_ops -> fx.rocdl.make_buffer_tensor via a moe_reduce-style helper
that folds the 64-bit descriptor base into the pointer
(inttoptr(ptrtoint(get_iter)+base_i64)) BEFORE make_buffer_tensor, so the
4 GiB / 32-bit-offset overflow guard holds by construction:
- fused_compress_attn_hca.py: 44 -> 2. Also finished the raw-dialect
  collapse: ArithValue 34->0, vector 8->0, and the RoPE subtract +
  softmax cmpf/select + int max/min -> fx (all correctness+perf verified;
  RoPE even faster). Net large LOC drop.
- fused_compress_attn.py: 76 -> 4. (The _build_kernel offset math and the
  RoPE/softmax float ops stay raw here -- PROVEN gate failures: the former
  regresses hca_main +8.9%, the latter breaks the fp8/fp4 e8m0 cache_scale
  bit-exact check by <=1 ULP. Kept raw, bisected.)
- moe_sorting_kernel.py: 82 -> 4; ArithValue 33->0, fx.Index 13->0,
  index_cast 30->0, trunci 2->0. GPU-probed that make_buffer_tensor's V#
  descriptor preserves the .select(idx,0x7FFFFFFF) OOB-drop semantics.

The survivors are proven boundaries, not oversights:
- 2/4 per file feed the off-limits _common fp8 emitter (raw V# descriptor
  + scf.IfOp) that can't take a fx buffer-tensor without editing siblings.
- moe_sorting's 4: uint8 byte-addressed scatter -- an i8 byte-mode store
  at the sentinel FAULTS (hipErrorIllegalAddress) instead of dropping, so
  it stays guarded on buffer_ops (probe-confirmed).

Critical units trap found+fixed (hca first, applied everywhere): the fx
buffer-tensor offset scales by the tensor's elem_ty, but buffer_load
scaled by the LOAD dtype -- a bf16 tensor read as i32 dwords got a 2x
offset (err 0.57). Fix: pass elem_ty = load dtype per site (bf16-dword
paths->Int32, state->Float32, cos/sin->BFloat16, byte-scatter->Int8).

Tiled-copy / layout-algebra evaluated for the regular loads and correctly
NOT applied: the f32 state loads are descriptor-rebased dynamic per-K row
gathers (a TV layout can't express a dynamic gather), the bf16 loads are
dword-packed bit-extracts, and the one affine site already lowers to a
single buffer_load (partition machinery = net LOC up, skill 7b).

Gate: compress_attn combined err_pct=0 (3 pre-existing cache_scale
failures A/B-confirmed unchanged) + moe_sorting 48/48 bit-exact vs torch
ref + GPU functional smoke (all tokens correctly routed); perf neutral on
all variants; black+ruff clean.

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

* [FLYDSL] moe_sorting: last 4 buffer_ops -> guarded direct ptr store

The 4 survivors were the uint8 byte-scatter stores in p0_scatter/p0v2,
already wrapped in `if valid:` / `if is_mine:` guards -> they only ever
fire in-bounds, so the V# descriptor's OOB-drop was never used (the
sentinel path is dead under the guard, which is why an unguarded byte
store faulted at the sentinel). A plain guarded LLVM store suffices and
needs neither buffer_ops nor make_buffer_tensor.

Added `_i8_global_ptr(tensor)` (inttoptr(ptrtoint(get_iter(t))) as i8
Global) and store `ws_i8[byte_off] = val_i8` inside the existing guard
(i8 element == byte, so the byte offset is the element index directly).
buffer_ops: 4 -> 0, import removed.

Gate: 48/48 cold bit-exact vs torch ref (all paths incl. the mask+padding
cases that drive the byte scatter); perf neutral (CUDA-graph interleaved
A/B; an apparent +1-2% was measurement-window drift, present on the
unchanged oneshot path too); black+ruff clean.

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

* [FLYDSL] scatter emitter: buffer_ops -> direct global ptr stores

The shared nm-asm fp8 scatter emitter (emit_group_fp8_nm_asm_scatter in
fused_compress_attn_common.py) used no OOB — it writes plan-bounded,
in-bounds kv_cache / k_rope slots — so the V# descriptor was unnecessary.
Switch it to direct global pointer stores built from an i64 block base,
and drop the 6 create_buffer_resource descriptors the callers fed it.

- fused_compress_attn_common.py: emitter takes out_base_i64 / krope_base_i64
  (i64 block base) + cache_base / krope_base (i32 within-block byte off)
  instead of raw V# resources; _global_ptr(base_i64, byte_off, elem, align)
  = fx.inttoptr over base+off, .store(...). 6 buffer_store -> 0. Rest of
  the emitter migrated to fx (cvt_pk_fp8, fx.Vector, typed ints); 3 guarded
  scf.IfOp kept (§5: plain `if` doesn't rewrite inside an imported helper),
  non-default-fastmath arith.MulFOp kept.
- callers pass out_base_i64=fx.Int64(fx.ptrtoint(fx.get_iter(kv_cache))) +
  fx.Int64(block_base): fused_compress_attn.py (2 sites) + hca (1) — now
  0 buffer_ops (dead import dropped); fused_compress_attn_gfx1250.py +
  hca_gfx1250.py (1 each).

Gate: gfx950 compress_attn err_pct=0 on all emitter-driven cases (hca_main
+ csa_main nm_asm_fp8 nope/scale/rope; cache_scale bit-exact) — the 3
pre-existing legacy(NW=1)/prefill-bs32 cache_scale failures unchanged;
gfx1250 CSA + HCA scatter cross-COMPILE clean (execution not validatable
here). black+ruff clean.

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

* [FLYDSL] dedup buf_tensor/buf_load/buf_store into _common

The _buf_tensor/_buf_load/_buf_store V#-helper trio was byte-identical in
fused_compress_attn.py and fused_compress_attn_hca.py. Move it to the
shared fused_compress_attn_common.py (as buf_tensor/buf_load/buf_store),
import via alias in both callers, drop the now-unused bare `ptrtoint`
imports. Net -~55 LOC, single source of truth.

Gate: compress_attn err_pct=0 (3 pre-existing cache_scale failures
unchanged); black+ruff clean.

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

* [FLYDSL] drop dead vecVf32 kwarg from the scatter emitter

The emitter builds its store vector directly from rotated_lane; the
vecVf32 (T.vec(VEC,f32)) parameter was unused. Remove it from the
signature and all 5 call sites, and the 3 now-dead local vecVf32
assignments in the wave64 callers (gfx1250 callers still use their local
vecVf32 for vector.from_elements, kept).

Gate: gfx950 compress_attn err_pct=0 (3 pre-existing unchanged); gfx1250
csa+hca cross-compile clean; black+ruff clean.

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

* [FLYDSL] attn-aux: fx.max/min, unsigned div, buffer_tensor dedup, deeper IR port

Continue the attn-aux fx.* modernization across the compress-attn kernels:

- Dedup buffer-tensor creation: fused_compress_attn_common.buf_tensor now
  delegates the view + descriptor build to tensor_shim.ptr_buf_tensor (added by
  #5112), keeping the n_elems/base_i64 fold. 0 ISA diff (ptrtoint/inttoptr folds).
- arith.maximumf/minimumf -> fx.max/fx.min (byte-identical for floats).
- Signed integer div/rem on non-negative index/offset chains -> unsigned via
  fx.Uint32 // and % (divui/remui). Byte-exact output; div-site IR only.
- Broader low-level port: vector.extract/bitcast/from_elements -> fx.Vector,
  fx.Index -> fx.Int32/Int64, ArithValue/_to_raw + arith.constant/muli/addi/subi/
  cmpi/select/andi -> fx operators, guard-only scf.IfOp -> python if; dead consts
  dropped. qk_norm _idiv -> unsigned divui.

Kept raw (justified, each ISA-gated): fastmath-sensitive softmax/rope/quant float
arith and the -inf-sentinel maximumf/cmpf (plain fx ops pick up fast_fp_math and
drift/corrupt the guard), buffer_ops base_byte_offset rebase (no make_buffer_tensor
form), value-yielding/large-body scf.IfOp (schedule drift), maxsi/minsi (no fx
signed-int form), and rocdl/llvm/cvt_pk/extract_strided_slice boundaries.

Validation: per-variant ISA byte-identical on the gfx1250/hca_gfx1250 wave32
kernels (IR-only; not executable on gfx950) and the wave64 buffer-dedup; gfx950
consolidated test_flydsl_compress_attn err_pct=0 on csa_main/hca_main/csa_indexer
(+fp4)/nm-asm-fp8/ksplit, decode+prefill. Only the pre-existing legacy(NW=1)
cache_scale cross-checks fail (A/B-confirmed on the clean baseline).

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

* [FLYDSL] attn-aux: drop buf_* wrappers, MulFOp->*, scf->@flyc.jit

Address review feedback on the compress-attn cleanup:

- Remove the buf_tensor/buf_load/buf_store wrappers from
  fused_compress_attn_common. buf_tensor duplicated tensor_shim.ptr_buf_tensor;
  call sites now use ptr_buf_tensor directly (base_byte_offset callers fold the
  offset into the pointer). buf_load/buf_store were thin, mis-named add_offset+
  load/store shims -> inlined at all 74 (CSA) + 45 (HCA) sites. V# descriptor
  byte-identical (make_buffer_tensor(max_size=True) pins num_records).
- arith.MulFOp/AddFOp/subf(fastmath=fm_fast) -> * / + / -. These kernels set the
  fast_fp_math compile hint, so the ambient fastmath is already "fast" and the
  operators carry fastmath<fast> identically; fm_fast param dropped from the
  shared emitter + all callers (incl. the two gfx1250 files).
- Remaining CSA arith.* -> fx (constants, cmp, select, unsigned div/rem, offset
  math); _common scf.IfOp/_if_then guard -> local @flyc.jit if; scf/ir imports
  dropped (fused_compress_attn_common now raw-IR-free).

Kept raw (each a proven byte-exact boundary): the -inf-sentinel softmax
maximumf/cmpf guard and loop-carried ring-index math (must NOT take ambient fast
fastmath), GPT-J rope subf + fp4-nib muls feeding e8m0 quant, maxsi/minsi (no fx
form), and cvt_pk/emit_*/rocdl intrinsics.

Validation: 10/10 kernel ISAs byte-identical (cold recompile); gfx950
test_flydsl_compress_attn 75 pass / err_pct=0 across csa_main/hca_main/
csa_indexer(+fp4)/nm-asm-fp8/ksplit, decode+prefill (only the pre-existing
legacy(NW=1) cache_scale cross-checks fail, A/B-confirmed).

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

* [FLYDSL] attn-aux: collapse redundant _to_raw round-trips

Values were being _to_raw()'d to store/pass, then re-wrapped fx.Float32/Int32 at
use -- a redundant round-trip. Keep them fx end-to-end and drop both halves.

- fused_compress_attn.py (CSA): _to_raw 72 -> 45. fexp_f32 now takes fx (wraps
  once inside for exp2); _load_bf16_vec_then_f32/_load_f32_vec return fx lists;
  comp_lane / am_safe / slot_in_block / wid / lid / scale_group_idx /
  cache_base / krope_base and the ksplit fp8-clamp kept fx.
- fused_compress_attn_gfx1250.py: _to_raw 94 -> 85 (the int index round-trips:
  ring/ape_row/in_row/comp_pos/wid/lid/_col_off_for_k). The raw float MulFOp
  layer stays (gfx1250 fastmath exception), so its _to_raw operands remain.

Remaining _to_raw all feed a genuine raw op (exp2/rcp/cvt_pk, emit_mx_e8m0_scale,
the -inf softmax maximumf/cmpf guard, loop-carried range/arith, maxsi/minsi,
padding arith.select, buffer stores).

Validation: ISA byte-identical (CSA 6/6 kernels; gfx1250 6/6 configs stage-18 +
final ISA) -- pure type-wrapper removals fold pre-ISA; gfx950
test_flydsl_compress_attn 75 pass / err_pct=0 (only the pre-existing legacy(NW=1)
cache_scale cross-checks fail).

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

* [FLYDSL] attn-aux: deeper arith->fx (maxsi/minsi, select, offset math) + drop mfma scf

CSA (fused_compress_attn.py): arith 70 -> 24 (code), _to_raw 46 -> 30, redundant
fx.Int32 wraps 100 -> 83.
- arith.maxsi/minsi -> fx.max/fx.min (they dispatch to maxsi/minsi for signed
  ints, byte-identical); arith.select -> .select; cmpi/subi/addi/index_cast/
  remui -> fx operators; arith.constant -> fx typed; collapse freed _to_raw; drop
  fx.Int32 wraps of already-typed values (strides, slot_in_block, ...).
- RoPE arith.subf/MulFOp/AddFOp KEPT raw: MEASURED -- the operator/fma
  contraction (v_pk_fma_f32) is 3.8% SLOWER on csa_main bf16 (latency-bound tail,
  tight VGPR), neutral on fp4. Raw form is both byte-exact and faster.
- -inf-sentinel softmax maximumf/cmpf kept raw (fx would take ambient fast
  fastmath and corrupt the guard); emit_f32_to_e2m1/cvt_pk/exp2/rcp raw boundaries.

mfma_epilogues.py: remove the value-yielding scf.IfOp (conditional LDS read) ->
select the source buffer (arith.select on the two memref bases) + a single load;
drop _if_then + the scf import + dead scf-availability guards. ISA: identical
ds_read count (no doubled LDS traffic), perf-neutral. (@flyc.jit value-return was
tested and DRIFTS numerically -- rejected.)

Validation: CSA 6/6 kernel ISAs byte-identical; gfx950 test_flydsl_compress_attn
75 pass / err_pct=0 (only pre-existing legacy(NW=1) cache_scale fails);
test_flydsl_moe_a8w4 34/34 (both epilog paths, normal + forced-split).

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

* [FLYDSL] attn-aux: scf/vector/fx.Index -> 0 where byte-exact; RoPE operator form

Sweep scf, vector.*, and fx.Index toward zero across the attn kernels, ISA-gated.

- gfx1250 + hca_gfx1250: guard-only scf.IfOp -> plain `if` (AST-rewrite in the
  @flyc.kernel body); vector.bitcast/from_elements -> fx.Vector, and the
  dwords>4 store-split vector.extract_strided_slice -> fx.Vector.from_elements
  (folds to identical ISA). Result: hca_gfx1250 scf=0/vector=0; gfx1250 vector=0,
  scf=3 (see floor). All configs final-ISA byte-identical.
- flash_attn_func_gfx1201: fx.Index -> explicit width (Uint64 for div/mod so it
  keeps udiv/urem; Int64 for addresses). ISA byte-identical (gfx1201 cross-dump).
- fused_compress_attn RoPE: raw arith.subf/MulFOp/AddFOp -> operator `e*c-o*s` /
  `e*s+o*c`. Root cause found: the raw `subf` was built WITHOUT fastmath=fm_fast
  (inconsistent), which blocked FMA contraction; the operator picks up the
  ambient fast_fp_math -> fastmath<fast> and contracts. Operator form is strictly
  fewer v_pk ops (bf16/fp4) / identical (ue8m0); the previously-claimed 3.8%
  regression does NOT reproduce (0.5%, noise; kernel is memory-bound). arith
  28->16, _to_raw 31->24.

Measured floors (kept raw, each verified): gfx1250 value-yielding `_if_tail`
(conditional Phase-2 softmax update -- @flyc.jit value-return reschedules the ISA
1599->870 lines; a select would read speculative prefetch garbage);
mfma_epilogues fx.Index (values cross the callback into caller memref.load/store
subscripts, which require MLIR `index` -- converting fails to compile).

Validation: gfx950 test_flydsl_compress_attn 75 pass / err_pct=0 (only
pre-existing legacy(NW=1)); test_flydsl_moe_a8w4 34/34; gfx1250/gfx1201 files
final-ISA byte-identical (compile-only).

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

* [FLYDSL] attn-aux: CmpFPredicate -> fx (fastmath-none scope), float consts -> fx.Float32

fused_compress_attn.py: remove the raw arith.cmpf(CmpFPredicate.OEQ,...) -inf
sentinel compares. The subtlety: the raw -inf guard is MIXED fastmath -- the
maximumf is fastmath<fast> (ambient), but the cmpf oeq carries NO fastmath. So:
  m_new = fx.max(m_old, score)              # ambient fast == raw maximumf
  with fastmath(None): is_first = m_old == c_neg_inf   # no-fast == raw cmpf oeq
(Wrapping maximumf in fastmath(None) is WRONG -> NaN-propagating v_maximum3.)
Drops the CmpFPredicate import. Also dropped 5 loop-bound _to_raw wraps
(range(..., init=) takes typed fx directly): _to_raw 24->19. Kept _to_raw feeding
exp2/rcp/emit_*/the raw softmax state lists.

fused_compress_attn_hca.py: float arith.constant -> fx.Float32 (c_log2e/c_eps/
c_inv_D; fexp_f32 takes fx, wraps once at exp2). arith 6->3 (kept c_neg_inf +
c_zero_f32 for the -inf guard, fm_fast for rsqrt).

Validation: ISA byte-identical (CSA 12/12 variants, hca 3/3; origin MLIR confirms
maximumf fastmath<fast> + cmpf no-fastmath == raw form); gfx950
test_flydsl_compress_attn 75 pass / err_pct=0 (only pre-existing legacy(NW=1)).

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

* [FLYDSL] attn-aux hca: scope the -inf sentinel compares to fastmath(None)

_softmax_step_padded's two `== -inf` sentinel compares picked up the
ambient fast_fp_math hint when they moved from raw arith.cmpf to the fx
`==` operator. `fast` carries ninf, so LLVM folds `x == -inf` to false
and deletes the guarding selects: the 3 v_cmp_neq_f32 + v_cndmask pairs
present in hca_compress_forward on main are absent from the built kernel.

When a wave's first Phase-1 iteration is padding, m_old and score_k are
both -inf, so m_old - m_new is NaN and exp2 propagates it into the
compressed KV output. Repro: a plan row with position < ratio-1 and
window_len > 0 gives max-abs-delta NaN (512 elements) vs 2.7109375 on
main. The shipped test plan always sets position = (s+1)*ratio-1, so
is_pad is unreachable there and the sweep stays green.

fused_compress_attn.py already scopes its four equivalent compares with
`with fastmath(None)`; this file was missed. Apply the same treatment
(the gfx1250 siblings keep the raw arith.cmpf and are unaffected).

After the fix hca_compress_forward's instruction histogram is identical
to origin/main and the 3 guard pairs are back; the only remaining ISA
delta is a benign operand commutation on an address add from the
buffer_ops -> ptr_buf_tensor migration.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
jin-amd pushed a commit to jin-amd/aiter that referenced this pull request Sep 11, 2026
_fn_to_fnuz_i64 splits an 8-byte fp8 pack into two 32-bit halves, patches
FN -0 (0x80) to +0 in each, then recombines. ROCm#4606 rewrote the recombine
from an explicit arith.ExtUIOp to a plain fx.Int64(...), which sign-extends.

Every fp8 byte >= 0x80 is a negative value, so the top byte of a half
routinely sets bit 31; the sign extension then floods the upper word with
ones and the OR corrupts the pack. fx.Int64(fx.Uint32(x)) is already the
zero-extend idiom used elsewhere in this file (the stride/base-pointer
path added by the same PR), so use it here too.

Only reachable on gfx942, where convert_q_fn/convert_kv_fn are set, and
only for e4m3fn operands -- which is what vLLM's sparse-MLA indexer feeds
this kernel. e4m3fnuz is unaffected and makes a clean control.

The bug is silent: compute volume is unchanged, so throughput and latency
look normal while the indexer's top-k selection degrades.

Measured on MI325X (gfx942), against an fp32 torch reference:

  e4m3fnuz  max_rel 9.9e-4  (unchanged, control)
  e4m3fn    max_rel 6.6e+5  ->  9.5e-4

Top-k index overlap vs reference (M=256, N=4096, k=2048; 50% is random):

  before 71.15%  ->  after 99.95%

matching v0.1.19, the last release before ROCm#4606.

Co-authored-by: Cursor <[email protected]>
jin-amd added a commit to jin-amd/aiter that referenced this pull request Sep 11, 2026
_fn_to_fnuz_i64 splits an 8-byte fp8 pack into two 32-bit halves, patches
FN -0 (0x80) to +0 in each, then recombines. ROCm#4606 rewrote the recombine
from an explicit arith.ExtUIOp to a plain fx.Int64(...), which sign-extends.

Every fp8 byte >= 0x80 is a negative value, so the top byte of a half
routinely sets bit 31; the sign extension then floods the upper word with
ones and the OR corrupts the pack. fx.Int64(fx.Uint32(x)) is already the
zero-extend idiom used elsewhere in this file (the stride/base-pointer
path added by the same PR), so use it here too.

Only reachable on gfx942, where convert_q_fn/convert_kv_fn are set, and
only for e4m3fn operands -- which is what vLLM's sparse-MLA indexer feeds
this kernel. e4m3fnuz is unaffected and makes a clean control.

The bug is silent: compute volume is unchanged, so throughput and latency
look normal while the indexer's top-k selection degrades.

Measured on MI325X (gfx942), against an fp32 torch reference:

  e4m3fnuz  max_rel 9.9e-4  (unchanged, control)
  e4m3fn    max_rel 6.6e+5  ->  9.5e-4

Top-k index overlap vs reference (M=256, N=4096, k=2048; 50% is random):

  before 71.15%  ->  after 99.95%

matching v0.1.19, the last release before ROCm#4606.

Co-authored-by: Cursor <[email protected]>
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.

3 participants