Skip to content

[FlyDSL] [gfx1250] Speed up the grouped-MoE route, quant, and gather-reduce epilogues - #5313

Merged
junhaha666 merged 15 commits into
mainfrom
wjx/psum_opt
Sep 11, 2026
Merged

junhaha666 merged 15 commits into
mainfrom
wjx/psum_opt

Conversation

@lalala-sh

@lalala-sh lalala-sh commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Three changes to the gfx1250 grouped-MoE auxiliary kernels, found by profiling
DSv4 TP4 prefill (7168/768, E=384, topk 6) where they had grown to ~30% of the
layer while the GEMMs took the rest.

Grid-stride the contiguous psum row remap

moe_contiguous_psum_remap ran at grid=(1,1,1). The scan it fuses is over E
and costs nothing, but the remap that follows walks every (token, topk) route,
so one workgroup was resolving ~200K routes on a single CU.

Every block now re-runs the cheap scan into its own LDS start table, so the
grid-strided remap resolves starts[expert] from LDS with no cross-block
barrier; only block 0 writes the global outputs. This is the treatment
moe_contiguous_psum_remap_ep already had. A dedicated MAX_REMAP_EXPERTS
table (8KB of the 320KB budget) lets the chunked, carry-based scan stay, so E
is not capped at the 512-lane scan width and the single-block variant is
deleted rather than kept as a wide-E fallback.

psum kernel   4096 tokens    30.2us -> 3.8us   (7.9x)
             32768 tokens   227.7us -> 5.1us   (45x)

LDS route cache + one flat resource in gather-reduce

Cherry-picked from wjx/opt_small_ops. The topk route rows and weights are
block-uniform, so caching them in LDS drops 12 redundant per-thread loads, and
addressing grouped_out through one flat buffer resource takes the per-row
descriptor construction out of the load loop.

gather_reduce 16384 tokens   209.0us -> 143.5us  (1.46x, 7.87 -> 11.46 TB/s)

Quantize each token once instead of once per route

The topk=6 stage1 input prep quantized the same hidden row once per route, so a
token's activation was read and converted six times. A new warp-per-token
kernel reads the row once, computes the MX payload and e8m0 scale once, then
emits six destinations. It is dispatched from
flydsl_moe_fused_quant_preshuffle when topk==6 and tokens >= 4096;
AITER_FLYDSL_TOKEN_MULTIDEST_QUANT=0 falls back to the route-ksplit path.

Two things this needs to be worth it:

  • The 16-row-interleaved a1 scale makes the quant pass write 4 B per cache
    line. Storing it row-major instead moves the interleave into gemm1's
    LDS->register read, which is free (row_major_ascale; ~12us off quant at 16k
    tokens, gemm1 unchanged). AITER_FLYDSL_ROWMAJOR_ASCALE=0 reverts.
  • Row-major then lets a row's e8m0 leave as one dwordx4 per 8 MX blocks instead
    of a byte per block.

Hidden rows are staged through LDS by TDM in chunks, each chunk issuing the next
one's DMA before converting the current one. A warp whose token is past the end
takes zero-length destination descriptors rather than a branch, so the staging
barriers stay CTA-uniform for ragged token counts.

quant kernel  16384 tokens    609 MB in 46.6us  (13.1 TB/s)

That is close to the ceiling for this access pattern, which is worth recording
because it says where the remaining headroom is not. Measured separately on the
same shape: reads sustain 16.4 TB/s, writes 12.4 TB/s, and the two are strictly
additive (14.2 + 30.2 = 44.4us predicted vs 44.3us measured), so the pattern's
floor is 44.4us and the quant math itself costs only ~2us. Replacing the payload
stores with TDM 2D or TDM gather-store made it slower, not faster (11.9 vs 13.3
TB/s), and a plain linear dwordx4 stream tops out at 13.5 TB/s -- the existing
buffer_store path is already at 99% of that. The only lever left is writing
fewer bytes: 352 of the 374 MB written are six copies of the same 59 MB, which
would need gemm1 to gather A by row instead of reading it linearly.

