Skip to content

[Triton/Gluon] Add tiled MoE sorting for M3 prefill - #5822

Closed
whx-sjtu wants to merge 11 commits into
mainfrom
hexwang/m3-sp-kernels
Closed

whx-sjtu wants to merge 11 commits into
mainfrom
hexwang/m3-sp-kernels

Conversation

@whx-sjtu

@whx-sjtu whx-sjtu commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add opt-in Triton tiled MoE sorting for large M3 MXFP4 prefill batches in the existing FlyDSL MoE pipeline. Per-tile histograms, prefix sums, and stable scatter produce the packed token IDs, expert padding, weights, and optional auxiliary mappings consumed by aiter.fused_moe.

aiter/ops/triton/
  _triton_kernels/moe/moe_sorting_tiled.py   histogram / prefix / stable scatter
  moe/moe_sorting_tiled.py                  wrapper and eligibility checks
  configs/gfx950/triton/moe/sorting_tiled/   launch configuration
aiter/fused_moe.py                          forwards the sorting opt-in
op_tests/                                  sorting tests and benchmark

use_tiled_sort defaults to False for generic callers. The eligible M3 path uses gfx950, at least 8,192 tokens, 129 experts, top-k 5, hidden size 6,144, intermediate size 768, and block size 64 with the supported MXFP4 layout. Unsupported contracts fall back through the existing dispatcher, including tuned block-128 layouts and caller-provided output buffers. ATOM selects the opt-in for supported native M3 SP layers.

This PR contains six files implementing the Triton sorter and its integration. The HIP sequence-parallel collectives are in #6031; both PRs target main and can be reviewed and merged independently. The downstream consumer is ROCm/ATOM#2364.

Evidence

  • Before: the existing Opus sorter takes 72.43–74.81 µs at 32,768 tokens across the six measured M3 routing distributions.
    After: the tiled sorter takes 41.94–42.24 µs, or 1.72–1.78× faster, while preserving the stable packed-output contract. These are the historical 67405e7fd measurements documented below.
  • After the split, the complete sorting test file passes 88 tests on gfx950 with the CI Triton wheel 3.8.0+amd.rocm7.2.0.git7cb7b059, FlyDSL 0.3.4.1, and pytest 8.3.4. Coverage includes shape/distribution variants, dispatch boundaries, changed-input graph replay, optional auxiliary maps, and bitwise M3 MoE comparisons at 8,192, 32,768, and 65,537 tokens. The integration test accepts the tuned block-128 fallback.
  • The six-file patch is byte-identical to the sorting contribution in a70f4fef9071f8b9b2bf25884b38bb6184b4d207. Combining it with the HIP patch reconstructs that source tree exactly. Black, Ruff, and git diff --check pass.
python -m pytest -q op_tests/triton_tests/moe/test_moe_sorting_tiled.py
# 88 passed

Prefill threshold and routing-distribution validation

The tiled-sort dispatch now accepts 8192 <= T < 2**24 with the existing M3 contract (int32[T, 5] IDs, float32[T, 5] weights, 129 experts, hidden size 6,144, block size 64, contiguous gfx950 inputs, and no accumulation buffer). 2**24 is the packed token-ID format limit. The lower cutoff keeps a margin over the actual Opus fallback, including partial token tiles. The existing dtype, layout, quantization and caller-eligibility checks still apply.

For more than 32 token tiles, prefix computation runs independently per expert, followed by a small expert-offset prefix. This avoids concentrating the whole expert-by-tile prefix in one GPU block and removes the regressions observed at non-power-of-two and larger token counts. The switch uses the existing JSON configuration; no environment variable is added.

Historical validation at 67405e7fd: 55 GPU tests passed, including dispatch/fallback boundaries, packed-token limits, optional auxiliary mappings, changed-input graph replay, and exact M3 MoE output comparisons at 8,192, 32,768, and 65,537 tokens. The performance matrix covers 15 token counts × 6 routing distributions × 3 seeds = 270 inputs, all passing stable-order, weight and padding checks for both sorters before and after timing. The existing Triton core is also checked and measured on the same 18 inputs at 32,768 tokens.

