Repository navigation
[FlyDSL] [gfx1250] Quantize each MoE source token once instead of once per route - #5274
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
There was a problem hiding this comment.
🟡 Changes recommended
The new dead-destination scale buffer descriptor sizing is capped in a way that can silently drop scale stores if the real scale buffer exceeds the chosen maximum, so the bounds size should be made robust (4GiB-1 with i64 select) before merging.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR optimizes the FlyDSL gfx1250 MoE stage1 quant+preshuffle path by changing the work partitioning from “one warp per route” to “one warp per source token”, quantizing each token row once and scattering to its topk destinations. It also reduces backend register pressure by sharing the e8m0 scale-write scf.if across destinations, and updates tuned configs / AOT compilation to cover the new variant.
Changes:
- Add
fuse_source_destsvariant to the route-indexed quant+preshuffle kernel and update runtime launch/grid selection to use a token-counted grid when enabled. - Refactor destination handling in the kernel to support multi-destination scatter and reduce redundant branch/materialization for scale writes.
- Retune gfx1250 grouped fmoe configs for tokens ≥ 2048 and update AOT compilation to emit fused/unfused variants.
File summaries
| File | Description |
|---|---|
| aiter/ops/flydsl/moe_kernels.py | Switch stage1 grid logic to token-based when fusing destinations; plumb fuse_source_dests through compilation/launch. |
| aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py | Implement fused-source-destination scatter path and share scale-write branch across destinations. |
| aiter/configs/tuned_grouped_fmoe.csv | Update tuned parameters for gfx1250 at higher token counts. |
| aiter/aot/flydsl/grouped_moe.py | Precompile both fused/unfused variants (where applicable) across ksplit modes. |
Review details
Suppressed comments (1)
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:1561
- num_records_bytes is currently built as an i32 select (fx.Int32(...)), which create_buffer_resource_from_addr sign-extends to i64. If SCALE_RSRC_MAX_BYTES is raised to 0xFFFFFFFF (4GiB-1), this must be an i64 select to avoid sign-ext turning it into -1 and effectively disabling bounds checks / making the descriptor invalid.
num_records_bytes=mapped_k.select(
fx.Int32(SCALE_RSRC_MAX_BYTES), fx.Int32(0)
),
- Files reviewed: 4/4 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
🟡 Changes recommended
The new row_to_token inversion launch can read dead-tail/unwritten topids_to_rows entries under EP truncation and corrupt the inverse map unless it is bounded by num_valid_routes (capture-safe) or the route map is pre-initialized.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
aiter/ops/flydsl/grouped_moe_gfx1250.py:1493
row_to_tokeninversion divides bytopk; iftopkis accidentally 0 (or negative), this will produce a divide-by-zero / incorrect token ids. Sincerow_to_tokenis only meaningful for MoE routing, it’s safer to validatetopk > 0before launching the kernel.
if row_to_token is not None:
# Its own launch: the remap above is a single-block prefix scan, so
# these scattered stores are far cheaper spread over their own grid.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
- Files reviewed: 9/9 changed files
- Comments generated: 2
- Review effort level: Lite
The stage1 quant kernel still wrote its output once per route. At topk=6
that is six copies of every payload row, and the e8m0 scale is worse: the
WMMA preshuffle spaces consecutive elements 256 B apart, so each store
lands 4 useful bytes in a 64 B line, 16x write amplification on top of the
6x duplication. At 16384 tokens the kernel moved 528 MB of stores for
62 MB of data.
Both halves now write one compact row per token. The payload goes straight
to the GEMM, which gathers its A rows through an inverse route map. A TDM
gather descriptor carries at most 16 row indices, so a wave owning 32 rows
issues two; every wave owns the same count, so the pipeline stays
symmetric and its fence arithmetic only has to count the extra descriptor.
This is what lets the gather run under the tile_m=128 configs.
The scale cannot be read compact: the GEMM's WMMA layout interleaves rows
that compact stores apart. Teaching the GEMM to read row-major would push
its LDS from 16 KB to 30 KB, and it owns 86% of the layer, so 5% there
would eat the whole saving. A second pass rebuilds the layout instead,
leaving the GEMM's scale path untouched. That pass has to stage through
LDS: the preshuffle transposes (row, k) into (k, row), so a direct copy
can only coalesce one side, and writing whole lines while reading 4 bytes
out of each just moves the amplification to the load side (measured no
faster than the scattered write it replaced).
Three things then dominated, none of them the layout:
- The quant kernel held all 224 converted payloads live until a separate
store pass, costing enough occupancy to leave it at 8.9 TB/s. Retiring
each store at conversion reaches 11.8 TB/s. Only with one destination:
the scattered path stores per route, and moving those inside breaks
the load clustering for the same register saving (78.1 -> 80.1 us), so
the choice follows the destination count.
- Writing the inverse map from the remap pass added 26 us. That pass is
a single-block prefix scan, so 100k scattered stores in it are nearly
serial; its own grid does them in 2.2 us.
- The preshuffle pass reads 4 dwords per thread so the accesses merge
into one dwordx4. That also flips its LDS budget: a whole row now
beats a half (6.8 vs 7.5 us), where before vectorizing the larger tile
lost more to occupancy than contiguity won.
At 16384 tokens: quant 77.4 -> 25.2 us, against 6.8 for the preshuffle
pass, 2.2 for the map and 1.6 on gemm1, so 2193 -> 2146 us end to end.
Output is unchanged, rel_l2 2.60e-03 at 512/2048/16384 on both paths.
Off by default; set AITER_COMPACT_A=1 to enable.
Also retunes tokens>=4096 to tile_m=128, which the multi-descriptor gather
above exists to support.
Co-authored-by: Cursor <[email protected]>
95814b2 to
7d4139b
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical correctness issues remain in compact-mode eligibility, EP mapping, and the gather API default.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (6)
aiter/ops/flydsl/grouped_moe_gfx1250.py:765
- The compact producer is also used before the
_fuse_quantsplit, butrow_to_tokenis threaded only through the fused GEMM1 call. Whenbias1makes_fuse_quantfalse, GEMM1 below still consumesa1_payloadwithout indexed gathering, so compact A rows are interpreted as contiguous grouped rows and the result is wrong. Pass the map and token bound through this branch too, or disable compact mode when the non-fused path is selected.
row_major_ascale=int(_row_major_ascale),
row_to_token=_row_to_token,
a_gather_rows=token_num,
aiter/ops/flydsl/grouped_moe_gfx1250.py:563
- The added compact layout, inverse route map, indexed TDM loads, EP interaction, and LDS scale preshuffle have no collected test that enables
AITER_COMPACT_Aor validatesrow_to_token; the existing gfx1250 tests cover only the non-compact remap. This leaves the unsupported-shape and EP failures above undetected. Add an independent correctness test covering a supported compact case plus small-token, padded, and EP/dropped-route cases.
if _compact_a:
_row_to_token = torch.full(
(int(contiguous_m),), -1, dtype=torch.int32, device=device
)
aiter/ops/flydsl/grouped_moe_gfx1250.py:693
- With compact A enabled, omitting
out_payloadstill makesflydsl_moe_fused_quant_preshuffleallocate its default(E, contiguous_m, payload_bytes)buffer, even though the token-multidest kernel writes onlytoken_numrows. For top-k 6 this retains roughly the old route-sized payload allocation and can materially increase memory pressure, undermining the compact layout's purpose. Allocate and pass a token-sized payload buffer for this mode.
row_major_scale=_row_major_ascale or _compact_scale_buf is not None,
out_scale=_compact_scale_buf,
aiter/ops/flydsl/grouped_moe_gfx1250.py:765
- The captured
kernel_bench_callableGEMM1 closure below is not updated withrow_to_token,a_gather_rows, or the gather wave-count override. When compact mode is enabled, the eager call is correct but the isolated benchmark then launches GEMM1 in contiguous mode against the compacta1_payload, so the reported GEMM1 timing is for the wrong memory layout. Mirror the new gather arguments in the benchmark closure.
row_major_ascale=int(_row_major_ascale),
row_to_token=_row_to_token,
a_gather_rows=token_num,
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
- The PR description says the new route-fused behavior is the active path and documents
AITER_ROUTEKS_FUSE_DESTS=0as the fallback, but this code defaultsAITER_COMPACT_Ato0and the documented variable is not read anywhere in the repository. As written, the described optimization is opt-in under a different name, so the reported default behavior and fallback control are not reproducible. Align the implementation and documentation on one environment variable and default.
_COMPACT_A = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:675
- The contiguous A path applies
a_mcast_maskfor clustered launches, but the new gather descriptor does not carry that mask. Withcluster_n > 1, every peer repeats the same indexed A transfer instead of sharing it, multiplying A bandwidth on the path this change is intended to optimize. Pass the cluster workgroup mask to the gather descriptor if gather-mode multicast is supported, or reject clustered compact-A launches explicitly.
pad_amount=LDS_PAD_A,
lds_byte_offset=0,
global_byte_offset=kt * j.k_adv,
)
tdm_ops.tensor_load_gather(desc)
- Files reviewed: 6/6 changed files
- Comments generated: 5
- Review effort level: Lite
CI's black run rejects four files on this branch. Two of the hunks predate the compact-A work (the k_chunk generator and the row_to_token index), so they have never matched the version CI pins; the other two come from the rebase onto main. Pure reformatting, no behaviour change: logits_diff is 3.4871e-06 at 512 tokens on both the default and compact paths, unchanged. Co-authored-by: Cursor <[email protected]>
Two findings, both fallout from moving compact A onto main's token-multidest quant: the route-ksplit module kept a scale_dwords_per_row constant that only the compact code it no longer holds ever read (F841), and the gather-rows bound check nested two ifs where one does (SIM102). Dropping the constant puts that module back to main's form. ruff 0.16.0 is then clean except for two EXE001 shebang findings that main carries as well. Behaviour unchanged: logits_diff 3.4871e-06 at 512 tokens on both the default and compact paths. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate correctness and integration issues remain in the compact GEMM, EP mapping, dispatch, and launch paths.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (10)
aiter/ops/flydsl/grouped_moe_gfx1250.py:558
_compact_ais enabled independently of the producer'suse_token_multidestgate. That producer only emits one row per token when the input is not prequantized,num_valid_routesis absent, top-k is supported, the batch is large enough, and its own environment switch is enabled; otherwise it emits route-indexed rows (or rejects the row-major-scale request), while this path still passes_row_to_tokento GEMM1. ThusAITER_COMPACT_A=1can select a compact consumer for non-compact data. Derive oneuse_compact_afrom the producer's actual selection and use it consistently for allocation, scale mode, and GEMM gathering.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:1451
row_to_tokenis now passed by the caller even for EP, but theep_scatter_params is not Nonebranch returns before the inverse-map launch below. In the EP scatter path the map therefore remains filled with-1, so indexed GEMM1 drops every A row. Generate the inverse map in the EP branch as well, bounded by the valid-route count, or disable compact mode for EP.
row_to_token: torch.Tensor | None = None,
aiter/ops/flydsl/grouped_moe_gfx1250.py:764
- The
kernel_bench_callableGEMM1 partial registered below does not pass the newrow_to_token/a_gather_rowsarguments. With compact A enabled, benchmark re-launches therefore read token rows as contiguous grouped rows, so the reported GEMM1 timing and any correctness check do not exercise the production layout. Thread the same gather arguments through the benchmark partial.
row_to_token=_row_to_token,
aiter/ops/flydsl/grouped_moe_gfx1250.py:757
- The PR description says tokens >=2048 are retuned to
tile_n=768andnum_buffer_stage2=3, but the production tuning rows remain unchanged:aiter/configs/tuned_grouped_fmoe.csvrows 29-31 still selecttile_n=512andnum_buffer_stage2=2. Since this path reads those rows through_find_grouped_config, the claimed retune is not applied; update the table or correct the description.
waves_per_tensor_tdm=(
aiter/ops/flydsl/grouped_moe_gfx1250.py:765
a_gather_rows=token_numis passed whenever_row_to_tokenexists, but the TDM launch explicitly rejects indexed gathers witha_gather_rows >= 65536because the row list uses 16-bit indices. The compact host gate has no matching upper bound, so long-context inputs fail at launch instead of falling back. Gate compact mode at this limit or add a 32-bit gather implementation.
a_gather_rows=token_num,
aiter/ops/flydsl/grouped_moe_gfx1250.py:1719
- The production gather path now returns
build_moe_gather_preshuffle_scale_lds_module, butop_tests/test_flydsl_moe_aux.py::test_preshuffle_scalestill constructsbuild_moe_scatter_copy_preshuffle_scale_moduledirectly. Consequently the new LDS staging/vectorized load-store path and its padding handling have no numerical test. Add a gather case through_get_compiled_scatter_preshuffle_scaleorflydsl_moe_scatter_preshuffle_scale.
if gather:
return build_moe_gather_preshuffle_scale_lds_module(
row_bytes, wmma_rep, scale_k_per_tile
aiter/ops/flydsl/grouped_moe_gfx1250.py:558
- The PR description says
AITER_ROUTEKS_FUSE_DESTS=0selects the per-route fallback, but this variable is not read anywhere in the implementation; the actual controls areAITER_COMPACT_AandAITER_FLYDSL_TOKEN_MULTIDEST_QUANT. As written, the documented fallback switch has no effect, so either wire it into dispatch or correct the description.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:558
- The compact payload and scale modes are entirely opt-in here, but the existing MoE tests do not exercise either compact layout, the row-to-token inversion, the EP/bias cases, or the long-map boundary. These paths change both the quantizer's destination layout and the GEMM's indexing, so add at least one top-k>1 numerical compact test and regressions for the unsupported dispatch combinations before relying on this gate.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:563
- The new compact dispatch, inverse row map, and compact scale path are not covered by the existing gfx1250 tests: the current remap tests exercise only the route-indexed map. Please add a correctness test for compact A with padding and the supported fallback conditions (and an EP case if EP is meant to remain supported); otherwise this integration can silently feed zeros, as in the EP path above, without a regression test.
_row_to_token = torch.full(
(int(contiguous_m),), -1, dtype=torch.int32, device=device
)
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
- The PR description documents
AITER_ROUTEKS_FUSE_DESTS=0as the fallback to per-route mapping, but this change introducesAITER_COMPACT_A/AITER_COMPACT_SCALEand no repository code readsAITER_ROUTEKS_FUSE_DESTS. Setting the documented switch therefore has no effect and cannot disable the new path; wire that variable into dispatch or update the documented interface to the actual controls.
_COMPACT_A = os.environ.get("AITER_COMPACT_A", "0") == "1"
- Files reviewed: 6/6 changed files
- Comments generated: 3
- Review effort level: Lite
ptr_buf_tensor views default to fx.Int32 elements, so wrapping what they return re-declares a type it already has. Four sites in the row_to_token map and the scale gather; the fx.Int32(0) literals they compare against stay, those introduce a type. Behaviour unchanged, verified with the runtime cache off on both the default and compact paths. Co-authored-by: Cursor <[email protected]>
The row_major_scale argument restated what the _row_major_ascale block above it already explains about the compact scale being a per-token row-major write. Keep only what is local to the call: gemm1 still reads the WMMA layout. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved correctness and compatibility issues remain in compact/fallback paths, caller argument plumbing, and scheduling configuration.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (9)
Previously missed (1) — in code that hasn't changed since the last review.
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
- [verified] The PR description documents
AITER_ROUTEKS_FUSE_DESTS=0as the rollback switch, but this code never reads that variable; compact routing is selected fromAITER_COMPACT_A(default0) andAITER_FLYDSL_TOKEN_MULTIDEST_QUANT. Setting the documented flag therefore neither enables the advertised default nor disables an enabled compact build, leaving the promised operational fallback unavailable. Author must wire the documented variable into dispatch or update the description to name the actual controls.
aiter/ops/flydsl/grouped_moe_gfx1250.py:557
- [verified]
_compact_aenables the row-to-token gather for every call, butflydsl_moe_fused_quant_preshuffleonly emits the compact one-row-per-token layout whenuse_token_multidestis true. That predicate is false for, among other cases,topk=1, fewer than 64 tokens, EP (num_valid_routes), prequantized input, or the explicit token-multidest disable flag; those fall back to route-indexed output while GEMM1 still receivesrow_to_tokenand gathers it as compact. The result is wrong A rows (and compact scale can raise on the same fallback). Author must gate_compact_a/_compact_scalewith the exact token-multidest eligibility or make every fallback producer emit the compact layout.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:760
- [verified] This override only changes
waves_per_tensor_tdmwhen it is-1/None. For the supported combinationtile_m=64, m_warp=1, n_warp=4, waves_per_tensor_tdm=2, indexed gathering computesA_DESCS=ceil((64/2)/16)=2, so(3 + A_DESCS) * 2 = 10is not divisible by the four workgroup waves and the kernel hits the ownership assertion inmxfp4_preshuffle_gfx1250_tdm.py. Author must validate or replace explicit wave-count overrides wheneverrow_to_tokenis enabled.
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
),
next_stage_prefetch=next_stage_prefetch,
aiter/ops/flydsl/grouped_moe_gfx1250.py:563
- [verified] The new compact path is enabled only through environment flags, but the existing gfx1250 tests do not set
AITER_COMPACT_Aor verify the compact payload/scale and indexed-TDM results. Since the default is off, those tests can all pass while this path has a layout bug or a failing fallback configuration. Author must add an independent-reference test for compact mode, including padding and the supported eligibility boundaries.
if _compact_a:
_row_to_token = torch.full(
(int(contiguous_m),), -1, dtype=torch.int32, device=device
)
aiter/ops/flydsl/grouped_moe_gfx1250.py:765
- These arguments are only supplied to the fused stage1 GEMM. When
bias1is present,_fuse_quantis false and the stage1 call in theelsebranch below omitsrow_to_token/a_gather_rows; compact A is then read as if it were route-indexed, producing incorrect results. Pass the gather arguments to that stage1 call as well, or reject compact mode for the bias path.
**_situ_kw,
)
aiter/ops/flydsl/grouped_moe_gfx1250.py:1530
- This optional-map launch is unreachable for EP calls:
contiguous_psum_remapreturns earlier wheneverep_scatter_paramsis set. The caller nevertheless allocates_row_to_tokenfor compact EP, so it remains all-1and indexed A loads are dropped/zeroed. Move the inversion before the EP return (with a valid-route bound) or explicitly reject compact EP.
# these scattered stores are far cheaper spread over their own grid.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
ptr_arg(topids_flat),
ptr_arg(row_to_token.reshape(-1)),
aiter/ops/flydsl/grouped_moe_gfx1250.py:761
- The PR description says token counts >=2048 are retuned to
tile_n=768andnum_buffer_stage2=3, but this diff adds no token-dependent override; stage2 still derivestile_n2andnum_buffers2from the stage1 values/config. Add the stated tuning rule or update the description so the shipped behavior is not misrepresented.
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
),
next_stage_prefetch=next_stage_prefetch,
row_major_ascale=int(_row_major_ascale),
aiter/ops/flydsl/grouped_moe_gfx1250.py:558
- The PR description documents
AITER_ROUTEKS_FUSE_DESTS=0as the fallback switch, but this change readsAITER_COMPACT_A(defaulting to disabled) and no implementation reads the documented variable. Consequently the advertised mode cannot be controlled as described and the stated fused behavior is not enabled by default.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:420
- The new
_A_GATHERidentity mode addsA_DESCS, but the caller only auto-selectswaves_per_tensor_tdm=4whenrow_to_tokenis present. WithAITER_A_GATHER=1and compact mode off, the common 64x.../4-wave case keeps the default wpt=2, making(3 + 2) * 2 % 4 != 0and triggering the ownership assertion. Include_A_GATHERin the valid-wpt selection or provide a matching schedule for this mode.
if const_expr(_A_GATHER or a_gather_indexed):
_rows_per_wave_a = tile_m // num_waves_per_tensor_tdm
A_DESCS = (_rows_per_wave_a + 15) // 16
assert (
(3 + A_DESCS) * num_waves_per_tensor_tdm
- Files reviewed: 6/6 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Critical and moderate correctness and dispatch issues remain unresolved.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (8)
aiter/ops/flydsl/grouped_moe_gfx1250.py:557
- [verified]
_compact_ais enabled solely fromAITER_COMPACT_A, but the quantizer only emits compact rows on the token-multidest branch (num_valid_routes is None, supported top-k, token count >= 64, and its env gate enabled). For example, compact mode with an EP route count or an 8-token batch falls back to route-ksplit while this caller still passesrow_to_tokento GEMM; with compact scale enabled, the(token_num, Ws)buffer is then indexed by grouped rows and can be written out of bounds, while compact payload gathers read the wrong rows. Author must gate the compact buffers/GEMM on the actual quantizer layout or make every fallback path produce compact rows.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:1528
- [verified] The EP remap branch returns before this inverse-map launch. When compact A is enabled, the caller has allocated
row_to_tokenand the GEMM consumes it, but EP scatter therefore leaves every entry at its initial-1; valid grouped rows are dropped by the gather and the result is incorrect. Author must populaterow_to_tokenfrom the EP-remapped route map before returning, or have the EP remap kernel write the inverse map.
if row_to_token is not None:
# Its own launch: the remap above is a single-block prefix scan, so
# these scattered stores are far cheaper spread over their own grid.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
aiter/ops/flydsl/grouped_moe_gfx1250.py:759
- [verified] The compact path only overrides
waves_per_tensor_tdmwhen the caller leaves it at-1/None. An explicit, otherwise-valid setting of2reaches the new descriptor split (for exampletile_m=128,m_warp=1,n_warp=4givesA_DESCS=4) and then fails the kernel assertion because(3 + A_DESCS) * 2 % 4 != 0. Author must force or explicitly reject non-4 TDM ownership whenever compact A is selected.
waves_per_tensor_tdm=(
4
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
),
aiter/ops/flydsl/grouped_moe_gfx1250.py:764
- The compact map is forwarded only in the
_fuse_quantstage-1 GEMM call. Whenbias1is present,_fuse_quantis false but the earlier quantization still produces compacta1_payload; theelseGEMM below treats it as contiguous grouped rows because it receives norow_to_token, producing incorrect stage-1 results. Pass the map/bound (and gather-compatible TDM configuration) through both stage-1 branches, or disable compact mode when stage-1 bias is used.
next_stage_prefetch=next_stage_prefetch,
row_major_ascale=int(_row_major_ascale),
row_to_token=_row_to_token,
a_gather_rows=token_num,
**_situ_kw,
aiter/ops/flydsl/grouped_moe_gfx1250.py:759
- The PR description says tokens >=2048 are retuned to
tile_n=768withnum_buffer_stage2=3, but this dispatch still readstuned_grouped_fmoe.csv, whose matching 2048-token entries remain attile_n=512/256and stage-2 buffer count2(for example, rows 29 and 95). Unless those tuning rows are updated elsewhere in the PR, the advertised retune is not shipped; update the relevant configuration entries or correct the description.
waves_per_tensor_tdm=(
4
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
),
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
_COMPACT_Achanges the destination layout, but it is enabled independently of the dispatch conditions that select the token-multidest quantizer.moe_kernels.py:3169-3183falls back to route-indexed output for small token counts, unsupported topk, remap/EP, prequantized input, or a disabled token-multidest flag; GEMM still receivesrow_to_tokenand gathers as if the payload were compact (and the compact scale buffer can be too small for the fallback stores). Gate compact allocation/GEMM on the same predicate or reject these combinations.
_COMPACT_A = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/kernels/moe_scatter_copy_preshuffle_scale.py:231
- [verified] This new LDS gather/preshuffle kernel is reached only when compact scale is enabled, but the existing gfx1250 grouped tests do not enable
AITER_COMPACT_A/AITER_COMPACT_SCALEor compare the compact scale output with an independent reference. The row-index padding and LDS transpose can therefore regress without a collected correctness test. Author must add a test that forces compact payload/scale and covers a paddedrow_to_tokentile.
def build_moe_gather_preshuffle_scale_lds_module(
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:658
- This gather descriptor leaves
workgroup_maskat its default zero. Forcluster_n > 1, all peers share the same M tile and the contiguous path usesa_mcast_maskto issue one cluster A load; this path instead makes every peer fetch every A descriptor independently, multiplying global A traffic by the cluster size. Passworkgroup_mask=a_mcast_maskhere to preserve the existing multicast behavior.
desc = make_tensor_gather_descriptor(
j.gt,
lds_c,
j.gather.rows,
row_width=j.inner,
- Files reviewed: 6/6 changed files
- Comments generated: 3
- Review effort level: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
One or more issues must be addressed before approval.
Review details
Suppressed comments (13)
aiter/ops/flydsl/grouped_moe_gfx1250.py:558
_compact_ais enabled for every shape, butflydsl_moe_fused_quant_preshuffleselects the token-multidest producer only for non-prequantized, non-EP inputs with2 <= topk <= 8, at least 64 tokens, and its feature enabled. The fallback route-indexed producer writes grouped rows, while this code still makes GEMM gather throughrow_to_token(and EP remap can leave that map unfilled), so opt-in compact mode returns incorrect/zero A for those cases. Gate this flag on the producer's actual contract or add compact destinations to every fallback.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:557
- The PR description documents
AITER_ROUTEKS_FUSE_DESTS=0as the fallback switch, but this code readsAITER_COMPACT_Aand defaults it to off; there is noAITER_ROUTEKS_FUSE_DESTShandling in the repository. Consequently the documented switch has no effect and the described fused path is not selected by default. Align the environment variable/default with the implementation or update the description.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:758
- When a tuned config explicitly supplies
waves_per_tensor_tdm=1or2, this conditional preserves it even though the new gather schedule only supports4for the tile/workgroup geometry described here. The kernel then reaches the ownership assertion at line 420 and fails instead of selecting a valid compact configuration. Force or validate4for every compact-A build, not only when the caller passes the sentinel.
waves_per_tensor_tdm=(
4
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
aiter/ops/flydsl/grouped_moe_gfx1250.py:1528
- The EP branch above returns before reaching this new inverse-map launch. With
AITER_COMPACT_A=1,_row_to_tokentherefore remains filled with-1on EP, so indexed payload and scale gathers treat every GEMM row as padding and produce zero input. Build the inverse map in the EP path as well, or move the launch before the early return.
if row_to_token is not None:
# Its own launch: the remap above is a single-block prefix scan, so
# these scattered stores are far cheaper spread over their own grid.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
aiter/ops/flydsl/grouped_moe_gfx1250.py:1533
- When
num_valid_routesis provided, the remap intentionally leaves dead-tail entries intopids_flatunwritten (1468-1469), but this launch always uses the fulltopids_flat.numel(). It can therefore read uninitialized rows for the tail; any nonnegative garbage can index outsiderow_to_tokenor overwrite a valid row. Limit the inversion to the valid route count while preserving-1for padding.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
ptr_arg(topids_flat),
ptr_arg(row_to_token.reshape(-1)),
numel,
int(topk),
(numel + 255) // 256,
aiter/ops/flydsl/grouped_moe_gfx1250.py:755
- The description says tokens >=2048 are retuned to
tile_n=768andnum_buffer_stage2=3, but this host code still consumes the existing CSV values fortile_nandnum_buffers2; the gfx1250 rows remain attile_n=512with two stage-2 buffers. The claimed retune is therefore not shipped by this change. Update the tuning data or correct the description.
# Gathering A splits a wave's rows over ceil(rows_per_wave/16)
# descriptors, and the kernel needs (3 + descs) * wpt to divide the
# workgroup's waves; at the tile_m this path runs, only wpt=4 does.
waves_per_tensor_tdm=(
aiter/ops/flydsl/grouped_moe_gfx1250.py:563
- This opt-in path is not exercised by the existing gfx1250 grouped-GEMM correctness tests, which do not set either compact environment flag. The new indexed payload/scale gathers and EP/dead-tail fallbacks can therefore regress without detection. Add cases for compact payload, compact scale, and route fallback/EP padding before relying on this switch.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
_compact_scale = _compact_a and os.environ.get("AITER_COMPACT_SCALE", "1") == "1"
_row_to_token = None
if _compact_a:
_row_to_token = torch.full(
(int(contiguous_m),), -1, dtype=torch.int32, device=device
)
aiter/ops/flydsl/grouped_moe_gfx1250.py:691
- Although
_compact_ais enabled, this quantization call does not provide anout_payload, somoe_kernels.pyallocates its default(1, contiguous_m, Pb)buffer. The compact kernel writes onlytoken_numrows, but the allocation and working set remain route/capacity-sized, often roughly topk times larger, undermining the intended memory-footprint reduction. Allocate a token-sized payload and pass it for the compact path.
out_scale=_compact_scale_buf,
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
- The PR description documents
AITER_ROUTEKS_FUSE_DESTS=0as the fallback switch, but this change reads onlyAITER_COMPACT_AandAITER_COMPACT_SCALE; there is noAITER_ROUTEKS_FUSE_DESTSusage in the repository. Setting the documented variable therefore has no effect. Align the flag name and semantics with the implementation or update the description.
_COMPACT_A = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:388
- [verified]
_emit_quant_block_loopis shared by the route-ksplit and other per-route quant builders, not just the new token-multidest builder. Those callers create one destination, so this new default makesearly_payload_store=Truefor the fallback/unfused kernels as well; that changes their generated code and the comment's own measurement shows scattered latency regressing from 78.1 to 80.1 us. Author must scope the default early-store decision to the token-multidest path or preserve the existing per-route behavior.
early_payload_store = (
len(dst_payload) == 1 if _EARLY_PAYLOAD_STORE is None else _EARLY_PAYLOAD_STORE
)
aiter/ops/flydsl/kernels/moe_scatter_copy_preshuffle_scale.py:234
- [verified] The existing
test_preshuffle_scaleonly instantiatesbuild_moe_scatter_copy_preshuffle_scale_module; no test exercises this new LDS gather builder, therow_to_tokeninversion, or the compact-A GEMM path. The new implementation has independentk_chunk/VECselection plus 16-bit OOB and-1padding handling, so the current tests cannot catch a transpose or padding error. Author must add an independent correctness test covering the LDS builder and compact path, including padding and a multi-chunk row.
def build_moe_gather_preshuffle_scale_lds_module(
row_bytes: int, wmma_rep: int, scale_k_per_tile: int
):
"""Route-gather + preshuffle staged through LDS, contiguous on both sides.
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:1579
- The new kernel argument is forwarded unconditionally, but existing direct callers such as
batched_gemm_mxfp4._run_gfx1250do not pass it, so it remainsNonewhile the nested kernel requires anfx.Pointer. Normalize this exactly likearg_ep_row_map(for example, fall back toarg_a) before buildingkargs;otherwise non-gather launches cannot be traced/launched.
arg_row_to_token,
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:658
- This new gather descriptor does not carry
a_mcast_mask, whereas the contiguous A load passes that mask toadd_tdm_loads. Withcluster_n > 1, compact-A GEMM therefore makes every peer fetch the same A rows independently, duplicating global traffic and forfeiting the cluster multicast optimization. Preserve the workgroup mask (and its required gather-descriptor early-timeout bit) for this path.
desc = make_tensor_gather_descriptor(
j.gt,
lds_c,
j.gather.rows,
row_width=j.inner,
- Files reviewed: 6/6 changed files
- Comments generated: 0 new
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved correctness and integration issues remain, including the critical gather-index overflow and multiple compact/fallback layout mismatches.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (10)
aiter/ops/flydsl/grouped_moe_gfx1250.py:691
- When
expert_maskis present,_ep_nvris non-None, somoe_kernels.pydeliberately makesuse_token_multidestfalse; the same happens fortoken_num < 64,topk > 8, prequantized input, or the route-ksplit fallback. In those cases the producer writes route-indexed rows, but this still supplies a compacttoken_num-row scale buffer (and the GEMM below still usesrow_to_token), causing out-of-bounds scale writes and/or reading the payload with the wrong row layout. Author must gate compact A/scale on the actual token-multidest eligibility or retain the route-indexed buffers and mapping in every fallback case.
out_scale=_compact_scale_buf,
aiter/ops/flydsl/grouped_moe_gfx1250.py:1528
- This inverse-map construction is after the
if ep_scatter_params is not None: ... returnpath incontiguous_psum_remap(). Stage-2 EP scatter therefore leaves the newly allocatedrow_to_tokenfilled with its initial-1values; compact GEMM treats every gathered A row as padding and produces zeros instead of the routed activations. Author must build the inverse map before the EP early return, or explicitly disable compact gather for EP stage-2.
if row_to_token is not None:
# Its own launch: the remap above is a single-block prefix scan, so
# these scattered stores are far cheaper spread over their own grid.
numel = int(topids_flat.numel())
_get_compiled_row_to_token()(
aiter/ops/flydsl/grouped_moe_gfx1250.py:557
- The PR description says
AITER_ROUTEKS_FUSE_DESTS=0selects the per-route fallback, but this implementation readsAITER_COMPACT_Aand there are no repository references to the described variable. Users following the documented switch cannot select the fallback or enable/disable the new mapping as advertised. Author must make the implementation and the documented environment-variable contract agree.
_compact_a = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/grouped_moe_gfx1250.py:563
- Enabling
_compact_aadds the row-to-token and gathered-scale launches, butaiter/aot/flydsl/grouped_moe.pystill precompiles only the existing contiguous remap and route/quant helpers; it does not compilebuild_moe_row_to_token_module()orbuild_moe_gather_preshuffle_scale_lds_module(). In run-only/AOT deployments, the first compact invocation therefore has no cached kernel for these new calls and cannot follow the advertised compact path. Author must add the compact helper variants to the AOT matrix or explicitly reject compact mode in run-only configurations.
if _compact_a:
_row_to_token = torch.full(
(int(contiguous_m),), -1, dtype=torch.int32, device=device
)
aiter/ops/flydsl/grouped_moe_gfx1250.py:758
- [verified] The description claims a
tokens >= 2048retune totile_n=768andnum_buffer_stage2=3, but this diff only changes gather wave selection; the checkedconfigs/tuned_grouped_fmoe.csventries still selecttile_n=512andnum_buffer_stage2=2, with no token-count branch. The claimed stage2 performance setup is therefore not represented by this PR. Author must add the tuning/dispatch change or correct the performance claim.
waves_per_tensor_tdm=(
4
if (_row_to_token is not None and waves_per_tensor_tdm in (-1, None))
else waves_per_tensor_tdm
aiter/ops/flydsl/grouped_moe_gfx1250.py:762
- [verified] The compact
a1_payloadis produced before_fuse_quantis computed. Whenbias1is present,_fuse_quantis false and the GEMM1 call in theelsebranch below does not passrow_to_tokenora_gather_rows, so it reads the one-row-per-token payload as contiguous grouped rows. Any supported compact configuration withbias1therefore computes GEMM1 from the wrong rows. Author must pass the gather mapping through the non-fused GEMM1 path or disable compact A when bias1 is present.
row_to_token=_row_to_token,
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:120
- [verified] The advertised rollback variable
AITER_ROUTEKS_FUSE_DESTS=0is not read anywhere in this codebase; this path instead usesAITER_COMPACT_AandAITER_FLYDSL_TOKEN_MULTIDEST_QUANT. Operators following the PR description therefore cannot select the claimed per-route fallback, and disabling the latter alone does not disable the GEMM gather. Author must implement the documented switch or update the description and expose a fallback that keeps producer/consumer layouts synchronized.
_COMPACT_A = os.environ.get("AITER_COMPACT_A", "0") == "1"
aiter/ops/flydsl/kernels/moe_fused_route_quant_scatter.py:388
- [verified] Route-indexed builders pass a single destination, so
len(dst_payload) == 1makesearly_payload_store=Truefor the non-compact fallback as well. That changes the old scattered quantizer to the interleaved store schedule; the surrounding comment reports this path moving from 78.1 to 80.1 us. Author must make the default early-store decision depend on the compact token-multidest path or preserve the old schedule when compact mode is off.
early_payload_store = (
len(dst_payload) == 1 if _EARLY_PAYLOAD_STORE is None else _EARLY_PAYLOAD_STORE
)
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:670
- The contiguous A path passes
a_mcast_maskto its TDM loads, but this new gather descriptor leavesworkgroup_maskat its default zero. Forcluster_n > 1, every peer therefore reloads the same gathered A rows instead of participating in the cluster multicast described by this kernel, multiplying A traffic and potentially invalidating the intended cluster performance path. Author must passworkgroup_mask=a_mcast_maskto the gather descriptor.
global_byte_offset=kt * j.k_adv,
aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py:170
- [verified] A 16-bit index can represent token IDs 0 through 65535, while
tensor_dim1is packed as a 32-bit bound bymake_tensor_gather_descriptor. Thus a batch of exactly 65,536 tokens is representable, but this check rejects it. Author must allow the 65,536-row case or document and enforce a smaller supported token limit.
if a_gather_indexed and not 0 < a_gather_rows < 65536:
raise ValueError(
f"a_gather_indexed needs 0 < a_gather_rows < 65536, got {a_gather_rows}"
)
- Files reviewed: 6/6 changed files
- Comments generated: 1
- Review effort level: Lite
Co-authored-by: Cursor <[email protected]>
The gather path still called the old helpers, which ruff flags as F821. Signed-off-by: yadaish <[email protected]> Co-authored-by: Cursor <[email protected]>
Signed-off-by: yadaish <[email protected]> Co-authored-by: Cursor <[email protected]>
main reverted #5274 in #5581, so its compact-scale and a_gather work is gone and this branch no longer overlaps it. The only conflict left is the scale staging in launch_gemm_a8w4_tdm: take main's ceildiv helpers from #5476 while keeping row_major_ascale dropped, which is what this branch's compact path replaces. Also drops AS_ROW. It was defined as (K // 128) * wmma_m_rep * 16, which is exactly the AS_FULL_INNER that already existed a few lines above, and the merge had already moved its uses over to that name.
The stage1 quant+preshuffle kernel gave every warp one route, so the topk routes that share a source token each re-read and re-quantized the same row: at topk=6 that is 6x the necessary read traffic. A warp now owns one source token and scatters the single quantized result to all of its grouped rows. Routes with no destination (EP drops, dead tail) are turned off with a zero-length buffer descriptor instead of a branch, so the quant pass stays one basic block and its loads keep clustering. grid.x counts source tokens now, which is also what selects the ksplit build.
All destinations additionally share one scf.if for the e8m0 scale write. Per-destination branches made the backend re-materialise the shared operands into every region (474 v_mov for six destinations, down to 133). The scale addresses deliberately stay inside the branch: hoisting them cuts more instructions but lengthens live ranges, and at 144 VGPR instead of 108 the lost occupancy costs more than the instructions save on a bandwidth-bound kernel.
Kernel is 1.58x faster across tokens 1024-8192 (125.6us -> 79.5us summed, measured against the unfused path in the same batch to cancel drift), and the output is bit-identical. The unfused build's ISA is unchanged. Set AITER_ROUTEKS_FUSE_DESTS=0 to fall back to the per-route mapping.
Also retunes tokens>=2048 to tile_n=768 and num_buffer_stage2=3, which cuts A-scale re-reads by a third and deepens the stage2 TDM pipeline.
Motivation
Technical Details
Test Plan
Test Result
Submission Checklist