Also sets num_buffers=3 for the a4w4 gemm1 rows at 16384/32768 tokens.

Test plan

  • test_flydsl_grouped_gemm_gfx1250.py --scenario verify, a8w4 and a4w4,
    E=384 and E=896 (the latter only reached the single-block psum before)
  • Prefill sweep 4096/8192/16384/32768, accuracy unchanged
    (E=384 a8w4 logits_diff bit-identical at 4.1555e-06)
  • Dropped-route regression above, on a NaN-poisoned row 0
  • Same-session interleaved A/B for both kernels; gather_reduce reads
    identically in both arms of the psum A/B, moe_route in both arms of the
    gather A/B
  • Quant path cross-check: multidest+row-major, multidest+interleaved, and
    the old route-ksplit path give bit-identical logits_diff on a4w4/a8w4 at
    4096 and 16384 tokens
  • Token sweep 1/7/64/1023/1024/2048/4095/4096/4097/4103/8192/12289/16384/
    16385, a4w4 and a8w4 -- covers the 4096 dispatch boundary and ragged
    counts that exercise the zero-length descriptors
  • silu / swiglu / situv2, with and without bias
  • Full tuned-CSV sweep: 85/85 pass, worst logits_diff 9.4e-05 (gate 0.01)
  • EP / multi-GPU (test_mega_moe_gfx1250.py) -- not run, single GPU here.
    Worth a look since the NaN fix is on the EP dropped-route path.

Measured on one gfx1250, SPX/NPS1.

moe_contiguous_psum_remap ran at grid=(1,1,1). The scan it fuses is over E and
costs nothing, but the remap that follows walks every (token, topk) route, so
one workgroup was left resolving ~200K routes on a single CU -- 229.6us at
32768 tokens for a few MB of traffic, two orders of magnitude off roofline and
5.6% of the layer.

Give it the treatment moe_contiguous_psum_remap_ep already had: every block
re-runs the (cheap) scan into its own LDS start table, so the grid-strided
remap resolves starts[expert] from LDS and no block waits on another's scan.
Only block 0 writes the global starts/psum/contiguous_m.

The EP variant keeps its starts in a spare scan buffer, which caps it at one
chunk. A dedicated MAX_REMAP_EXPERTS table (8KB of the 320KB budget) instead
lets the chunked, carry-based scan stay -- so E is not limited to the 512-lane
scan width, and the single-block variant it replaces is deleted rather than
kept as a wide-E fallback. A host-side assert covers E past the table.

Measured on gfx1250, DSv4 TP4 (7168/768, E=384, topk 6, a8w4), idle GPU:

  psum kernel      4096 tokens   30.2us -> 3.8us   (7.9x)
                  32768 tokens  227.7us -> 5.1us   (45x)
  fused_moe e2e    4096 tokens   863.7us -> 845.8us  (-2.1%)
                  32768 tokens  4137.2us -> 4009.2us (-3.1%)

e2e is the mean of 3 interleaved A/B reps; gather_reduce, untouched, reads
identically in both arms of every trace. Accuracy is bit-identical at E=384
(logits_diff 4.1555e-06) and passes at E=896, which the old code could only
serve from the single-block path.
Cache topk route rows/weights in LDS per CTA and use a single flat
in_rsrc with dword-offset loads for grouped_out (~11->15 TB/s on DSV4).

(cherry picked from commit 042aced)
The _frlds rewrite replaced the per-row buffer descriptor with one flat
resource, and with it the zero-sized descriptor that made a dropped EP route
(DROPPED_ROUTE_ROW) read as 0. Dropped routes now clamp to grouped row 0 and
rely on their zero weight to cancel the contribution -- but stage2 need never
have written row 0, and NaN * 0 is still NaN.

Not theoretical: poisoning row 0 and dropping every third route turns the
whole 16384x7168 output into NaN (117440512 of them).

The flat resource already carries the right num_records, so aim dropped
routes one row past the end and let the hardware OOB check return 0, exactly
as the old descriptor did. out_dwords is a build constant, so the divide
folds to a shift, and only the topk threads filling the LDS route cache run
it -- no cost in the load loop.

  dropped 32768/98304, row 0 = NaN, 16384 tokens:
    before   NaN in output = 117440512   max_abs = nan
    after    NaN in output = 0           max_abs = 3.07e-02