Distributions are balanced/shuffled, balanced/clustered (identical paired expert histograms), uniform, Zipf sampling proportional to rank⁻¹·⁵ without replacement, hot-eight, and collapsed-four. Every token has four distinct routed experts from 128 plus shared expert 128. Seeds are 7, 19, and 73; expert labels are permuted per seed, routed weights are normalized, and the shared weight is 1.

Timing on gfx950, implementation 67405e7fd1f4: mean GPU latency, three trials × 16 graph replays per seed, 32 sequential calls per replay; input generation, allocation and capture are excluded. Opus and tiled receive identical inputs and emit the legacy packed output without optional auxiliary maps. Each range below spans six distribution means, each averaged over three seeds. Opus includes its internal workspace clearing.

Tokens Original Opus (µs) New tiled (µs) Opus / tiled
8,192 23.87–24.58 17.28–17.34 1.38–1.42×
8,193 24.95–25.58 20.19–20.32 1.24–1.27×
10,003 28.52–29.32 22.27–22.59 1.27–1.32×
16,384 39.40–40.56 26.31–26.41 1.49–1.54×
16,385 40.46–41.74 29.42–29.72 1.37–1.42×
32,768 72.43–74.81 41.94–42.24 1.72–1.78×
32,769 73.68–76.00 47.63–48.01 1.54–1.60×
65,536 137.84–145.71 73.57–74.22 1.87–1.98×
65,537 139.83–147.48 84.16–85.64 1.66–1.75×
98,304 204.13–227.64 105.88–108.51 1.91–2.14×
131,072 270.30–296.70 137.93–140.74 1.95–2.14×
131,073 272.92–301.65 159.20–164.12 1.71–1.89×
196,608 401.04–466.69 202.45–206.71 1.98–2.31×
262,144 533.43–623.01 267.17–272.17 1.98–2.33×
1,048,576 2242.43–2522.09 1038.02–1055.20 2.15–2.43×
Three-way comparison at 32,768 tokens

The existing Triton column measures sort_tokens only; bitmatrix preparation, scratch reset, and conversion to legacy packed output are excluded. Each native call uses separate scratch, cleared before the timed interval. Values are means over the same three seeds.

Routing distribution Original Opus (µs) Existing Triton sort_tokens only (µs) New tiled (µs)
Balanced, shuffled 73.29 107.82 41.98
Balanced, clustered 72.43 105.53 41.94
Uniform 73.31 107.70 42.11
Zipf (1.5) 72.70 106.42 42.24
Hot 8 72.80 105.77 42.14
Collapsed 4 74.81 105.55 42.12

Merge Danger

Door: two-way

Blast Radius: sorting

The optimized dispatch is opt-in and restricted to the supported M3 contract. The standalone sorter supports additional shapes, but the production gate remains limited to the validated M3 layout. This changes the sorting stage used by the existing GEMM pipeline, so packed IDs, padding, and auxiliary mappings must remain compatible with its consumers.

@whx-sjtu
whx-sjtu requested a review from a team September 24, 2026 13:29
@github-actions

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 5822 --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 Add opt-in M3 sequence-parallel collectives and tiled MoE sorting [Triton/Gluon] [HIP] [JIT] Add opt-in M3 sequence-parallel collectives and tiled MoE sorting Sep 24, 2026
@azaidy
azaidy requested review from lburzawa and nsusanto September 24, 2026 13:52
@Boss2002n
Boss2002n requested a lite review from Copilot September 24, 2026 17:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Critical alignment and head-exchange integration issues remain, along with required coverage and separation changes.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 1 Medium severity

Open (2)
What changed in this PR

Adds opt-in M3 sequence-parallel communication kernels and tiled MoE sorting for gfx950 workloads.

Changes:

  • Adds QuickReduce reduce-scatter and head-exchange kernels.
  • Adds stable, configured tiled MoE sorting with tests and benchmarks.
  • Propagates use_tiled_sort through fused MoE APIs.

Outstanding findings include staged-buffer alignment validation, missing head-exchange build/API registration, absent AITER reduce-scatter coverage, and the requested separation of MoE sorting from collective changes.

