Repository navigation
[moe][perf] Argsort expert ids on the narrowest integer type (2/4) - #5436
Conversation
d95ec05 to
a84819b
Compare
a84819b to
941f6ba
Compare
941f6ba to
60a963c
Compare
60a963c to
dce0860
Compare
…#5436) Cherry-picked from felipemello1's open PR: pytorch#5436.
dce0860 to
8f72c90
Compare
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 1m 43s —— View job Approve (fill in the human-written summary before merging) -- review |
|
Claude finished @felipemello1's task in 32s —— View job Approve (the human-written summary still needs filling in before merging) -- review |
There was a problem hiding this comment.
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
- 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.
9e10246 to
ee7e9ad
Compare
| 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) |
There was a problem hiding this comment.
can we avoid having to do this on every call and, somehow, define it once, maybe on model definition?
There was a problem hiding this comment.
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.
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 54s —— View job Approve (the human-written summary still needs filling in before merging) -- review |
There was a problem hiding this comment.
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
- 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,DeepEPTokenDispatcherandHybridEPTokenDispatcherall callsuper().__init__(config), so every dispatcher setsexpert_ids_sort_dtype. OnlyLocalTokenDispatcher.dispatch(:173),AllToAll._dispatch(:503) and the TorchAO EP=1 path (:753) call_local_reorder. All three pass global ids from the router'stopk, so the globalnum_expertsbound is correct. torchtitan/quantization/utils.py:63,69rebuilds dispatchers fromdispatcher.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).
_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 |
There was a problem hiding this comment.
maybe make this private field
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
curious: is local_compile (on some region) not able to figure this out automatically?
There was a problem hiding this comment.
Reply from claude: no. Neither Inductor nor ATen narrows the sort keys on its own today (PyTorch main 24459281f):
- 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.
- 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. - 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.
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.
bc51dae to
c4a7d10
Compare
…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
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)
Problem
T * top_kroutes by expert:torch.argsort(expert_ids, stable=True)in_local_reorder(EP=1, and EP>1 before the all-to-all; training and inference).Solution
LocalTokenDispatcher.__init__picks the sort dtype once fromnum_experts: uint8 (<= 256 experts), int16 (<= 32,768) or int64, stored asexpert_ids_sort_dtype._local_reordercasts the ids to it beforetorch.argsort(stable=True). Every dispatcher inherits it, and the dtype is the same in training and inference.Results
NOTE:
[0, num_experts), as the grouped GEMM already requires.Test plan
test_narrow_key_argsort_matches_int64_argsort: uint8, int16 and int64 keys give the same stable order.