Skip to content

[moe][perf] Argsort expert ids on the narrowest integer type (2/4) - #5436

Merged
felipemello1 merged 6 commits into
mainfrom
felipemello1/gen-perf/8-narrow-argsort
Nov 8, 2026
Merged

felipemello1 merged 6 commits into
mainfrom
felipemello1/gen-perf/8-narrow-argsort

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: The MoE dispatch sorts expert ids as uint8 (up to 256 experts) or int16 instead of int64, so the radix sort makes 1-2 passes instead of 8. Qwen3.5-35B-A3B, 2 layers, 1 GB300: prefill 1024 tokens 1447 -> 1296 us (-10.4%), decode 64 711 -> 683 us (-4.0%). Same order, bitwise.

Stack (4 PRs, merge bottom-up; this PR is in bold)

# PR Independent? Needs (stack positions)
1 AllToAll dispatcher: permute and unpermute with gathers yes —
2 Argsort expert ids on the narrowest integer type yes —
3 Gather-sum MoE dispatch and combine, training and inference, any EP no 2
4 Turn on gather-sum dispatch and combine for DeepSeek-V3/V4, Kimi K3, GPT-OSS and Qwen3 MoE no 3

Problem

  1. Sort. Every dispatch sorts the T * top_k routes by expert: torch.argsort(expert_ids, stable=True) in _local_reorder (EP=1, and EP>1 before the all-to-all; training and inference).
  2. Keys. The router returns int64 ids, so the radix sort sorts 64-bit keys.
  3. Passes. CUB's radix sort makes one pass per key byte, plus memsets: 8 passes, though 256 experts fit in 1 byte.
  4. Cost. One Qwen3.5-35B-A3B MoE layer at 1024 tokens (8192 routes): the sort kernels and their memsets take 88 us of the layer's 755 us.

Solution

  1. LocalTokenDispatcher.__init__ picks the sort dtype once from num_experts: uint8 (<= 256 experts), int16 (<= 32,768) or int64, stored as expert_ids_sort_dtype.
  2. _local_reorder casts the ids to it before torch.argsort(stable=True). Every dispatcher inherits it, and the dtype is the same in training and inference.
  3. Compile sees a constant dtype on the module: no branch per call, no graph break.
  4. Unchanged: the order (a stable sort on the same keys). More than 32,768 experts keep int64.

Results

Numerics: bitwise identical (stable sort on the same keys).

torch.argsort(stable=True) of top-8 expert ids (E=256), 1 GB300, CUDA-graph replay, us
routes      int64   int16   uint8
272          26.6    12.0     9.7
2,048        28.3    12.7    10.6
32,768       65.7    28.9    18.8
262,144      84.1    33.0    23.0
524,288      96.8    37.3    26.9

Qwen3.5-35B-A3B, 2 layers (GDN + gated attention, each with a 256-expert MoE), no_grad, EP=1, the model's
regions, compiled in the generator's order (2048, 1536, then largest to smallest), CUDA-graph replay, 1 GB300, us.
One process per arm, one run per row. Before = main (stack position 1 only changes EP>1 code).
tokens          main    this PR
decode 32        686      654    -4.6%
decode 64        711      683    -4.0%
decode 128       746      714    -4.3%
decode 256       818      725   -11.4%
prefill 1024    1447     1296   -10.4%
prefill 2048    2045     1890    -7.6%
prefill 4096    3280     3184    -2.9%
prefill 8192    6013     5912    -1.7%
decode 1-16: within 1.4% of main (noise)

One layer, prefill 1024, kernel diff: radix-sort kernels 67.6 us in 10 launches -> 20.8 us in 3; memsets 20.1 -> 12.6 us.

NOTE:

  • Expert ids must be in [0, num_experts), as the grouped GEMM already requires.
  • Training: not timed at layer level. The table gives -70 us per sort at a 64k-token microbatch (524,288 routes).

Test plan

pytest tests/unit_tests/cpu/models/common/test_token_dispatcher.py

test_narrow_key_argsort_matches_int64_argsort: uint8, int16 and int64 keys give the same stable order.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 15, 2026
@felipemello1
felipemello1 added this pull request to stack #5388 October 15, 2026 23:37
@felipemello1
felipemello1 removed this pull request from stack #5388 October 18, 2026 04:16
@felipemello1
felipemello1 changed the base branch from felipemello1/gen-perf/3-train-gather-combine to main October 18, 2026 04:16
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from d95ec05 to a84819b Compare October 18, 2026 04:17
@felipemello1
felipemello1 changed the base branch from main to felipemello1/gen-perf/3-train-gather-combine October 18, 2026 04:17
@felipemello1
felipemello1 added this pull request to stack #5497 October 18, 2026 04:18
@felipemello1 felipemello1 changed the title [moe][perf] Argsort expert ids on the narrowest integer type (8/9) [moe][perf] Argsort expert ids on the narrowest integer type Oct 18, 2026
@felipemello1
felipemello1 removed this pull request from stack #5497 October 18, 2026 21:35
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from a84819b to 941f6ba Compare October 18, 2026 21:35
@felipemello1
felipemello1 changed the base branch from felipemello1/gen-perf/3-train-gather-combine to main October 18, 2026 21:35
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from 941f6ba to 60a963c Compare October 19, 2026 02:16
@felipemello1
felipemello1 changed the base branch from main to felipemello1/moe/7-shared-experts-side-stream October 19, 2026 02:17
@felipemello1
felipemello1 added this pull request to stack #5519 October 19, 2026 02:17
@felipemello1
felipemello1 removed this pull request from stack #5519 October 19, 2026 06:46
@felipemello1
felipemello1 changed the base branch from felipemello1/moe/7-shared-experts-side-stream to main October 19, 2026 06:47
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from 60a963c to dce0860 Compare October 19, 2026 06:47
@felipemello1
felipemello1 changed the base branch from main to felipemello1/lcp/dsv3-3-moe-ep-permute-gathers October 19, 2026 06:48
@felipemello1
felipemello1 added this pull request to stack #5533 October 19, 2026 06:48
@felipemello1 felipemello1 changed the title [moe][perf] Argsort expert ids on the narrowest integer type [moe][perf] Argsort expert ids on the narrowest integer type (2/6) Oct 19, 2026
wwwjn added a commit to wwwjn/torchtitan that referenced this pull request Oct 27, 2026
@felipemello1
felipemello1 removed this pull request from stack #5533 November 7, 2026 06:00
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from dce0860 to 8f72c90 Compare November 7, 2026 06:00
@felipemello1
felipemello1 added this pull request to stack #5932 November 7, 2026 06:00
@felipemello1 felipemello1 changed the title [moe][perf] Argsort expert ids on the narrowest integer type (2/6) [moe][perf] Argsort expert ids on the narrowest integer type (2/4) Nov 7, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 43s —— View job


Approve (fill in the human-written summary before merging) -- review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 32s —— View job


Approve (the human-written summary still needs filling in before merging) -- review

@claude claude Bot 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.

Verdict: Approve -- please address the item below before merging. The new commits fix the test gap from the last review, and nothing new came up. A maintainer still needs to review this because it touches models/common.

What changed since the last review. 8f72c90 removes the GB300 timing from the _argsort_expert_ids docstring. 9e10246 changes the test to run at both sides of each dtype threshold (256, 257, 215, 215 + 1 experts) and sets ids_N[0] = num_experts - 1, so the largest id is always in the input.

Example. If a threshold had an off-by-one, the test now catches it:

threshold <= 257, num_experts=257: id 256 -> uint8 0, sorts first instead of last -> torch.equal fails
threshold <= 2**16, num_experts=2**15+1: id 32768 -> int16 -32768, sorts first -> torch.equal fails

Must fix

  1. The "Summary (human-written)" section of the PR description is still the template placeholder. The author needs to write it (still open from the last review).

Resolved from the last review

  • The test now checks the dtype bounds and forces the largest id into the input (9e10246).

Not verified: the GB300 timings, and that stable sort on uint8/int16 keys doesn't regress on non-CUDA backends.

@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from 9e10246 to ee7e9ad Compare November 7, 2026 20:52
Comment on lines +230 to +233
if num_experts <= 256:
expert_ids_N = expert_ids_N.to(torch.uint8)
elif num_experts <= 2**15:
expert_ids_N = expert_ids_N.to(torch.int16)

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.

can we avoid having to do this on every call and, somehow, define it once, maybe on model definition?

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.

Reply from claude: done in 1a6ebfc. LocalTokenDispatcher.__init__ now picks the dtype once from num_experts and stores it as self.expert_ids_sort_dtype:

if config.num_experts <= 256:
    self.expert_ids_sort_dtype = torch.uint8
elif config.num_experts <= 2**15:
    self.expert_ids_sort_dtype = torch.int16
else:
    self.expert_ids_sort_dtype = torch.int64

_local_reorder only casts: torch.argsort(ids.view(-1).to(self.expert_ids_sort_dtype), stable=True). _argsort_expert_ids is deleted. The test now goes through LocalTokenDispatcher._local_reorder at 256, 257, 215 and 215 + 1 experts, and fails if either threshold is off by one.
The cast itself stays per call: torch.topk always returns int64 ids, and the other users of the ids (indexing, counts) need int64.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 54s —— View job


Approve (the human-written summary still needs filling in before merging) -- review

@claude claude Bot 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.

Verdict: Approve -- please address the item below before merging. 1a6ebfc resolves the maintainer's comment, and the new commit raises nothing new. A maintainer still needs to review because this touches models/common.

What changed since the last review. 1a6ebfc deletes _argsort_expert_ids. LocalTokenDispatcher.__init__ (token_dispatcher.py:98-103) now picks expert_ids_sort_dtype once from num_experts, and _local_reorder (:132) only casts the ids before torch.argsort(stable=True). The test builds a real LocalTokenDispatcher at 256, 257, 215 and 215 + 1 experts and calls _local_reorder directly.

Example. Qwen3.5-35B-A3B, 256 experts:

__init__:       expert_ids_sort_dtype = torch.uint8         (picked once)
_local_reorder: argsort(ids_N.int64.to(uint8), stable=True) -> same order as int64, 1 radix pass

Must fix

  1. The "Summary (human-written)" section of the PR description is still the template placeholder. The author needs to write it. This was raised in both earlier reviews and is still open.

Resolved since the last review

  • @felipemello1's comment ("define it once, maybe on model definition"): the dtype is now chosen in __init__, not on every call (1a6ebfc).
Details
  • Every subclass gets the attribute. AllToAllTokenDispatcher, TorchAOTokenDispatcher, DeepEPTokenDispatcher and HybridEPTokenDispatcher all call super().__init__(config), so every dispatcher sets expert_ids_sort_dtype. Only LocalTokenDispatcher.dispatch (:173), AllToAll._dispatch (:503) and the TorchAO EP=1 path (:753) call _local_reorder. All three pass global ids from the router's topk, so the global num_experts bound is correct.
  • torchtitan/quantization/utils.py:63,69 rebuilds dispatchers from dispatcher.num_experts, so the rebuilt ones pick the dtype again.
  • When the dtype is int64, .to(torch.int64) on int64 ids returns the same tensor (no copy). The attribute is a constant under compile and CUDA graphs.

Not verified: the GB300 timings. I also couldn't run the unit test in this environment (it needs command approval).

@felipemello1
felipemello1 marked this pull request as ready for review November 7, 2026 21:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026
felipemello1 pushed a commit that referenced this pull request Nov 7, 2026
_argsort_expert_ids is gone on #5436. The sort functions here take
expert_ids_sort_dtype (from LocalTokenDispatcher) instead of num_experts,
and cast the ids before torch.argsort(stable=True).
# [0, num_experts): the CUDA radix sort's passes scale with key width, so int64
# ids take 8x the passes of uint8 ids. Same order.
if config.num_experts <= 256:
self.expert_ids_sort_dtype = torch.uint8

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.

maybe make this private field

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.

Reply from claude: done in c35165e. It is now self._expert_ids_sort_dtype.

# Reorder the token indices to match the order of the experts where N = T*K
token_indices_experts_sorted_N = torch.argsort(
topk_expert_ids_TK.view(-1), stable=True
topk_expert_ids_TK.view(-1).to(self.expert_ids_sort_dtype), stable=True

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.

curious: is local_compile (on some region) not able to figure this out automatically?

@felipemello1 felipemello1 Nov 8, 2026 •

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.

Reply from claude: no. Neither Inductor nor ATen narrows the sort keys on its own today (PyTorch main 24459281f):

  1. Inductor hands sorts above 512 elements to ATen's sort (ir.py#L3346-L3353). Our sort has T * top_k rows, e.g. 8192 at 1024 tokens.
  2. ATen's CUDA sort always sorts every bit of the key dtype (SortStable.cu#L145-L147: end_bit = sizeof(scalar_t) * 8). To use fewer bits, it would need the max id on the CPU. That is a device-to-host sync, and CUDA graph capture rejects it.
  3. Inductor's value ranges work inside one kernel (bounds.py#L34-L36), so nothing carries "topk ids < num_experts" into the sort.

The model knows the bound up front, so a cast is the cheap fix. On one GB300, sorting 8192 ids in [0, 256): int64 keys 95.7 us, uint8 22.0 us, and the cast costs 1.8 us.
A sync-free upstream change could narrow the bits inside ATen's one-block sort (up to 4096 keys), but nobody has asked for it and the gain is unmeasured.

felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
Base automatically changed from felipemello1/lcp/dsv3-3-moe-ep-permute-gathers to main November 8, 2026 03:47
Felipe Mello added 6 commits November 7, 2026 22:47
The CUDA radix sort makes one pass per key byte. _argsort_expert_ids casts the
expert ids to uint8 (up to 256 experts) or int16 before the stable argsort, so
_local_reorder sorts in 1-2 passes instead of 8. Same order.
Review fix: the docstring and the PR body gave two numbers for the same row.
Run 256, 257, 2**15 and 2**15 + 1 experts with the largest id present, so an
off-by-one in either threshold wraps that id and fails the test.
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/8-narrow-argsort branch from bc51dae to c4a7d10 Compare November 8, 2026 03:47
@felipemello1
felipemello1 merged commit 9771724 into main Nov 8, 2026
felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
…ce, any EP

Rebased on main after #5162 and #5436 merged. One commit with the PR's changes from:
- 8ad2584 [moe][perf] Gather-sum MoE dispatch and combine, training and inference, any EP
- 2e3549b [moe] Address review: names, docstrings, fewer tests, TorchAO EP=1 TODO
- 742288d [moe] Fold the region-name check into the trainer == generator test
- aaa0090 [moe] Rename _sort_and_gather to _reorder_by_expert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants