Skip to content

[FlyDSL] replace ptr_rsrc and buffer ops low level api use - #5303

Merged
coderfeli merged 29 commits into
mainfrom
flydsl-moe-ptr-buf-tensor
Sep 9, 2026
Merged

coderfeli merged 29 commits into
mainfrom
flydsl-moe-ptr-buf-tensor

Conversation

@coderfeli

@coderfeli coderfeli commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

clean all vector.py usage.
reduce buffer ops usage.
clean scf, vector in moe.
all same perf.

… aux kernels

Move the MoE gather-reduce and fused route/quant/scatter kernels, and
tensor_shim's GTensor, off buffer_ops and onto ptr_buf_tensor buffer views, so
loads and stores go through the layout API instead of hand-computed byte
offsets. ptr_rsrc is gone and tensor_shim no longer imports buffer_ops.

- ptr_buf_tensor now accepts a raw i64 base (buf_base_i64), so a descriptor can
  be narrowed to one row without materialising a pointer, and takes unit_stride
  for a wide access at an arbitrary element offset. That case is real: a
  gather-reduce row base is row*model_dim*2, which is only dword-aligned when
  model_dim = 2 (mod 4), so a dwordx4 store there can only claim dword
  alignment.
- The quant loop's per-lane addressing collapses to a single lane-unit index
  shared by the hidden load, the payload store and the pre-quantized read, with
  each access width carried by its tensor's layout. Five now-unused SSA
  constants drop out with it.
- Two s_buffer_load sites stay on buffer_ops -- there is no scalar-load copy
  atom -- but take the V# from the tensor via get_buffer_rsrc, so there is
  still one view per pointer.
- TensorBase was eight pure forwarders onto a lazily built TensorView; it now
  subclasses TensorView and binds load/store as its impls (65 -> 19 lines).

Validated: MoE aux suite 616/616; gather-reduce 216/216 across split_k, route
weight dtypes and the num_valid_tokens paths; the quant loop byte-exact against
baseline on hardware; qk_norm_rope_quant err=0 on 18 shapes and fp8_mqa_logits
bit-identical. ISA A/B over 37 modules (gfx950/gfx1250/gfx1201): identical
memory-op mix and zero spills everywhere, SGPR unchanged, no occupancy-granule
regression, -18 instructions net; the remaining diffs are register allocation
and VOPD packing churn. gather-reduce wall-clock is neutral (0.983-1.023 over
two trials, inside the 1.8% same-build noise); the scatter kernel is
gfx1250-only and cannot be benchmarked on this host.

Co-Authored-By: Claude <[email protected]>
@coderfeli
coderfeli requested a review from a team September 7, 2026 05:23
@coderfeli
coderfeli marked this pull request as draft September 7, 2026 05:24
@github-actions

github-actions Bot commented Sep 7, 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:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: 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 5303 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

@github-actions github-actions Bot changed the title [FlyDSL][WIP] replace ptr_rsrc and buffer ops low level api use [FlyDSL] [WIP] replace ptr_rsrc and buffer ops low level api use Sep 7, 2026
@github-actions github-actions Bot added the FlyDSL label Sep 7, 2026
coderfeli and others added 15 commits September 7, 2026 10:24
Move the MoE gather-reduce, fused route/quant/scatter and causal-conv1d kernels,
plus tensor_shim's GTensor, off raw buffer resources onto ptr_buf_tensor buffer
views, so loads and stores go through the layout API instead of hand-computed
byte offsets. ptr_rsrc is gone, tensor_shim no longer imports buffer_ops, and
the only buffer_ops left in these kernels is create_llvm_ptr for atomic RMW.

- ptr_buf_tensor accepts an fx pointer, a tensor/memref, or a raw i64 base
  (buf_base_i64), so a descriptor can be narrowed to one row without
  materialising a pointer. unit_stride expresses a wide access at an arbitrary
  element offset: a gather-reduce row base is row*model_dim*2, only
  dword-aligned when model_dim = 2 (mod 4), so a dwordx4 there can claim only
  dword alignment.
- The quant loop's per-lane addressing collapses to one lane-unit index shared
  by the hidden load, the payload store and the pre-quantized read, each access
  width carried by its tensor's layout; five now-unused SSA constants go with it.
- buf_scalar_load wraps the one access with no layout form: s_buffer_load, whose
  result must stay in an SGPR to keep a per-row descriptor uniform. The layout
  API has no scalar spelling and ROCDL exposes no op to wrap, so it takes the
  V# off the tensor and calls the intrinsic.
- causal_conv1d is one element per access throughout, so each buffer gets a
  single view typed by its element and t[i] is the whole access.