File Reviewed change
op_tests/​triton_tests/​moe/​test_moe_sorting_tiled.py Tiled sorting correctness and dispatch tests
op_tests/​op_benchmarks/​triton/​bench_moe_sorting_tiled.py Native-versus-tiled sorting benchmark
csrc/​pybind/​sp_head_exchange_pybind.cu Head-exchange bindings
csrc/​pybind/​quick_reduce_scatter_pybind.cu Reduce-scatter bindings
csrc/​kernels/​sp_head_exchange.cu Head-exchange implementation
csrc/​kernels/​quick_reduce_scatter.cu QuickReduce implementation
aiter/​ops/​triton/​moe/​moe_sorting_tiled.py Tiled sorter wrapper and dispatch guard
aiter/​ops/​triton/​configs/​gfx950/​triton/​moe/​sorting_tiled/​DEFAULT.json Tiled sorter launch configuration
aiter/​ops/​triton/​_triton_kernels/​moe/​moe_sorting_tiled.py Histogram, prefix, and scatter kernels
aiter/​ops/​quick_reduce_scatter.py Public reduce-scatter API
aiter/​jit/​optCompilerConfig.json Reduce-scatter build registration
aiter/​fused_moe.py Tiled-sort API propagation

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +58 to +59
AITER_CHECK(stage || reinterpret_cast<uintptr_t>(input.data_ptr()) % 16 == 0,
"registered head exchange input requires 16-byte alignment");
Comment on lines +14 to +17
PYBIND11_MODULE(AITER_EXTENSION_NAME, m)
{
AITER_SET_STREAM_PYBIND;
m.def("sp_head_exchange", &aiter::sp_head_exchange);
@lburzawa

Copy link
Copy Markdown
Contributor

Could you provide more context on this change as compared to existing moe sorting codebase? We already have moe routing/sorting kernels in aiter triton. How is your different/better? Is it meant to be used with aiter triton moe gemms or some other backend?

@whx-sjtu whx-sjtu changed the title [Triton/Gluon] [HIP] [JIT] Add opt-in M3 sequence-parallel collectives and tiled MoE sorting [Triton/Gluon] [HIP] [JIT] Add M3 sequence-parallel collectives and tiled MoE sorting Sep 28, 2026
@whx-sjtu

Copy link
Copy Markdown
Contributor Author

Could you provide more context on this change as compared to existing moe sorting codebase? We already have moe routing/sorting kernels in aiter triton. How is your different/better? Is it meant to be used with aiter triton moe gemms or some other backend?

hi @lburzawa, thanks for the review. This change targets large-prefill sorting in aiter.fused_moe. The measured workload uses FlyDSL MXFP4 two-stage GEMMs. It replaces the existing Opus/HIP sorting stage while preserving the packed token IDs, expert padding, weights, and optional auxiliary mappings expected by that pipeline. GEMM dispatch remains unchanged.

The tiled implementation uses per-tile histograms, prefix sums, and parallel stable scatter to avoid Opus’s dense expert–token mesh and parallelize its long per-expert scan. Existing Triton routing implementations produce different routing metadata and gather/scatter indices, so reusing them here requires an adapter. Histogram/prefix/scatter itself is not a new algorithm.

For the measured 32,768-token workload, sorting latency decreased from 72.79 µs to 42.49 µs versus Opus, with about 0.25% lower full-MoE latency. I haven't compared with existing triton sorter yet, and will provide detailed data after comparing locally.

@whx-sjtu

Copy link
Copy Markdown
Contributor Author

@lburzawa I have posted comparing results in PR description.

@@ -0,0 +1,232 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
"""Stable MoE sorting for the M3 prefill contract selected by the caller.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a note here that the kernel is meant to be used with Flydsl MOE pipeline.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@lburzawa

Copy link
Copy Markdown
Contributor

@whx-sjtu thanks for explanation. Let's add a comment that the kernel is meant for Flydsl MOE stack otherwise should be good to go on triton side.

Comment thread aiter/fused_moe.py Outdated
Comment on lines +1459 to +1460
# Explicit call-site opt-in; metadata/kernel selection is unchanged.
use_tiled_sort = (

@nsusanto nsusanto Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does E==129 and model_dim==6144 check in try_m3_tiled_sort. This is redundant and can be removed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

@azaidy
azaidy requested a review from coderfeli September 30, 2026 18:06
@azaidy

azaidy commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@coderfeli can you also review. I think this is trying to use Triton routing with FlyDSL MoE

lburzawa
lburzawa previously approved these changes Sep 30, 2026

@lburzawa lburzawa left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good on triton side but needs a HIP/Flydsl reviewer since it's meant to be used with Flydsl MOE.

@rahulbatra85

Copy link
Copy Markdown
Contributor

This PR should be split into 2. One for each each backend ie Triton/Gluon and HIP

@rahulbatra85 rahulbatra85 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Split into 2 PRs. One for just Triton/Gluon and other for any hip/flydsl/ck related changes.

@whx-sjtu

whx-sjtu commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Split into 2 PRs. One for just Triton/Gluon and other for any hip/flydsl/ck related changes.

sure, will do.

Keep the Triton tiled sorter, fused-MoE integration, configuration, tests, and benchmark in this PR. Move the unchanged QuickReduce reduce-scatter and head-exchange kernels, bindings, public wrappers, JIT registrations, and multi-GPU tests to hexwang/m3-sp-hip-collectives.
@github-actions github-actions Bot changed the title [Triton/Gluon] [HIP] [JIT] Add M3 sequence-parallel collectives and tiled MoE sorting [Triton/Gluon] Add M3 sequence-parallel collectives and tiled MoE sorting Oct 1, 2026
@whx-sjtu whx-sjtu changed the title [Triton/Gluon] Add M3 sequence-parallel collectives and tiled MoE sorting [Triton/Gluon] Add tiled MoE sorting for M3 prefill Oct 1, 2026
@whx-sjtu

whx-sjtu commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@rahulbatra85 Splited. Another PR is #6031

junhaha666 pushed a commit that referenced this pull request Oct 9, 2026
Split the unchanged HIP contribution out of PR #5822: four-rank INT4 QuickReduce reduce-scatter and direct token-major head exchange, with JIT registration, public wrappers, and head-exchange tests. The Triton sorter remains independent in #5822.
whx-sjtu added a commit to ROCm/ATOM that referenced this pull request Oct 20, 2026
Fixes:
- Pass token counts to the SP pack and FP8 transport Triton kernels at
  run time; as constexprs every new prefill length recompiled them.
- Drop the MegaMoE block's placeholder scale when the next layer does
  not consume per-token FP8 input.
- Import CacheCompiledArtifact only on torch 2.10+, where it exists.
- Small batches skip the fused MegaMoE prefix and run the native MoE
  directly, instead of a prefix, extra copies and a routing gather.
- Reset the shared MegaMoE runtime before its int32 launch epochs wrap.
- Resolve the optional QuickRS op once at import.

Removed:
- The MegaMoE benchmark, the non-fused MegaMoE paths only it reached,
  MXFP8 activation and the diagnostic activation override.
- Tiled MoE sort selection, which needs the unmerged ROCm/aiter#5822.
- The MegaMoE experiment scripts, manifest and handoff notes.
- A redundant compile-hash factor and an unrelated import reorder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@azaidy
azaidy requested review from lburzawa, nsusanto and rahulbatra85 and a lite review from Copilot October 21, 2026 18:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Fix the use_tiled_sort scoping error, FHMoE flag propagation, and oversized boundary-test allocation.

3 open issues

Review effort: Lite

Comment thread aiter/fused_moe.py
Comment on lines +1471 to +1472
use_tiled_sort = (
use_tiled_sort
@@ -0,0 +1,459 @@
# SPDX-License-Identifier: MIT

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets put this file under op_tests/triton_tests/moe/moe_routing folder.

@lburzawa

Copy link
Copy Markdown
Contributor

We will need to resolve conflict before merge. Please also check any unresolved copilot comments.

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 7, 2026
@lburzawa

Copy link
Copy Markdown
Contributor

Closing due to inactivity, please reopen/resubmit if still relevant.

@lburzawa lburzawa closed this Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale The PR hasn't been updated in 2 weeks Triton/Gluon

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants