Repository navigation
Expert-parallel dispatch hands the experts the received rows, not the all-to-all's pending result - #49421
Conversation
… all-to-all's pending result The token dispatch's all-to-all is a functional collective: its result is an `AsyncCollectiveTensor`, whose own pointer is null until a torch op waits on it. Experts that go through the torch dispatcher first (aten ops, `torch.library` custom ops, a compiled graph) wait implicitly, but a kernel launched straight from Python reads the null pointer and faults with an illegal memory access (Triton-launched expert kernels in eager). The dispatch now waits on the received rows itself, once, before any experts implementation sees them; the expert-id work is already queued by then, so no overlap is lost. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ed tests do Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
Torch experts (aten ops, and custom ops called through the dispatcher) wait on the all-to-all's pending result themselves, at the entry of the first op that reads it, so their routing work before it still overlaps the exchange. Only the quantized experts flagged `_hf_quantized_needs_local_tp` read raw pointers and need the rows waited, which `_maybe_wait_tensor` does right before the experts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The integrations set `_hf_quantized_needs_local_tp` on the module instance after building it; the test does the same instead of taking it as a constructor argument. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The dummy experts assert their input themselves: the pending `AsyncCollectiveTensor` for torch experts, the received rows for quantized ones. The worker block moves to the end of the file. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
| # the received rows' pointer is null until a torch op waits on them; quantized experts read raw pointers | ||
| if getattr(module, "_hf_quantized_needs_local_tp", False): |
There was a problem hiding this comment.
nope this is a very bad precedent. The code here should never depend on quantization or not. let's find a better solution!
There was a problem hiding this comment.
we could wait_tensor by default as apparently the torch internal dispatcher does it by default bt to be sure, we should launch some benchmarks to verify
There was a problem hiding this comment.
Tried to bench everything possible, on 2 and 4 ranks, it seems that waiting by default costs about 1% at most, for inference and training, and makes eager and batched_mm experts faster. So the condition can go:
tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens(...)
# hand the experts the received rows, not the all-to-all's pending result
tokens = wait_tensor(tokens)What changes
all_to_all_single returns an AsyncCollectiveTensor, which wraps the pending output. Its __torch_dispatch__
waits on the collective at the first op that reads it. The all-to-all runs on the NCCL stream, and the wait makes
the compute stream depend on it. Waiting explicitly changes two things:
- When that dependency is inserted: right after the dispatch, instead of at the experts' first read of the
rows. Compute kernels the experts enqueue before that read can no longer overlap the all-to-all. - What the experts receive: a plain tensor. Without the wait, the variable stays an
AsyncCollectiveTensor,
so every op on it goes through the Python__torch_dispatch__again. Only the first one actually waits; the
later ones still pay the Python round-trip. View ops also re-wrap their output, so the wrapper spreads to views of the rows.
Benchmarks
Setup:
- Qwen3-MoE with random weights: 8 layers, 128 experts, top-8, hidden 2048, bf16.
- A100 80GB over NVLink/NCCL,
DistributedConfig(tp_size=N, ep_size=N)with N = 2 and N = 4. - Each figure is the median of 100 runs, with both variants interleaved in the same process.
- "A/A" times the same variant twice, to show the noise level.
Inference (forward, no cache), 2 ranks
| Experts impl | Input | Wait at first read | Explicit wait | Δ | A/A noise |
|---|---|---|---|---|---|
grouped_mm (default) |
4×1024 | 61.26 ms | 62.14 ms | +1.4% | +0.1% |
grouped_mm |
1×128 | 41.70 ms | 41.86 ms | +0.4% | +1.1% |
grouped_mm |
32×1 | 46.66 ms | 46.77 ms | +0.2% | 0.0% |
batched_mm |
1×128 | 72.91 ms | 71.60 ms | −1.8% | +0.1% |
batched_mm |
32×1 | 34.15 ms | 32.88 ms | −3.7% | −0.7% |
eager |
1×128 | 115.71 ms | 95.61 ms | −17.4% | −0.4% |
eager |
32×1 | 233.49 ms | 186.54 ms | −20.1% | −0.5% |
Training (forward + backward), 2 ranks
| Experts impl | Input | Wait at first read | Explicit wait | Δ | A/A noise |
|---|---|---|---|---|---|
grouped_mm |
4×1024 | 187.54 ms | 188.26 ms | +0.4% | −0.1% |
grouped_mm |
2×512 | 149.45 ms | 150.02 ms | +0.4% | +0.4% |
grouped_mm |
1×128 | 138.95 ms | 139.11 ms | +0.1% | −0.1% |
eager |
1×128 | 416.57 ms | 397.35 ms | −4.6% | +0.1% |
Inference (forward, no cache), 4 ranks
| Experts impl | Input | Wait at first read | Explicit wait | Δ | A/A noise |
|---|---|---|---|---|---|
grouped_mm (default) |
4×1024 | 45.75 ms | 45.86 ms | +0.2% | −0.2% |
grouped_mm |
1×128 | 38.31 ms | 38.16 ms | −0.4% | −0.2% |
grouped_mm |
32×1 | 41.48 ms | 41.35 ms | −0.3% | −0.1% |
batched_mm |
1×128 | 52.30 ms | 50.92 ms | −2.6% | −0.1% |
batched_mm |
32×1 | 34.65 ms | 33.52 ms | −3.3% | +0.7% |
eager |
1×128 | 78.37 ms | 67.01 ms | −14.5% | 0.0% |
eager |
32×1 | 137.85 ms | 114.07 ms | −17.3% | −0.3% |
Training (forward + backward), 4 ranks
| Experts impl | Input | Wait at first read | Explicit wait | Δ | A/A noise |
|---|---|---|---|---|---|
grouped_mm |
4×1024 | 153.34 ms | 153.81 ms | +0.3% | 0.0% |
grouped_mm |
2×512 | 136.13 ms | 136.11 ms | 0.0% | 0.0% |
grouped_mm |
1×128 | 129.46 ms | 129.70 ms | +0.2% | −0.2% |
eager |
1×128 | 202.08 ms | 191.13 ms | −5.4% | +0.2% |
batched_mm is missing from the 4×1024 inference rows and from training because it runs out of memory there even
without this change (it gathers a weight copy per token).
wait_tensor has a generated backward that passes the gradient through unchanged. With the wait forced on for all
experts, the EP tests pass (test_ep_forward and test_ep_backward for eager, grouped_mm and batched_mm on
qwen3_moe and olmoe), and a 2-rank check gives identical gradients through the all-to-all with and without the wait.
Where the differences come from
grouped_mm large prefill (+1.4% on 2 ranks, noise on 4): lost overlap
In a GPU trace of 3 forwards at 4×1024 on 2 ranks, the compute kernels running alongside the all-to-all kernels add
up to:
- 3.83 ms without the explicit wait, mostly
DeviceRadixSort*, i.e.grouped_mm's sort of the expert ids; - 0.97 ms with the explicit wait: only the
repeat_interleave/scatterin_dispatch_tokens, which come before
either wait.
That's about 1 ms per forward, matching the +0.88 ms measured. In training the backward dominates, so this shrinks
to noise.
On 4 ranks the cost disappears even in inference. Each rank dispatches a quarter of the tokens instead of half, so
the median all-to-all kernel takes 332 µs instead of 674 µs, and it finishes before the host has enqueued the sort.
Even without the explicit wait, the sort overlaps the all-to-all for only 0.013 ms (vs 2 ms on 2 ranks), so there's
nothing to lose. The overlap only matters when the all-to-all outlasts the host's launch latency, which may be the
case on a slower multi-node interconnect; I couldn't measure that here. grouped_mm reads the rows once per layer, so its wrapper-call count is the same either way (24 per
forward).
eager (−17% to −20% inference, −4.6% training): wrapper dispatch on every expert
Profile of eager inference, 32×1, 5 forwards, rank 0:
| Wait at first read | Explicit wait | |
|---|---|---|
PythonSubclass (wrapper dispatch) calls |
2310 | 120 |
PythonSubclass self CPU |
189 ms (~82 µs/call) | 11 ms |
aten::index calls |
6610 | 4420 |
| Total self CPU | 1.495 s | 1.239 s |
- Eager reads the rows once per hit expert (
hidden_states[token_idx]), about 438 times per forward. Each read
goes through the wrapper's Python dispatch and then re-dispatchesaten::indexon the inner tensor, hence the
2190 extraaten::indexcalls. - That's about 51 ms of extra CPU per forward, matching the wall-clock gap. Eager MoE syncs the host thousands of times (
.item()/nonzero), so host overhead shows up 1:1 in latency.
batched_mm (−2% to −4% inference): wrapper spreading through views
batched_mm reads the rows only once per layer, with hidden_states.repeat_interleave(num_top_k, dim=0). But
repeat_interleave decomposes into unsqueeze, then expand, then clone. The two view ops re-wrap their
output, so all three go through the wrapper's Python dispatch: 3 calls per layer instead of 1.
Profile of batched_mm inference, 32×1, 5 forwards, rank 0:
| Wait at first read | Explicit wait | |
|---|---|---|
PythonSubclass calls |
200 | 120 |
aten::repeat_interleave CPU per call |
175 µs | 68 µs |
| Total self CPU | 197.4 ms | 177.9 ms |
aten::bmm CUDA time |
31.1 ms | 32.5 ms |
The gain is purely on the host side; the GPU work is the same.
Conclusion
Waiting by default:
- removes the dependency on quantization: every experts implementation gets a plain tensor with a valid pointer;
- costs about 1% on large
grouped_mmprefill on 2 ranks, nothing measurable on 4 ranks, and nothing measurable in training; - makes
eager15–20% faster in inference and about 5% faster in training, andbatched_mm2–4% faster in inference, on both 2 and 4 ranks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
vasqu
left a comment
There was a problem hiding this comment.
As discussed internally it's super needed and the numbers show that its overall a win on pretty much everything
| if is_torch_distributed_available(): | ||
| import torch.distributed as dist | ||
| from torch.distributed._functional_collectives import all_to_all_single | ||
| from torch.distributed._functional_collectives import all_to_all_single, wait_tensor |
| hidden_states, top_k_index, module.num_experts, ep_group, ep_size | ||
| ) | ||
| # hand the experts the received rows, not the all-to-all's pending result (whose pointer is null until | ||
| # waited on): https://github.com/huggingface/transformers/pull/49421#discussion_r4249715216 |
There was a problem hiding this comment.
Imo we can just link the base pr
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CI recapDashboard: View test results in Grafana |
The token dispatch's all-to-all is a functional collective: its result is an
AsyncCollectiveTensor, whose own pointer is null until a torch op waits on it. Experts that go through the torch dispatcher (aten ops,torch.librarycustom ops, a compiled graph) wait implicitly, but a kernel launched straight from Python reads the null pointer and faults with an illegal memory access (Triton-launched expert kernels in eager). The dispatch now always waits on the received rows (wait_tensor), once, before any experts implementation sees them, so every implementation gets a plain tensor and the code no longer depends on quantization.Waiting by default is free or faster (full benchmarks and profiles; Qwen3-MoE shape, 8 layers, A100 over NVLink,
tp_size=ep_size2 and 4, median of 100 interleaved runs):grouped_mm(default)batched_mmeagerThe
eagerandbatched_mmgains are host-side: without the wait, every op on the rows (and on views of them) goes through the wrapper's Python__torch_dispatch__.wait_tensorpasses gradients through unchanged, and the EP forward/backward tests pass with it for eager,grouped_mmandbatched_mm.What does this PR do?
Fixes # (issue)
Code Agent Policy
The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by
code agents. These often are low-quality, or fix extremely minor issues that occur rarely or never in practice.
As a result, we're instituting a rule that first-time contributors should not use code agents to submit PRs or issues.
We'd also ask autonomous "OpenClaw"-like agents not to open any PRs or issues.
Issues/PRs from first-time contributors that violate this rule will probably just be closed without review, and we
might block you, especially if you open more than one or appear to be deliberately ignoring this. We especially do not
want new contributors to jump in on random issues to contribute an agent-written fix. This creates lots of noise
for reviewers and other users and will almost certainly get you blocked.
For more information, please read
CONTRIBUTING.md.Before submitting
Pull Request checks?
to it if that's the case.
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.