3.07e-02 is the bf16 output quantum; the no-drop path measures 3.10e-02.
@lalala-sh
lalala-sh requested a review from a team September 7, 2026 09:22
@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 5313 --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 added the FlyDSL label Sep 7, 2026
@lalala-sh lalala-sh changed the title [FlyDSL] Speed up the gfx1250 grouped-MoE psum and gather-reduce epilogues [FlyDSL][gfx1250] Speed up the grouped-MoE route and gather-reduce epilogues Sep 7, 2026
Formatting only; the Check Code Style with Black job flagged call wrapping in
moe_gather_reduce.py (mostly inherited with the _frlds cherry-pick) and
moe_contiguous_psum.py.
@github-actions github-actions Bot changed the title [FlyDSL][gfx1250] Speed up the grouped-MoE route and gather-reduce epilogues [FlyDSL] [gfx1250] Speed up the grouped-MoE route and gather-reduce epilogues Sep 7, 2026
@coderfeli

Copy link
Copy Markdown
Collaborator

Looks good. e2e validated?

@lalala-sh

Copy link
Copy Markdown
Contributor Author

Looks good. e2e validated?

Not Yet.

@zufayu
zufayu requested a review from coderfeli September 8, 2026 01:26
…x routes

The topk=6 stage1 input prep quantized the same hidden row once per route, so
a token's activation was read and converted six times. Add a warp-per-token
kernel that reads the row once, computes the MX payload and e8m0 scale once,
then emits six destinations. Dispatched from flydsl_moe_fused_quant_preshuffle
when topk==6 and tokens >= 4096; AITER_FLYDSL_TOKEN_MULTIDEST_QUANT=0 falls
back to the route-ksplit path.

Two things this needs to be worth it:

- The 16-row-interleaved a1 scale makes the quant pass write 4 B per cache
  line. Store it row-major instead and move the interleave into gemm1's
  LDS->register read, which is free (~12us off quant at 16k tokens, gemm1
  unchanged). AITER_FLYDSL_ROWMAJOR_ASCALE=0 reverts to the interleaved form.
- Row-major then lets a row's e8m0 leave as one dwordx4 per 8 MX blocks
  instead of a byte per block.

Hidden rows are staged through LDS by TDM in chunks, each chunk issuing the
next one's DMA before converting the current one. A warp whose token is past
the end takes zero-length destination descriptors rather than a branch, so the
staging barriers stay CTA-uniform for ragged token counts.

DSV4 (7168/768, E=384, topk=6, gfx1250) quant kernel at 16k tokens: 609 MB of
traffic in 46.6us (13.1 TB/s). Measured separately, that access pattern's floor
is 44.4us -- reads sustain 16.4 TB/s, writes 12.4 TB/s, and the two are strictly
additive -- so the quant math itself costs ~2us and the rest is bytes on the
bus. Also set num_buffers=3 for the a4w4 gemm1 rows at 16384/32768 tokens.

Verified against the route-ksplit path: both quant paths and both scale layouts
produce bit-identical logits_diff across a4w4/a8w4, tokens 1..16385 (including
ragged 4097/4103 and the 4096 dispatch boundary), and silu/swiglu/situv2. Full
tuned-CSV sweep passes 85/85.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 0bed75879681e006eea22c597227a022fb298392)
@lalala-sh lalala-sh changed the title [FlyDSL] [gfx1250] Speed up the grouped-MoE route and gather-reduce epilogues [FlyDSL] [gfx1250] Speed up the grouped-MoE route, quant, and gather-reduce epilogues Sep 9, 2026
lalala-sh and others added 9 commits September 9, 2026 13:56
Formatting only; the parsed AST of both files is unchanged.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
Drop three import lines that a rebase had duplicated (F811, which also left
the block unsorted for I001) and flatten the chunk-0 prefetch guard into one
condition (SIM102). The const_expr goes first so the Python bool short-circuits
before the traced predicate, matching the existing guard on the next line.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
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]>
…unts

One warp per token gives only token_num/8 blocks, so the kernel that wins at
16k tokens was starving the CUs below a few thousand: measured on DSV4 (7168,
topk 6, fp4, gfx1250) it sustained 0.37 TB/s at 64 tokens against 13.2 at
16384, and achieved bandwidth tracked the block count almost exactly -- 3.1% of
the CUs busy, 2.8% of the bandwidth. It was not inefficient, just too narrow.

An MX block scale covers 32 contiguous elements, so a row's K groups are wholly
independent: splitting them over grid.y widens the grid without reintroducing
the per-route requant this kernel exists to avoid. The split targets ~1024
blocks (4x the CUs) and stops there, which is where every token count from 8 to
32768 measured fastest; past it the deeper split only multiplies the per-block
route setup. Splitting costs the TDM staging pipeline, so a split block drops it.

Two thresholds move as a result:

- The staging depth is now 2 chunks below 4096 tokens and 7 above. Each chunk
  costs a tensor_wait and two CTA barriers, which a narrow grid cannot hide:
  512 tokens 7.31 vs 9.33 us, 2048 10.67 vs 12.22, 16384 50.75 vs 46.72.
- The dispatch threshold drops from 4096 to 64 tokens. With both kernels now
  splitting K, multidest wins from ~32 tokens up; below that one warp per token
  cannot fill a grid whatever the split, while one warp per route starts with
  topk times as many.

Quant kernel through the production dispatch, route-ksplit vs multidest:

     64 tokens    3.43 ->  3.09 us   1.11x
    256 tokens    6.40 ->  4.15 us   1.54x
    512 tokens   10.24 ->  5.90 us   1.74x
   2048 tokens   20.21 -> 13.63 us   1.48x
   8192 tokens   56.65 -> 36.37 us   1.56x

End-to-end this is under the noise floor -- at 512 tokens the quant kernel is
~2% of fused_moe, so 4.3us off it does not show. The win is the kernel, not the
layer; it matters if the epilogue is ever hoisted or the batch shape changes.

Every K-split output is bit-identical to the unsplit one, and to the
route-ksplit path, across 8..32768 tokens. a4w4/a8w4 logits_diff unchanged
across the new 64-token boundary (63/64/65 continuous); tuned-CSV sweep 85/85.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
… the batch

The TDM staging depth was the constant 7, which divides model_dim 7168's 28
wave iterations but not model_dim 4096's 16. Anything that reached the
token-multidest path at another model_dim raised out of the builder's own
geometry check:

    ValueError: tdm_hidden_chunks=7 must divide block_iters=16 ...

The tuned CSV has such rows (4096 / E=256 / topk 6, to 32768 tokens) and they
only survived because the K-split now drops staging below 8192 tokens, and
before that because the dispatch threshold was above their token counts. Pick
the depth from the row's divisors instead, so it is 7 at 7168 and 4 at 4096.

While here, two things the K-split made stale:

- The depth no longer keys on token count. That heuristic chose 2 chunks below
  4096 tokens, but a split block drops staging entirely, so the shallow arm was
  unreachable the moment K-split landed. It now keys on ksplit, which is what
  the builder actually acts on, so the two cannot disagree.
- The split's block target was the literal 1024, i.e. 4x this part's 256 CUs.
  Read the CU count instead; a narrower partition was aiming at four times its
  real width.

model_dim 4096 at 8192 tokens now builds and runs (logits_diff 8.0606e-06);
DSV4 is unchanged at 512 / 8192 / 16384 tokens, tuned-CSV sweep 85/85 twice.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
…seven

The depth curve is a bowl and both sides of the floor are wide. Measured on
DSV4 (7168, topk 6, fp4, gfx1250) at 16384 tokens: 1 chunk 59.4 us -- worse
than not staging at all, since the prologue then waits on the whole row with
nothing to overlap -- 2: 50.7, 4: 47.4, 7: 46.7, 14: 48.1, 28: 53.4, none:
48.1. Past four, the per-chunk tensor_wait and two CTA barriers cost more than
the smaller transfer saves; at 28 that is 56 barriers for 512 B of DMA a warp.

Four and seven are within 0.6% of each other and trade places by batch (8192:
25.44 vs 25.57, 32768: 88.86 vs 89.15, 16384: 47.40 vs 46.70), so this is not a
speed change. It is that four divides 7168's 28 wave iterations, 4096's 16 and
2048's 8 alike, where seven divides only the first: every model_dim now takes
the same depth instead of leaving one shape on a path of its own.

Worth recording while the numbers are here: staging at all is only worth 2-5%
over the plain buffer_load path. That is consistent with the earlier finding
that reads and writes are strictly additive on this kernel -- there is little
for the transfer to hide behind.

DSV4 logits_diff unchanged at 512 / 8192 / 16384 / 32768 tokens, a4w4 and a8w4;
tuned-CSV sweep 85/85.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
The comments around the K-split and staging constants had grown into
measurement logs: the depth sweep, the dispatch crossover, and the block-count
rationale were all transcribed inline. Those numbers say where a constant came
from, which is what the commit that set it is for; a reader here needs the
constraint the code cannot show -- that one chunk is degenerate, that a K slice
needs no cross-block reduction, that a chunk must divide the row.

Also drops a docstring reference to _TOKEN_MULTIDEST_TARGET_BLOCKS, renamed to
_TOKEN_MULTIDEST_BLOCKS_PER_CU when the target started reading the CU count,
and de-duplicates the K-split rationale between the builder and the helper that
chooses it.

Comments only. DSV4 logits_diff unchanged at 512 and 16384 tokens.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
… just six

The kernel was written against DSV4 and said so: the route stride, the
destination list and the dispatch gate all carried a literal 6, and the name
carried it too. Nothing downstream did -- the payload stores, the scale stores
and the packed row-major stores already iterate the destination list -- so the
literal was the only thing tying a general technique to one model.

Take topk as a parameter. What the kernel saves is the topk-1 redundant reads
and requants of the same hidden row, so the payoff grows with topk rather than
being a property of six; what it costs, a buffer descriptor per destination
live across the store pass, grows with it too, hence the cap.

Route-ksplit vs multidest, 7168 / E=256 / fp4, bit-identical output throughout:

    topk 2   1024 tokens   7.94 ->  5.58 us  1.42x     8192   24.14 -> 20.75  1.16x
    topk 4   1024 tokens   9.92 ->  6.98 us  1.42x     8192   39.67 -> 28.56  1.39x
    topk 6   1024 tokens  12.09 ->  8.49 us  1.43x     8192   56.57 -> 36.24  1.56x
    topk 8   1024 tokens  13.06 ->  9.98 us  1.31x     8192   68.34 -> 43.54  1.57x

The large-batch gain rising with topk is the saving showing up as predicted;
topk 8 giving back a little at 1024 tokens is the descriptor pressure.

topk=1 still routes to route-ksplit, where a token has one destination and
there is nothing to amortise. DSV4 logits_diff unchanged at 63 / 64 / 512 /
16384 tokens; tuned-CSV sweep 85/85.

Co-authored-by: XingerZhu <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
@junhaha666
junhaha666 merged commit 2aac63b into main Sep 11, 2026
52 of 57 checks passed
@junhaha666
junhaha666 deleted the wjx/psum_opt branch September 11, 2026 04:38
junhaha666 pushed a commit that referenced this pull request Sep 18, 2026
* [FlyDSL] [gfx1250] Quantize the MoE a1 scale compact and rebuild it in one launch

The stage1 quant pass wrote its e8m0 straight into the 16-row-interleaved WMMA
layout, once per route. That layout spaces a row consecutive blocks wmma_rep*16
dwords apart, so every store landed 4 useful bytes in a 64 B line, and topk
repeated it: at 16384 tokens the scale cost 143 us of a 68 us pass.

#5313 had answered this by letting the quant write row-major and moving the
interleave into gemm1 LDS read. That is the layout #5391 then dropped, because
producer and consumer derived the choice independently and disagreed under EP.
This keeps the single interleaved layout gemm1 reads and fixes the write
instead: one compact row-major row per source token, then a rebuild pass that
walks destination tiles so both its load and its store cover whole lines.

The rebuild cannot run inside the token loop. A cache line of the interleaved
scale spans 16 consecutive grouped rows, which belong to 16 unrelated tokens; no
workgroup owns them, so it needs every token quantized first. A persistent grid
plus a spin barrier buys that ordering without a second launch, reusing the
protocol build_moe_fused_route_psum_quant_scatter_module already uses. Two
blocks per CU: one also works but gives up the cross-block latency hiding, and
measured 93 us against 75.

Falls back to the scattered write when the shape cannot take it -- prequantized
input, EP route counts, a routing the token-multidest quant does not cover, or a
scale row too wide to stage a tile in LDS.

Measured on gfx1250, a4w4, 16384 tokens, 7168/768, E=384, topk=6, no bias
(device time summed over the layer kernels):

  scattered interleaved write   1014 us   quant 143.1
  compact + rebuild, 2 launches  915 us   quant 54.3 + rebuild 7.9 + map 6.1
  compact + rebuild, 1 launch    953 us   quant 75.1

The two-launch form is faster on device and the one-launch form on wall time:
merging the passes saves two launches but the persistent grid costs the GEMMs
after it about 30 us. This ships the single launch; logits_diff is 3.5076e-06 on
all three, unchanged from the scattered write.

Also packs the fallback scattered write into one dword per 4 MX blocks, which
share a destination dword in the interleaved layout too (143.1 -> 142.7 us).

* [FlyDSL] Format the fused MoE quant kernel for black and ruff

Style only, no behaviour change. Four things CI would have caught:

  - black 26.5.1 wants a blank line after two module-level statements the
    branch touched.
  - The LDS-budget environment knob went away with the simplification, and
    took the only use of `os` in this module with it.
  - The fused builder inherited dst_scale_dwords_per_row and its constants
    from the plain one, but its scale destination is the source token row,
    so nothing reads them.
  - Phase 1 closures captured the persistent loop token0, which ruff reports
    as B023 even though the tracer walks the body once. Taking it as a
    parameter binds them to a local and says the same thing more directly.

ruff 0.16.0 and black 26.5.1, the versions pre-checks.yaml pins, are clean on
the five changed files. logits_diff stays 3.5076e-06 and the fused kernel 74.4
us at 16384 tokens; pre- and post-format trees measured 1097.58 us against
1097.58 on the same machine state.

* [FlyDSL] [gfx1250] Address the grouped MoE output past 4 GiB in gather-reduce

The gather-reduce pass read grouped_out through one buffer descriptor covering
the whole tensor, indexed in dwords. Two 32-bit quantities in that scheme break
once the tensor passes 4 GiB, which contiguous_m * model_dim * 2 does at around
48k tokens with topk=6:

  - The descriptor bound was built as an i32 product of dwords and 4. Landing
    in the negative half is harmless -- create_buffer_resource_from_addr sign
    extends to the i64 num_records field, and the hardware reads that as a huge
    unsigned bound -- so the wrap goes unnoticed until it crosses 2**32 and
    lands on a small positive bound instead. At 301056 rows that bound is 20 MB
    and every row past it reads as zero.

  - The buffer offset itself is 32-bit, so even a correct bound cannot reach
    the far end of the tensor.

Folding the grouped row into the 64-bit descriptor base fixes both: the offset
then only has to span one row. The base is loop-invariant, so the address math
runs once per route instead of once per access -- which is also why this is not
slower. A dropped EP route now takes a zero-length descriptor rather than an
out-of-range row, so switching its loads off no longer depends on the bound the
first hunk just changed.

Measured on gfx1250, 7168/3072, E=96, topk=6, logits_diff against the fp32
reference (gate 0.01):

  tokens   before      after
   16384   4.22e-06    4.22e-06
   48128   9.90e-01    4.23e-06
   49152   9.51e-01    4.23e-06
   65536   nan         4.22e-06

a4w4 moves with it: 47104 tokens 9.50e-01 -> 6.65e-06, 65536 nan -> 6.67e-06.
The route-ksplit quant faulted outright at these sizes (Memory access fault on
a page not present); the multidest one only wrote the zeros, because its stores
go through descriptors whose bounds check drops them silently.

bench_gfx1250_combo.py --dsv4 --ops moe now passes all ten token tiers. The
gather-reduce kernel measures 108.3 us against 113.8 at 16384 tokens, a4w4
7168/768 E=384, interleaved over three pairs.

* [FlyDSL] [gfx1250] Split the MoE scale rebuild into its own launch

The compact-scale quant and the WMMA scale rebuild ran as one launch over a
persistent grid of cu_num*2 workgroups, separated by a hand-rolled grid-wide
spin barrier. FlyDSL has no cooperative launch, so nothing makes those
workgroups co-resident, and the barrier deadlocks if even one of them is not:
the others spin forever, the kernel never returns, and the device reads as
100% busy while producing nothing. A serving runtime cannot promise that
residency -- collectives and other streams hold CUs of their own -- so this
only ever held on a benchmark that owned the device.

Launching the two phases back to back on one stream buys the same ordering
from the inter-kernel dependency and assumes nothing about residency. Both
were already grid-stride loops, so a grid that just covers the work leaves
each block one iteration, and each kernel now allocates only the LDS its own
phase uses. The pair is also the faster of the two at prefill sizes, 65.6 us
against 79.4 at 16384 tokens and wmma_rep=2, since the persistent grid slowed
the GEMM behind it.

Below roughly a thousand tokens the pair loses to writing the interleaved
scale inline: the rebuild launch is a fixed cost, while coalescing the scale
write pays off only in proportion to the token count. Gate the compact path on
batch size, with a higher threshold at wmma_rep=1 whose narrower interleave
stride is exactly one cache line:

  inline / pair, us, run_perftest with rotated inputs, fd7168 topk=6 fp4
  wmma_rep=1   512  7.1/11.8   1024  10.7/12.6   2048  18.4/14.4
  wmma_rep=2   512  8.4/12.0   1024  15.3/13.0   2048  23.5/14.8

AITER_FLYDSL_COMPACT_SCALE_MIN_TOKENS overrides the threshold.

Since the two paths fill the same buffer gemm1 reads, they cross-check
bitwise: payload and interleaved scale agree on both sides of the threshold,
at wmma_rep 1 and 2, and with padding tiles exercising the rebuild's
zero-fill. End to end on a4w4 the logits_diff is unchanged at 3.60e-06.

* [FlyDSL] [gfx1250] Reuse the scatter-copy kernel for the MoE scale rebuild

The compact scale path had its own rebuild kernel, but
build_moe_scatter_copy_preshuffle_scale_module already turned a compact
per-token scale plus a grouped-row -> token map into the interleaved layout the
GEMM reads, with the same index math and the same -1 padding rule. Two copies of
one pass, and only ours was outside the oracle test in test_flydsl_moe_aux.

What ours had that the shared one lacked was LDS staging. Written straight out,
adjacent lanes read adjacent grouped rows, so the source side moves one dword
per line; going through LDS lets the load walk a row instead and leaves both
sides on whole lines. Port that over, keeping the direct path for a tile too wide
to stage, since this module also serves gather=False and wider scale rows.

The shared kernel then beats the one it replaces -- 7.9 us against 9.4 at 16384
tokens wmma_rep=2, 7.5 against 8.6 at wmma_rep=1 -- because it takes one tile per
workgroup off a 2D grid rather than a grid-stride loop. Output is bitwise equal
on every shape tried.

Net effect on the layer is a wash, which is expected at 12% of the pair: r1/2048
13.9 us against 14.4, r2/1024 12.8 against 13.0, 16384 unchanged either way.
gemm1/gemm2 stay at 1945/1024 us and logits_diff at 3.6030e-06.

Drops 139 lines: build_moe_scale_rebuild_module, its compile cache, and the
fused_preshuffle_out parameter that selected it. row_to_token now selects the
compact scale on its own, and the caller does the rebuild -- one launch each,
which is what the pair always was.

---------

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

3 participants