- TensorBase was eight pure forwarders onto a lazily built TensorView; it now
  subclasses TensorView and binds load/store as its impls (65 -> 19 lines).

Validated: MoE aux suite 616/616; gather-reduce 216/216 across split_k, route
weight dtypes and the num_valid_tokens paths; quant loop byte-exact against
baseline on hardware; causal_conv1d 11/11 with byte-identical ISA;
qk_norm_rope_quant err=0 on 18 shapes and fp8_mqa_logits bit-identical. ISA A/B
over 37 modules (gfx950/gfx1250/gfx1201): identical memory-op mix and zero
spills everywhere, SGPR unchanged, no occupancy-granule regression, -18
instructions net; remaining diffs are register allocation and VOPD packing.
gather-reduce wall-clock neutral (0.983-1.023 over two trials, inside the 1.8%
same-build noise); the scatter kernel is gfx1250-only and cannot be benchmarked
on this host.

Co-Authored-By: Claude <[email protected]>
The position and batch-id reads are single-element loads through a resource
used for nothing else, so each becomes a typed view indexed directly; the
i64->i32 position narrowing folds into the fx.Int32 that already wrapped it.

The rest of this kernel stays on buffer_ops for now: the vector load/store
helpers take the resource as a parameter and are fed GTensor(...).rsrc by their
callers, their widths are computed as VEC//2 / vec//4 (so a 3-dword access with
no copy atom is reachable), and the stores are byte-offset with cache
modifiers. That is a coupled change, not a mechanical one.

Validated: 18/18 shapes err=0, and 24/24 modules match on ISA (23 byte-identical,
1 scheduling-equivalent) with register counts unchanged and no spills.

Co-Authored-By: Claude <[email protected]>
buf_scalar_load reimplemented what buffer_ops.buffer_load(is_scalar=True)
already does -- the ptr8->v4i32 bitcast, the byte scaling and the intrinsic
call -- and did not even remove the buffer_ops import from its only caller,
which still needs create_llvm_ptr. The scatter kernel goes back to the
existing scalar path via the tensor's V#.

kernels_common._create_llvm_ptr was a copy of buffer_ops.create_llvm_ptr with
a different default address space, in a module that already imports
buffer_ops; it now delegates. The dedup cannot go the other way: buffer_ops
importing kernels_common would invert that dependency into a cycle.

Validated: scatter ISA unchanged over 19 gfx1250 modules, MoE aux 200/200,
causal_conv1d 11/11.

Co-Authored-By: Claude <[email protected]>
The atomicrmw builder needs a raw !llvm.ptr<n>, which no layout op produces, so
these sites hand-built one via buffer_ops.create_llvm_ptr with the LLVM address
space hardcoded. fx.inttoptr gives a typed fly pointer and to_llvm_ptr lowers
it, letting the backend resolve the space: Shared is 2 in fx terms but lowers to
!llvm.ptr<3>, which is exactly the number that was being written by hand.

The emitted IR is unchanged -- llvm.inttoptr i64 -> !llvm.ptr<1> feeding
atomicrmw add ptr addrspace(1) ... syncscope("agent") monotonic, align 4.

moe_route_maps and moe_contiguous_psum are now free of buffer_ops entirely.
moe_fused_route_quant_scatter keeps it only for the two s_buffer_load sites,
which have no copy-atom form.

Validated: MoE aux 616/616 with zero errors, gather-reduce 216/216, and the
scatter kernel's ISA unchanged across 19 gfx1250 modules.

Co-Authored-By: Claude <[email protected]>
Both had a single kind of user and no layout form, so they move out rather than
get wrapped:

- s_buffer_load becomes tensor_shim.buf_scalar_load. It is the one access with
  no copy-atom spelling -- t[i] and every BufferCopy* atom lower to a VGPR
  buffer load, and the result here has to stay in an SGPR to keep a per-row
  descriptor uniform. Its only two callers were in the scatter kernel, so the
  is_scalar branch and _ptr8_to_v4i32 leave buffer_ops entirely.
- create_llvm_ptr becomes kernels_common.create_llvm_ptr, built with
  fx.inttoptr + to_llvm_ptr. That drops the hand-written LLVM address-space
  number: Shared is 2 in fx terms and lowers to !llvm.ptr<3>, which is exactly
  what the call sites were writing by hand. One public definition replaces the
  copy that was in buffer_ops and the private duplicate in kernels_common.

moe_route_maps, moe_contiguous_psum and moe_fused_route_quant_scatter are now
free of buffer_ops.

Validated: MoE aux 420/420 with zero errors, gather-reduce 216/216, and ISA
unchanged -- 19 gfx1250 scatter modules and all 3 fmha modules byte-identical.

Co-Authored-By: Claude <[email protected]>
It is a raw LLVM GEP builder, not a buffer op, and its 14 callers all want a
plain pointer rather than a descriptor. It joins create_llvm_ptr in
kernels_common, which is where the raw-pointer helpers now live.

buffer_ops needed it for one internal byte GEP in from_memref; that is inlined
rather than imported back, since kernels_common imports buffer_ops and the
dependency must not become a cycle. The moved copy also drops its own reach
into buffer_ops._unwrap_value, and uses kernels_common's T, where T.i8 is
already a type rather than a factory.

buffer_ops is now just buffer load/store and resource creation:
  __all__ = [buffer_load, buffer_store, create_buffer_resource,
             create_buffer_resource_from_addr]

Validated: MoE aux 420/420 zero errors, gather-reduce 216/216, causal_conv1d
11/11, qk_norm 18/18 err=0, the EP dispatch/combine and mega_moe stage kernels
still compile, and ISA unchanged -- 19 gfx1250 scatter modules and all 3 fmha
modules byte-identical.

Co-Authored-By: Claude <[email protected]>
It claimed behavior matches upstream, which stopped being true when the
raw-pointer helpers and the uniform-load path moved out.

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

Moving get_element_ptr required two duplications to avoid a cycle -- an inlined
byte GEP in buffer_ops and a private _unwrap_ir in kernels_common -- which is a
worse trade than leaving it where it was. It goes back to buffer_ops, and both
duplicates go away with it.

The real duplication was elsewhere: four places had grown the same
to_llvm_ptr(inttoptr(PointerType.get(i32, space), addr)) sequence -- the shared
helper plus open-coded copies in moe_route_maps, moe_contiguous_psum and
moe_fused_route_quant_scatter. They all call kernels_common.create_llvm_ptr now,
and the local _g_i32_pt / lds_i32_pt builders are gone.

create_llvm_ptr takes either the LLVM number (1 global / 3 LDS) or an
fx.AddressSpace, since one caller passes each and a mismatch was a KeyError at
build time rather than anything the type checker would catch.

Validated: MoE aux 200/200 zero errors, gather-reduce 216/216, causal_conv1d
11/11, qk_norm 18/18 err=0, and ISA unchanged -- 19 gfx1250 scatter modules and
all 3 fmha modules byte-identical.

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

Move the single-access-width buffers in the mega_moe kernels off buffer_ops and
onto fx.rocdl.make_buffer_tensor + layout views (via the existing gemm_util
helpers), keeping buffer_ops only where it is still the right tool.

quant.py is fully migrated. mega_moe_stage2.py migrates its four single-width
scalar read buffers. dispatch.py migrates 65 of 111 sites.

Left on buffer_ops deliberately, each verified by ISA diff:
  - rsrc_dst (stage2): sparse P2P scatter accessed at mixed widths (1B scale /
    8B payload / 16B bf16). A layout descriptor carries the access width, so
    (buffer, elem, width) combinations do not CSE; migrating multiplies
    descriptors and spills registers.
  - dispatch remote-scale buffers: accessed at both width-4 and width-1.
  - gemm2.py bq_rsrc: scalar-base raw-address load carrying a predication mask
    with no clean layout form.

Gated by compile-only ISA diff (memop multiset + VGPR/SGPR + spill markers) on
megamoe_stage1/stage2 and the quant kernels: all byte-identical except
per_1x32_mx_quant_fp4 (VGPR 42 -> 41). No register spills introduced.

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

aiter/ops/flydsl/kernels/vector.py was a compatibility shim kept when upstream
FlyDSL removed flydsl.expr.vector: it re-implemented five wrappers
(from_elements, store, extract, load_op, bitcast) with auto-unwrapping, plus a
star re-export of the raw vector dialect. FlyDSL 0.3.2 covers all five with the
first-class fx.Vector surface, so the shim is now dead weight that keeps kernels
on a raw-MLIR idiom and hides type errors until trace time.

All call sites migrate:
  vector.extract(v, static_position=[K])  -> fx.Vector(v)[K]
  vector.from_elements(T.vec(n,ty), e)    -> fx.Vector.from_elements(e, dtype)
  vector.bitcast(T.vec(n,ty), src)        -> fx.Vector(src).bitcast(dtype)
  vector.store(val, mr, [i], alignment=N) -> fx.Vector(val).store(mr, [i], ...)
  vector.load_op(vec_ty, mr, [i])         -> fx.Vector.load(vec_ty, mr, [i])

from_elements/bitcast require a Numeric class rather than an ir.Type, so element
types go through fx.Numeric.from_ir_type(); .load keeps its full vector type.

Also in this change:
  - mfma_preshuffle_pipeline.py: drop 20 unreachable functions (the
    load_b_raw_*/unpack_b_*/lds_load_pack_k32 family, zero references
    repo-wide), 1231 -> 454 lines, and prune the stale __all__ entries.
  - The pipeline no longer takes injected `vector`/`arith` module parameters;
    six signatures become keyword-only and their mixed_moe call sites follow.
  - preshuffle_gemm.py: migrate its three epilogue buffers to
    make_buffer_tensor + fx.copy (ISA-identical: VGPR 126, SGPR 38, no spills).
  - A partial raw-arith cleanup in mixed_moe_gemm_2stage_common.py.

Two families were deliberately left raw. scf -> Python control flow does not
work here: the kernel builds IR eagerly, so a Python `if` never lowers to scf.if
and fx.Boolean.__bool__ raises during tracing. LDS/SmemAllocator is owned by the
separate "migrate mixed MoE 2-stage LDS to fly shared storage" change. Unsigned
cmpi, logical shrui and index-typed constants stay raw because converting them
would change signedness or silently widen index to i64.

Care is needed with ArithValue vs Numeric: scalar ir.Values auto-cast to
ArithValue, whose .bitcast takes an ir.Type and which has no .to(), whereas fx.*
helpers return Numeric. Converting ops piecemeal broke the a4w4 fp4-quant path
(a chain the a8w4/a16wfp4 tests do not reach); those conversions are reverted so
each dataflow chain stays internally consistent.

Validation: AOT compile 569/569 kernel variants; a8w4 34/34 and a16wfp4 12/12;
the a4w4 fp4-quant benchmark path exits clean. Perf on dsv4 (7168/512, E384,
topk6) at token 16384 is unchanged: stage1 1023.1/1023.3 us before vs
1019.8/1023.6 us after, stage2 within 0.2%.

Net -993 lines.

Co-Authored-By: Claude <[email protected]>
Brings in #5317 ("migrate mixed MoE 2-stage LDS to fly shared storage"), which
touches the same two files as the vector.py shim removal.

Conflict resolution (24 hunks) takes main's side throughout: #5317 replaces the
LDS memref API (fx.Vector.load / .store on a memref + an explicit vec_ty) with
the pointer API (fx.ptr_load / fx.ptr_store on lds_ptr), which supersedes the
shim migration's version of those same statements. The dead-code deletion and
the dropped injected vector/arith parameters in mfma_preshuffle_pipeline.py are
preserved (they auto-merged cleanly).

Two fixups on top of main's side:
  - main's LDS A-tile load still calls vector.extract(), the shim this branch
    deletes. Replaced with fx.Vector indexing: bitcast(fx.Int64) then [0]/[1],
    dropping the now-needless .ir_value().
  - dropped a dead `T.vec(vec16_elems, x_elem)` expression statement and the
    vec2_i64 / f32_t locals left unused by the resolution.

Validation: AOT compile 569/569 kernel variants; a8w4 34/34 and a16wfp4 12/12;
the a4w4 fp4-quant path exits clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
Full review of the branch against main turned up no correctness defects; these
are the leftovers it did find.

  - mixed_moe_gemm_2stage_common.py: remove two dead `T.vec(...)` expression
    statements in gemm2 and the vec8_elems / vec4_elems locals that only fed
    them. These came in with the LDS shared-storage change and are the gemm2
    siblings of the `T.vec(vec16_elems, x_elem)` statement already dropped
    during the merge.
  - mixed_moe_gemm_2stage_common.py: spell the two remaining
    `arith.index_cast(T.i32, row)` as `fx.Int32(row)` to match the ~30 identical
    conversions elsewhere in the file. Same emitted op.
  - mega_moe_gfx1250/combine.py: drop the `_V1I32()` helper, unreferenced since
    its two callers moved to fx.Numeric.from_ir_type(T.i32).

Verified during the review, with no changes required: offset units are preserved
across every buffer_ops migration (the width-1 sites index identically, and
quant.py's width-4 sites divide the old element offsets exactly); OOB/num_records
semantics are unchanged; bitcast lane counts reproduce the original widths; and
no ArithValue/Numeric receiver mismatches remain. A COMPILE_ONLY ISA A/B against
origin/main is identical in memop multiset and registers with zero spills for
mega_moe stage1/stage2, preshuffle_gemm, and the three quant kernels
(per_1x32_mx_quant_fp4 is 1 VGPR better).

Gates: AOT 569/569; a8w4 34/34 and a16wfp4 12/12; a4w4 fp4-quant path clean;
ruff and black clean.

Co-Authored-By: Claude <[email protected]>
…-tensor layout API"

Restores aiter/ops/flydsl/kernels/mega_moe/{dispatch,quant,mega_moe_stage2}.py to
their state on main, dropping the buffer_ops -> buffer-tensor migration.

These are multi-GPU EP kernels. They could only be validated here by compile-only
ISA comparison with dummy addresses (which was clean: identical memop multiset and
registers, no spills, one VGPR better in per_1x32_mx_quant_fp4) — they were never
executed multi-GPU. Taking them out keeps this PR to the parts that have real
runtime coverage.

mega_moe_gfx1250/combine.py is deliberately NOT reverted: its change is the
fx.Vector migration, not the buffer_ops one, and main's version still has seven
references to the deleted vector.py shim.

Gates after revert: AOT 569/569; a8w4 34/34 and a16wfp4 12/12; a4w4 fp4-quant
path clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
@coderfeli
coderfeli marked this pull request as ready for review September 8, 2026 09:34
coderfeli and others added 8 commits September 8, 2026 09:39
Restores the uniform/SGPR scalar-load path (and its `_ptr8_to_v4i32` helper)
that "retire buffer_ops' raw-pointer and scalar-load paths" moved out to
tensor_shim.buf_scalar_load. Kernels that have not been migrated to the
buffer-view API yet still reach it through buffer_ops.buffer_load, so removing
the parameter breaks them.

Code is identical to main's; only the module docstring differs, now recording
why the path stays. tensor_shim.buf_scalar_load remains the preferred entry
point for migrated kernels.

Gates: AOT 569/569; a8w4 34/34 and a16wfp4 12/12; a4w4 fp4-quant clean; ruff and
black clean.

Co-Authored-By: Claude <[email protected]>
Converts the raw arith dialect to the fx surface where the emitted code is
provably unchanged: 447 -> 344 raw arith ops.

  - index_cast 25 -> 0 via fx.Index(...), which maps to MLIR index and so is
    type-preserving (fx.Int64 would have widened index -> i64).
  - shrui 10 -> 0 via fx.Uint32 operands, where >> lowers to a logical shift.
    Plain >> on a signed value would have emitted shrsi.
  - cmpi 31 -> 7 and andi 21 -> 6, again typing operands as fx.Uint32 so that <
    lowers to ult rather than slt.
  - select 10 -> 4, and ori/shli/subi to operators.

Every batch was gated on ISA equality across six modules (three gemm1 variants,
two gemm2 variants, the reduction kernel), comparing memop multiset and
VGPR/SGPR/spill counts. All six stayed byte-identical throughout.

Left raw, with reasons:
  - arith.index constants: a blanket conversion segfaults the backend. Bisected
    to k_base_idx, an index value reassigned and carried across the eager
    mainloop, where a Numeric instead of an ArithValue breaks codegen. Only the
    two pure arithmetic-factor positions were converted.
  - llvm.StoreOp: fx.ptr_store takes no alignment or nontemporal argument, and
    these are nontemporal global streaming stores. The existing fx.ptr_store
    sites here are all LDS, where the hint is irrelevant.
  - The fp4-quant e2m1 block (maximumf, maxsi, TruncIOp and its cmpi/select/andi)
    is the chain whose earlier conversion shipped a bug and was reverted.
  - scf: this kernel builds IR eagerly, so a Python if never lowers to scf.if.
  - buffer_ops: scalar-base, per-thread-offset loads with no layout form.

Gates: AOT 569/569; a8w4 34/34 and a16wfp4 12/12; a4w4 fp4-quant path clean;
ruff and black clean. Net -27 lines.

Co-Authored-By: Claude <[email protected]>
…te/quant scatter

The fx.Vector migration made `fx.Vector(v)[i]` return a Numeric, and three
`llvm.fabs.f32` calls pass that straight into `llvm.call_intrinsic`. The raw llvm
dialect does not auto-unwrap (unlike flydsl.expr.rocdl / .arith), so every
grouped-MoE kernel failed to build with

    Operand 0 of operation "llvm.call_intrinsic" must be a Sequence of Values

Unwrap with .ir_value() at the three sites.

This regressed the whole grouped-MoE AOT build (222 ok on main -> 0 ok) and was
missed because the gate used until now, aot/flydsl/moe.py, does not reach these
kernels; aot/flydsl/grouped_moe.py does. Both are now part of the gate.

Verified against main by dumping every grouped-MoE module: 164/164 identical
memop multiset, and pre-session-branch -> HEAD is 164/164 identical VGPR too, so
the shim migration is register-neutral here.

Gates: grouped_moe AOT 222/222; MoE AOT 569/569; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
Restores this kernel to main's buffer_ops implementation. The migration kept the
memop multiset identical and introduced no spills, but it moved register
pressure enough to cross occupancy thresholds on the gfx1250 grouped-MoE
kernels:

  108 -> 158  moe_fused_quant_preshuffle_routeks_fd7168_r1_fp4_pk8_srctk6_noKS
  114 -> 156  moe_fused_route_quant_scatter_md7168_tk_1_r1_fp4_pk8_basem768
  170 -> 196  moe_fused_route_quant_scatter_md7168_tk_1_r1_fp8_pk8_basem768

122 of 164 modules differed in VGPR. Judging the migration on memops and spills
alone had missed this. After the revert all 164 modules match main exactly:
0 VGPR differences, 0 memop differences, 0 spills.

Kept on top of main's version:
  - the fx.Vector migration of its six vector.py shim sites, so the deleted shim
    stays deleted, with .ir_value() on the three llvm.fabs operands (raw llvm
    does not auto-unwrap Numeric)
  - tensor_shim.ptr_rsrc, restored because this kernel needs it again
  - the two create_llvm_ptr call sites now use kernels_common.create_llvm_ptr
    (fx-based, backend-resolved address space) rather than reinstating the
    hardcoded buffer_ops version

Gates: grouped_moe AOT 222/222; MoE AOT 569/569; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

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

Restores the ptr_buf_tensor migration reverted in the previous commit, but only
for the buffers where it costs nothing. All 164 gfx1250 grouped-MoE modules now
match main exactly: 0 VGPR differences, 0 memop differences, 0 spills.

Root cause of the earlier regression, found by bisecting one buffer at a time:
the whole +50/+42/+26 tail came from migrating the hidden/payload SOURCE load in
_emit_quant_block_loop, specifically the wide pk8 access (16B per lane, dwordx4)
routed through a copy atom and a make_fragment_like fragment. The fragment's
register bundle survives into the store pass, and because a layout descriptor
carries its access width, the pk8 view cannot fold the way the buffer_ops
raw-SSA vec_width=4 load does. Measured in isolation:
  caller sites + scale-byte store  -> 0 modules differ
  + payload store                  -> 115 improve, ~8 pk8 modules regress +1..+4
  + hidden load                    -> the full 108->158 / 114->156 / 170->196 tail

Migrated (all verified neutral incrementally): the single-width caller-site
accesses across all five builders -- topk_ids, g2l_lut, weight_in, gather_w,
expert_row_base, topids_to_rows, counter, masked_m, num_valid_routes,
row_starts, and the persistent kernel's count/starts/topids_to_rows, with
is_scalar loads going to buf_scalar_load -- plus the e8m0 scale byte store.

Left on buffer_ops: the nine payload/hidden/src_scale sites in the quant core,
which share one width-agnostic V# across pk8 dwordx4, fp8 dwordx2 and byte
accesses. A comment records why. This matches the earlier finding that only
per-kernel migration of single-access-width buffers is safe.

moe_gather_reduce, migrated the same way in this branch, was already VGPR-neutral
and served as the positive control.

Gates: grouped_moe AOT 222/222; MoE AOT 569/569; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

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

Raw scf ops 30 -> 6.

An earlier attempt at this concluded a Python `if` could not lower here and
reverted. That was incomplete. The reason it failed is that this file builds IR
eagerly: `_emit_moe_gemm1` / `_emit_moe_gemm2` are plain helpers driving
`ir.InsertionPoint(...)` by hand, and they are merely *called* from the
@flyc.kernel body, so their `if` statements are never seen by the AST rewriter
and just run as Python.

The fix is the documented idiom for branches with side effects: put the branch
body in a helper and dispatch it from a nested @flyc.jit, whose typed `if` does
get rewritten into scf.if. Applied to all nine guarded regions -- the two tid
prologues, the scale-writer store, the fused_read row guard, and the gemm1/gemm2
blk/expert/format nests, with the last collapsing to
`if blk_valid and exp_valid:` plus `const_expr(heterogeneous_b)`.

Where a branch condition was a raw i1 from `arith.andi`, it is wrapped in
fx.Boolean only at the dispatch, leaving the raw value intact for the loop carry
that still consumes it.

Also drops the `_if_then` contextmanager and its scf.YieldOp fallback, which had
no callers anywhere, and the contextlib import it needed.

Left raw: the two persistent-loop scf.ForOps and the two YieldOps that carry
their state. Each is the outer loop of an eager builder whose body is emitted
under a manual InsertionPoint with no indentation, and range()/range_constexpr
only emit scf ops when the body is inside an AST-rewritten function; converting
either means re-indenting ~2200 lines and restructuring the loop carry.

Gated on ISA equality after every batch, across three gemm1 variants, two gemm2
variants and the reduction kernel: all six byte-identical throughout, so the
jit-nested scf.if inlines to exactly the previous code.

Gates: MoE AOT 569/569; a8w4 34/34 and a16wfp4 12/12; a4w4 fp4-quant clean;
ruff and black clean.

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

gemm_a16w16_gfx950_utils.py: scf 3 -> 0, raw vector 2 -> 0.
  - the hand-built scf.WhileOp spin-wait in `wait_until_initialized` becomes a
    Python `while cur == 0:` inside the @flyc.jit body, with cur typed so the
    compare and the loop carry work; the acquire-scoped atomic load stays raw.
  - vector.extract / vector.from_elements become fx.Vector indexing and
    fx.Vector.from_elements; the result feeds a raw llvm.InlineAsmOp, so it is
    unwrapped with .ir_value().

moe_fused_route_quant_scatter.py: scf 2 -> 0. The lead-lane e8m0 scale store
moves to the branch-helper + local @flyc.jit idiom, since _emit_quant_block_loop
is a plain helper where a bare `if` would trace the dynamic Boolean as a host
bool.

Both files drop scf (and vector) from their dialect imports. With this, no
gfx950 kernel uses the raw memref or vector dialects, and the only raw scf left
in the tree is the pair of eager persistent loops in the mixed MoE kernel.

Verified: grouped_moe AOT 222/222 with all 164 modules still VGPR- and
memop-identical to main and no spills; gemm_a16w16 byte-exact over 24 split-K
skinny cases; ISA A/B on the affected hgemm modules identical in registers and
memops. ruff and black clean.

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

Raw scf in the mixed MoE kernel goes 6 -> 0, and the scf import with it. No
gfx950 kernel now uses the raw scf, memref or vector dialects.

The previous pass left these three ForOps alone on the grounds that their
~2200-line bodies would need re-indenting. They do not: the body that actually
emits IR is only the per-iteration setup plus a dispatch call and a barrier, and
the bulk is a nested `def` that emits nothing until called. So the loop body
moves into a small `_persist_iter(mi_p)` helper which rebinds the setup names
with `nonlocal` (the big nested defs close over them), driven by a `for` inside
a local @flyc.jit. The two gemm2 loops additionally return their carried values,
which the loop variable yields.

One non-obvious detail, recorded in a comment at the call site: the plain no-init
`range(...)` dispatches to scf_for_dispatch, which casts bounds and the induction
variable to i32 and so breaks the index-typed `bx = bx_persist * c_pm + mi_p`
arithmetic. The `init=` form routes through scf_range and preserves the
index-typed IV, matching the original ForOp, so even the carry-free gemm1 loop
uses `init=[]`. Bounds stay index-typed constants; range_constexpr is avoided
because it would unroll for persist_m > 1.

Also fixes a latent closure bug surfaced by the conversion: `tokens_i32_guard` is
read by a nested def and had to stay in the enclosing scope.

Gated on ISA equality after every batch: all six modules (three gemm1 variants,
two gemm2 variants, the reduction kernel) byte-identical throughout.

Gates: MoE AOT 569/569; grouped_moe AOT 222/222; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
coderfeli and others added 2 commits September 8, 2026 14:26
The note said fx.to_llvm_ptr needed a newer fly dialect than the pinned LLVM
build exposes. That is no longer true: kernels_common.create_llvm_ptr, which
this site now calls, is built on fx.to_llvm_ptr and compiles fine.

Comment only.

Co-Authored-By: Claude <[email protected]>
@zufayu
zufayu requested a review from yadaish September 9, 2026 01:24
coderfeli and others added 3 commits September 9, 2026 05:20
One conflict, in tensor_shim.py, where both sides extended the buffer-view
helpers.

  - ptr_buf_tensor's base address: kept this branch's buf_base_i64(ptr). It is a
    superset of main's inline `fx.Int64(ptrtoint(ptr)) if isinstance(ptr,
    fx.Pointer) else fx.Int64(ptr)` -- it also accepts a tensor/memref or a raw
    address, which callers on this branch rely on to narrow a descriptor to a
    single row.
  - The two sides' additions are disjoint and both are kept: buf_scalar_load
    and the _fx_elem / _fx_value_elem helpers from this branch, and
    _buf_copy_slice / buf_copy_load / buf_copy_store from main. Only the
    buf_copy_atom body overlapped; main's duplicate was dropped, keeping this
    branch's docstring, which documents the cache_modifier values.

The vector.py shim stays deleted after the merge, with no importers.

Gates: MoE AOT 2464/2464; grouped_moe AOT 222/222; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
Editorial pass over the comments and docstrings introduced by this branch:
denser prose in the buffer_ops module header, ptr_buf_tensor's unit_stride
paragraph, moe_gather_reduce's alignment note, and the three route/quant-scatter
notes.

Every factual claim is preserved, in particular why the hidden/payload and MX
payload rows stay on the width-agnostic buffer_ops descriptor (+50 and +1..+4
VGPRs on the fp4/fp8 pk8 modules), why the lead-lane guard needs a local
@flyc.jit dispatch, and the offset/alignment gotchas.

Comments and docstrings only; no executable line changed.

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

Removing the raw scf.ForOp introduced more structure than the change needs.
This keeps the loop on range() and trims the rest:

  - _persist_setup took a still_active argument it never used, and each branch
    passed None for the other branch's carries. It is now
    _persist_setup(mi_p, prev_expert_i32=None, prev_expert_b_base=None).
  - The persistent and non-persistent paths had a duplicated _persist_iter and
    _run_persist that differed only in loop bound and carry count. Those are now
    two const_expr-selected values feeding one _persist_iter and one
    _run_persist, with the branch-specific guard kept inside _persist_iter.

Net cost of the whole scf removal in this file drops from +40 lines to +16.

ISA byte-identical across all six modules (three gemm1 variants, two gemm2
variants, the reduction kernel), so both the persistent and non-persistent
gemm2 paths lower exactly as before.

Gates: MoE AOT 2464/2464; grouped_moe AOT 222/222; a8w4 34/34 and a16wfp4 12/12;
a4w4 fp4-quant clean; ruff and black clean.

Co-Authored-By: Claude <[email protected]>
@coderfeli coderfeli changed the title [FlyDSL] [WIP] replace ptr_rsrc and buffer ops low level api use [FlyDSL] replace ptr_rsrc and buffer ops low level api use Sep 9, 2026
@XingerZhu

XingerZhu commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

LGTM (test moe ut on a07-3):
image
image

@coderfeli coderfeli removed the ci:atom label Sep 9, 2026
@coderfeli
coderfeli merged commit 08d73a1 into main Sep 9, 2026
64 of 65 checks passed
@coderfeli
coderfeli deleted the flydsl-moe-ptr-buf-tensor branch September 9, 2026 14:40
lalala-sh added a commit that referenced this pull request Sep 10, 2026
Resolves against #5303, which moved these kernels off the raw buffer_ops/scf
dialect onto the layout API. Both conflicting files keep this branch's kernels
and are ported to the new spelling:

moe_fused_route_quant_scatter.py
  - vector.bitcast / vector.extract / vector.from_elements -> fx.Vector
  - scf.IfOp + InsertionPoint -> a plain helper behind a local @flyc.jit
    dispatch, the pattern #5303 introduced for the lead-lane scale store
  - ptr_rsrc + buffer_load(is_scalar=True) -> buf_scalar_load on a
    ptr_buf_tensor view, for the six wave-uniform destination rows
  - the unpacked e8m0 store moves to the c.scale_t byte view; the packed
    row-major dword / dwordx4 stores keep a width-agnostic V# (c.scale_rsrc),
    for the same reason #5303 left the payload on buffer_ops. Both carry the
    zero-on-invalid bound that switches off a padding warp's destinations.

moe_gather_reduce.py
  - keeps this branch's LDS route cache and single flat descriptor indexed in
    dwords, which is the change being measured, rather than main's per-row
    descriptor rebuilt per access
  - takes main's full module docstring, its ptr_buf_tensor reads of the route
    map / weights / num_valid_tokens, and its copy-atom output store

Verified after the merge: a4w4 and a8w4 logits_diff bit-identical to pre-merge
at 4096 / 4097 / 16384 tokens, 12 psum/remap/route/gather unit tests pass, full
tuned-CSV sweep 85/85, no GPU faults.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
yuychang added a commit to yuychang/aiter that referenced this pull request Oct 1, 2026
- Use CombiningKind from the MLIR vector dialect that both KDA kernels already import.
- Remove aiter/ops/flydsl/kernels/vector.py, which main dropped in ROCm#5303 and nothing else imports.
- Document that cache slot zero is reserved for the KDA decode APIs.
yuychang added a commit to yuychang/aiter that referenced this pull request Oct 15, 2026
- Use CombiningKind from the MLIR vector dialect that both KDA kernels already import.
- Remove aiter/ops/flydsl/kernels/vector.py, which main dropped in ROCm#5303 and nothing else imports.
- Document that cache slot zero is reserved for the KDA decode APIs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants