From 11de8b96443573aea969fbec37dd1f241fc70a2f Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Wed, 7 Oct 2026 09:29:58 -0700 Subject: [PATCH 01/12] Expert-parallel dispatch hands the experts the received rows, not the 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) --- .../distributed/tensor_parallel.py | 6 +- tests/utils/test_distributed_ep_dispatch.py | 74 +++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 tests/utils/test_distributed_ep_dispatch.py diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index 00b44df39b63..11605dcd8bc9 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -38,7 +38,7 @@ 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 from torch.distributed.tensor import DTensor, Partial, Replicate, Shard, distribute_tensor from torch.distributed.tensor.placement_types import _StridedShard @@ -804,7 +804,9 @@ def _dispatch_tokens( recv_counts = torch.empty_like(send_counts) torch.distributed.all_to_all_single(recv_counts, send_counts, group=ep_group) send_sizes, recv_sizes = torch.stack([send_counts.sum(dim=1), recv_counts.sum(dim=1)]).tolist() - recv_tokens = all_to_all_single(send_tokens, recv_sizes, send_sizes, ep_group) + # the experts get the received rows, not the all-to-all's pending result: its pointer is null until a torch op + # waits on it, which a kernel launched straight from Python (Triton, a raw pointer) never does + recv_tokens = wait_tensor(all_to_all_single(send_tokens, recv_sizes, send_sizes, ep_group)) recv_expert_ids = torch.arange(num_local_experts, device=hidden_states.device).repeat(ep_size) recv_expert_ids = recv_expert_ids.repeat_interleave(recv_counts.reshape(-1), output_size=sum(recv_sizes)) return recv_tokens, recv_expert_ids, order, send_sizes, recv_sizes diff --git a/tests/utils/test_distributed_ep_dispatch.py b/tests/utils/test_distributed_ep_dispatch.py new file mode 100644 index 000000000000..5825e3e60133 --- /dev/null +++ b/tests/utils/test_distributed_ep_dispatch.py @@ -0,0 +1,74 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import unittest + +from transformers.testing_utils import get_torch_dist_unique_port, require_torch +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + import torch.distributed as dist + import torch.multiprocessing as mp + from torch.distributed.device_mesh import init_device_mesh + + from transformers.distributed.tensor_parallel import EpDispatchExpertsParallel + + class _RecordingExperts(torch.nn.Module): + """Stand-in experts: the identity, recording the type of the rows it is handed.""" + + def __init__(self, num_experts): + super().__init__() + self.num_experts = num_experts + self.received = None + + def forward(self, hidden_states, top_k_index, top_k_weights): + self.received = type(hidden_states) + return hidden_states.clone() + + +def _dispatch_hands_the_experts_the_received_rows(rank, world_size, port): + os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port)) + dist.init_process_group("gloo", rank=rank, world_size=world_size) + try: + ep_mesh = init_device_mesh("cpu", (world_size,)) + hidden_states = torch.arange(4 * 8, dtype=torch.float32).view(4, 8) + 100 * rank + top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) + top_k_weights = torch.full((4, 2), 0.5) + experts = _RecordingExperts(num_experts=2) + EpDispatchExpertsParallel().install_forward(experts, ep_mesh) + output = experts(hidden_states, top_k_index, top_k_weights) + assert experts.received is torch.Tensor, experts.received + torch.testing.assert_close(output, hidden_states) + finally: + dist.destroy_process_group() + + +@require_torch +class EpDispatchTest(unittest.TestCase): + def test_dispatch_hands_the_experts_the_received_rows(self): + """The experts get the all-to-all's received rows as a plain tensor. Its pending result + (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on it, which a kernel launched straight + from Python (Triton, a raw pointer) never does.""" + world_size = 2 + mp.spawn( + _dispatch_hands_the_experts_the_received_rows, + args=(world_size, get_torch_dist_unique_port()), + nprocs=world_size, + ) + + +if __name__ == "__main__": + unittest.main() From de98a5225b540d61f8d11972628831f843bd24f4 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 03:36:32 -0700 Subject: [PATCH 02/12] Move the dispatch test into the tensor-parallel layer tests Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/tensor_parallel/test_tensor_parallel.py | 41 +++++++++- tests/utils/test_distributed_ep_dispatch.py | 74 ------------------- 2 files changed, 40 insertions(+), 75 deletions(-) delete mode 100644 tests/utils/test_distributed_ep_dispatch.py diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index c83741361fd5..63ea3c7cfbec 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -11,10 +11,14 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import os import warnings from unittest.mock import patch import torch +import torch.distributed as dist +import torch.multiprocessing as mp +from torch.distributed.device_mesh import init_device_mesh from transformers import AutoModelForCausalLM from transformers.distributed import tensor_parallel @@ -22,11 +26,40 @@ from transformers.distributed.tensor_parallel import ( ALL_PARALLEL_STYLES, ColwiseParallel, + EpDispatchExpertsParallel, PackedColwiseParallel, PackedRowwiseParallel, RowwiseParallel, ) -from transformers.testing_utils import TestCasePlus, is_tensor_parallel_test +from transformers.testing_utils import TestCasePlus, get_torch_dist_unique_port, is_tensor_parallel_test + + +class _RecordingExperts(torch.nn.Module): + """Stand-in experts: the identity, recording the type of the rows it is handed.""" + + def __init__(self, num_experts): + super().__init__() + self.num_experts = num_experts + self.received = None + + def forward(self, hidden_states, top_k_index, top_k_weights): + self.received = type(hidden_states) + return hidden_states.clone() + + +def _dispatch_hands_the_experts_the_received_rows(rank, world_size, port): + os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port)) + dist.init_process_group("gloo", rank=rank, world_size=world_size) + try: + experts = _RecordingExperts(num_experts=2) + EpDispatchExpertsParallel().install_forward(experts, init_device_mesh("cpu", (world_size,))) + hidden_states = torch.arange(4 * 8, dtype=torch.float32).view(4, 8) + 100 * rank + top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) + output = experts(hidden_states, top_k_index, torch.full((4, 2), 0.5)) + assert experts.received is torch.Tensor, experts.received + torch.testing.assert_close(output, hidden_states) + finally: + dist.destroy_process_group() @is_tensor_parallel_test @@ -167,6 +200,12 @@ def test_post_init_keeps_class_level_plans(self): @is_tensor_parallel_test class TestTensorParallelLayer(TestCasePlus): + def test_dispatch_hands_the_experts_the_received_rows(self): + """The experts get the all-to-all's received rows as a plain tensor. Its pending result + (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on it, which a kernel launched straight + from Python (Triton, a raw pointer) never does.""" + mp.spawn(_dispatch_hands_the_experts_the_received_rows, args=(2, get_torch_dist_unique_port()), nprocs=2) + class MockDeviceMesh: def __init__(self, world_size, rank): self.world_size = world_size diff --git a/tests/utils/test_distributed_ep_dispatch.py b/tests/utils/test_distributed_ep_dispatch.py deleted file mode 100644 index 5825e3e60133..000000000000 --- a/tests/utils/test_distributed_ep_dispatch.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright 2026 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -import unittest - -from transformers.testing_utils import get_torch_dist_unique_port, require_torch -from transformers.utils import is_torch_available - - -if is_torch_available(): - import torch - import torch.distributed as dist - import torch.multiprocessing as mp - from torch.distributed.device_mesh import init_device_mesh - - from transformers.distributed.tensor_parallel import EpDispatchExpertsParallel - - class _RecordingExperts(torch.nn.Module): - """Stand-in experts: the identity, recording the type of the rows it is handed.""" - - def __init__(self, num_experts): - super().__init__() - self.num_experts = num_experts - self.received = None - - def forward(self, hidden_states, top_k_index, top_k_weights): - self.received = type(hidden_states) - return hidden_states.clone() - - -def _dispatch_hands_the_experts_the_received_rows(rank, world_size, port): - os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port)) - dist.init_process_group("gloo", rank=rank, world_size=world_size) - try: - ep_mesh = init_device_mesh("cpu", (world_size,)) - hidden_states = torch.arange(4 * 8, dtype=torch.float32).view(4, 8) + 100 * rank - top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) - top_k_weights = torch.full((4, 2), 0.5) - experts = _RecordingExperts(num_experts=2) - EpDispatchExpertsParallel().install_forward(experts, ep_mesh) - output = experts(hidden_states, top_k_index, top_k_weights) - assert experts.received is torch.Tensor, experts.received - torch.testing.assert_close(output, hidden_states) - finally: - dist.destroy_process_group() - - -@require_torch -class EpDispatchTest(unittest.TestCase): - def test_dispatch_hands_the_experts_the_received_rows(self): - """The experts get the all-to-all's received rows as a plain tensor. Its pending result - (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on it, which a kernel launched straight - from Python (Triton, a raw pointer) never does.""" - world_size = 2 - mp.spawn( - _dispatch_hands_the_experts_the_received_rows, - args=(world_size, get_torch_dist_unique_port()), - nprocs=world_size, - ) - - -if __name__ == "__main__": - unittest.main() From d009c920628ab7e49f19d83da471ef98e60d66c9 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 03:39:16 -0700 Subject: [PATCH 03/12] Test the dispatch wait in one process, patching the collectives Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/tensor_parallel/test_tensor_parallel.py | 48 +++++-------------- 1 file changed, 11 insertions(+), 37 deletions(-) diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index 63ea3c7cfbec..cb1b00a8d125 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -11,14 +11,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import os import warnings from unittest.mock import patch import torch -import torch.distributed as dist -import torch.multiprocessing as mp -from torch.distributed.device_mesh import init_device_mesh +from torch.distributed._functional_collectives import AsyncCollectiveTensor from transformers import AutoModelForCausalLM from transformers.distributed import tensor_parallel @@ -31,35 +28,7 @@ PackedRowwiseParallel, RowwiseParallel, ) -from transformers.testing_utils import TestCasePlus, get_torch_dist_unique_port, is_tensor_parallel_test - - -class _RecordingExperts(torch.nn.Module): - """Stand-in experts: the identity, recording the type of the rows it is handed.""" - - def __init__(self, num_experts): - super().__init__() - self.num_experts = num_experts - self.received = None - - def forward(self, hidden_states, top_k_index, top_k_weights): - self.received = type(hidden_states) - return hidden_states.clone() - - -def _dispatch_hands_the_experts_the_received_rows(rank, world_size, port): - os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port)) - dist.init_process_group("gloo", rank=rank, world_size=world_size) - try: - experts = _RecordingExperts(num_experts=2) - EpDispatchExpertsParallel().install_forward(experts, init_device_mesh("cpu", (world_size,))) - hidden_states = torch.arange(4 * 8, dtype=torch.float32).view(4, 8) + 100 * rank - top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) - output = experts(hidden_states, top_k_index, torch.full((4, 2), 0.5)) - assert experts.received is torch.Tensor, experts.received - torch.testing.assert_close(output, hidden_states) - finally: - dist.destroy_process_group() +from transformers.testing_utils import TestCasePlus, is_tensor_parallel_test @is_tensor_parallel_test @@ -201,10 +170,15 @@ def test_post_init_keeps_class_level_plans(self): @is_tensor_parallel_test class TestTensorParallelLayer(TestCasePlus): def test_dispatch_hands_the_experts_the_received_rows(self): - """The experts get the all-to-all's received rows as a plain tensor. Its pending result - (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on it, which a kernel launched straight - from Python (Triton, a raw pointer) never does.""" - mp.spawn(_dispatch_hands_the_experts_the_received_rows, args=(2, get_torch_dist_unique_port()), nprocs=2) + """The all-to-all's pending result (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on + it, which a kernel launched straight from Python never does: the experts get the received rows.""" + hidden_states, top_k_index = torch.randn(4, 8), torch.tensor([[0, 1], [1, 0], [0, 1], [1, 0]]) + with ( + patch.object(tensor_parallel, "all_to_all_single", lambda tokens, *args: AsyncCollectiveTensor(tokens)), + patch.object(torch.distributed, "all_to_all_single", lambda out, inp, group=None: out.copy_(inp)), + ): + tokens, *_ = EpDispatchExpertsParallel()._dispatch_tokens(hidden_states, top_k_index, 2, None, 1) + self.assertIs(type(tokens), torch.Tensor) class MockDeviceMesh: def __init__(self, world_size, rank): From e129eeb76797200aaff0b847ca5315fd6edeff2a Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 03:43:37 -0700 Subject: [PATCH 04/12] Run the dispatch test on two real ranks, at the end of the layer tests Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/tensor_parallel/test_tensor_parallel.py | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index cb1b00a8d125..e9b7c5061ff9 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -15,8 +15,9 @@ from unittest.mock import patch import torch -from torch.distributed._functional_collectives import AsyncCollectiveTensor +import torch.distributed as dist +from tests.test_tensor_parallel_mixin import _init_distributed from transformers import AutoModelForCausalLM from transformers.distributed import tensor_parallel from transformers.distributed.sharding_utils import DtensorShardOperation @@ -31,6 +32,13 @@ from transformers.testing_utils import TestCasePlus, is_tensor_parallel_test +def _dispatch_hands_the_experts_the_received_rows(rank): + hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank + top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) + tokens, *_ = EpDispatchExpertsParallel()._dispatch_tokens(hidden_states, top_k_index, 2, dist.group.WORLD, 2) + assert type(tokens) is torch.Tensor, type(tokens) + + @is_tensor_parallel_test class TestTensorParallelProperties(TestCasePlus): def test_tp_plan_property_setter_getter(self): @@ -169,17 +177,6 @@ def test_post_init_keeps_class_level_plans(self): @is_tensor_parallel_test class TestTensorParallelLayer(TestCasePlus): - def test_dispatch_hands_the_experts_the_received_rows(self): - """The all-to-all's pending result (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on - it, which a kernel launched straight from Python never does: the experts get the received rows.""" - hidden_states, top_k_index = torch.randn(4, 8), torch.tensor([[0, 1], [1, 0], [0, 1], [1, 0]]) - with ( - patch.object(tensor_parallel, "all_to_all_single", lambda tokens, *args: AsyncCollectiveTensor(tokens)), - patch.object(torch.distributed, "all_to_all_single", lambda out, inp, group=None: out.copy_(inp)), - ): - tokens, *_ = EpDispatchExpertsParallel()._dispatch_tokens(hidden_states, top_k_index, 2, None, 1) - self.assertIs(type(tokens), torch.Tensor) - class MockDeviceMesh: def __init__(self, world_size, rank): self.world_size = world_size @@ -378,3 +375,8 @@ def test_sharding_does_not_create_unrelated_module_attributes(self): self.assertEqual(module.random_attr, 123) self.assertFalse(hasattr(module, "num_experts")) + + def test_dispatch_hands_the_experts_the_received_rows(self): + """The all-to-all's pending result (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on + it, which a kernel launched straight from Python never does: the experts get the received rows.""" + _init_distributed(tp=2, backend="gloo")(_dispatch_hands_the_experts_the_received_rows)() From 133876bb31276cd67e2d6bd31e8c259052a36687 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 03:48:38 -0700 Subject: [PATCH 05/12] Import the distributed test helper relatively, as the other distributed tests do Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/tensor_parallel/__init__.py | 0 tests/tensor_parallel/test_tensor_parallel.py | 4 +++- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 tests/tensor_parallel/__init__.py diff --git a/tests/tensor_parallel/__init__.py b/tests/tensor_parallel/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index e9b7c5061ff9..569bd192eb43 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -17,7 +17,6 @@ import torch import torch.distributed as dist -from tests.test_tensor_parallel_mixin import _init_distributed from transformers import AutoModelForCausalLM from transformers.distributed import tensor_parallel from transformers.distributed.sharding_utils import DtensorShardOperation @@ -31,7 +30,10 @@ ) from transformers.testing_utils import TestCasePlus, is_tensor_parallel_test +from ..test_tensor_parallel_mixin import _init_distributed + +# Worker functions for the expert-parallel layer tests, spawned through `_init_distributed`. def _dispatch_hands_the_experts_the_received_rows(rank): hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) From 97265f85a4dbc61f1dc0d51a7769b70d84a4d8ff Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 05:38:59 -0700 Subject: [PATCH 06/12] Wait on the dispatched rows only for quantized experts 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) --- .../distributed/tensor_parallel.py | 13 +++++-- tests/tensor_parallel/test_tensor_parallel.py | 35 +++++++++++++++---- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index 11605dcd8bc9..6a210695a4d8 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -100,6 +100,14 @@ def _get_parameter_plan(parameter_name: str, plan: dict[str, str], is_weight=Tru return None +def _maybe_wait_tensor(module, tensor): + # A collective's pending result (`AsyncCollectiveTensor`) has a null pointer until a torch op waits on it. Torch + # experts wait at that op's entry; quantized experts read raw pointers, so they get the result waited. + if getattr(module, "_hf_quantized_needs_local_tp", False): + return wait_tensor(tensor) + return tensor + + @contextlib.contextmanager def _use_local_dtensor_params(module): # Kernels as DeepGEMM require local tensors rather than DTensors. @@ -804,9 +812,7 @@ def _dispatch_tokens( recv_counts = torch.empty_like(send_counts) torch.distributed.all_to_all_single(recv_counts, send_counts, group=ep_group) send_sizes, recv_sizes = torch.stack([send_counts.sum(dim=1), recv_counts.sum(dim=1)]).tolist() - # the experts get the received rows, not the all-to-all's pending result: its pointer is null until a torch op - # waits on it, which a kernel launched straight from Python (Triton, a raw pointer) never does - recv_tokens = wait_tensor(all_to_all_single(send_tokens, recv_sizes, send_sizes, ep_group)) + recv_tokens = all_to_all_single(send_tokens, recv_sizes, send_sizes, ep_group) recv_expert_ids = torch.arange(num_local_experts, device=hidden_states.device).repeat(ep_size) recv_expert_ids = recv_expert_ids.repeat_interleave(recv_counts.reshape(-1), output_size=sum(recv_sizes)) return recv_tokens, recv_expert_ids, order, send_sizes, recv_sizes @@ -893,6 +899,7 @@ def ep_forward(hidden_states, top_k_index, top_k_weights): tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens( hidden_states, top_k_index, module.num_experts, ep_group, ep_size ) + tokens = _maybe_wait_tensor(module, tokens) expert_output = self._run_local_experts(experts_forward, tokens, expert_ids) output = self._combine_tokens( expert_output, top_k_weights, order, send_sizes, recv_sizes, ep_group diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index 569bd192eb43..13843fa15ad2 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -15,7 +15,7 @@ from unittest.mock import patch import torch -import torch.distributed as dist +from torch.distributed.device_mesh import init_device_mesh from transformers import AutoModelForCausalLM from transformers.distributed import tensor_parallel @@ -34,11 +34,31 @@ # Worker functions for the expert-parallel layer tests, spawned through `_init_distributed`. -def _dispatch_hands_the_experts_the_received_rows(rank): +class _RecordingExperts(torch.nn.Module): + """Experts that record the type of the rows they receive and return them weighted.""" + + def __init__(self, quantized): + super().__init__() + self.num_experts = 2 + if quantized: + self._hf_quantized_needs_local_tp = True + + def forward(self, tokens, expert_ids, weights): + self.received_type = type(tokens) + return tokens * weights + + +def _dispatch_waits_only_for_quantized_experts(rank): + mesh = init_device_mesh("cpu", (2,)) hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) - tokens, *_ = EpDispatchExpertsParallel()._dispatch_tokens(hidden_states, top_k_index, 2, dist.group.WORLD, 2) - assert type(tokens) is torch.Tensor, type(tokens) + top_k_weights = torch.ones(4, 2) + # torch experts wait at their first op's entry; quantized experts read raw pointers + for quantized in (False, True): + experts = _RecordingExperts(quantized) + EpDispatchExpertsParallel().install_forward(experts, mesh) + experts(hidden_states, top_k_index, top_k_weights) + assert (experts.received_type is torch.Tensor) == quantized, quantized @is_tensor_parallel_test @@ -378,7 +398,8 @@ def test_sharding_does_not_create_unrelated_module_attributes(self): self.assertEqual(module.random_attr, 123) self.assertFalse(hasattr(module, "num_experts")) - def test_dispatch_hands_the_experts_the_received_rows(self): + def test_dispatch_waits_only_for_quantized_experts(self): """The all-to-all's pending result (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on - it, which a kernel launched straight from Python never does: the experts get the received rows.""" - _init_distributed(tp=2, backend="gloo")(_dispatch_hands_the_experts_the_received_rows)() + it. Torch experts get it as is and wait at that op's entry; quantized experts read raw pointers and get the + received rows.""" + _init_distributed(tp=2, backend="gloo")(_dispatch_waits_only_for_quantized_experts)() From 09f60bf4ea814090e7f936daf7b6f3024d44d1e7 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 05:40:38 -0700 Subject: [PATCH 07/12] Flag the test experts the way the quantization integrations do 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) --- tests/tensor_parallel/test_tensor_parallel.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index 13843fa15ad2..97a136122779 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -37,11 +37,9 @@ class _RecordingExperts(torch.nn.Module): """Experts that record the type of the rows they receive and return them weighted.""" - def __init__(self, quantized): + def __init__(self): super().__init__() self.num_experts = 2 - if quantized: - self._hf_quantized_needs_local_tp = True def forward(self, tokens, expert_ids, weights): self.received_type = type(tokens) @@ -55,7 +53,9 @@ def _dispatch_waits_only_for_quantized_experts(rank): top_k_weights = torch.ones(4, 2) # torch experts wait at their first op's entry; quantized experts read raw pointers for quantized in (False, True): - experts = _RecordingExperts(quantized) + experts = _RecordingExperts() + if quantized: + experts._hf_quantized_needs_local_tp = True EpDispatchExpertsParallel().install_forward(experts, mesh) experts(hidden_states, top_k_index, top_k_weights) assert (experts.received_type is torch.Tensor) == quantized, quantized From 29144e34a2a59530ccc15d4e5cdc43e8fb0aa116 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 05:54:07 -0700 Subject: [PATCH 08/12] Check both sides of the dispatch wait in the dummy experts 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) --- tests/tensor_parallel/test_tensor_parallel.py | 53 +++++++++---------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index 97a136122779..ace335dcb617 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -15,6 +15,7 @@ from unittest.mock import patch import torch +from torch.distributed._functional_collectives import AsyncCollectiveTensor from torch.distributed.device_mesh import init_device_mesh from transformers import AutoModelForCausalLM @@ -33,34 +34,6 @@ from ..test_tensor_parallel_mixin import _init_distributed -# Worker functions for the expert-parallel layer tests, spawned through `_init_distributed`. -class _RecordingExperts(torch.nn.Module): - """Experts that record the type of the rows they receive and return them weighted.""" - - def __init__(self): - super().__init__() - self.num_experts = 2 - - def forward(self, tokens, expert_ids, weights): - self.received_type = type(tokens) - return tokens * weights - - -def _dispatch_waits_only_for_quantized_experts(rank): - mesh = init_device_mesh("cpu", (2,)) - hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank - top_k_index = torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]) - top_k_weights = torch.ones(4, 2) - # torch experts wait at their first op's entry; quantized experts read raw pointers - for quantized in (False, True): - experts = _RecordingExperts() - if quantized: - experts._hf_quantized_needs_local_tp = True - EpDispatchExpertsParallel().install_forward(experts, mesh) - experts(hidden_states, top_k_index, top_k_weights) - assert (experts.received_type is torch.Tensor) == quantized, quantized - - @is_tensor_parallel_test class TestTensorParallelProperties(TestCasePlus): def test_tp_plan_property_setter_getter(self): @@ -403,3 +376,27 @@ def test_dispatch_waits_only_for_quantized_experts(self): it. Torch experts get it as is and wait at that op's entry; quantized experts read raw pointers and get the received rows.""" _init_distributed(tp=2, backend="gloo")(_dispatch_waits_only_for_quantized_experts)() + + +class _DummyExperts(torch.nn.Module): + def __init__(self): + super().__init__() + self.num_experts = 2 + + def forward(self, tokens, expert_ids, weights): + if getattr(self, "_hf_quantized_needs_local_tp", False): + assert type(tokens) is torch.Tensor + else: + assert type(tokens) is AsyncCollectiveTensor + return tokens + + +# Worker functions for the expert-parallel layer tests, spawned through `_init_distributed`. +def _dispatch_waits_only_for_quantized_experts(rank): + hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank + for quantized in (False, True): + experts = _DummyExperts() + if quantized: + experts._hf_quantized_needs_local_tp = True + EpDispatchExpertsParallel().install_forward(experts, init_device_mesh("cpu", (2,))) + experts(hidden_states, torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]), torch.ones(4, 2)) From cd8eaf93d65d51576f3c200eb0ff765b211a01fc Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Thu, 8 Oct 2026 05:55:39 -0700 Subject: [PATCH 09/12] Inline the quantized-experts wait in the dispatch forward Co-Authored-By: Claude Opus 5.5 (1M context) --- src/transformers/distributed/tensor_parallel.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index 6a210695a4d8..2399374f3236 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -100,14 +100,6 @@ def _get_parameter_plan(parameter_name: str, plan: dict[str, str], is_weight=Tru return None -def _maybe_wait_tensor(module, tensor): - # A collective's pending result (`AsyncCollectiveTensor`) has a null pointer until a torch op waits on it. Torch - # experts wait at that op's entry; quantized experts read raw pointers, so they get the result waited. - if getattr(module, "_hf_quantized_needs_local_tp", False): - return wait_tensor(tensor) - return tensor - - @contextlib.contextmanager def _use_local_dtensor_params(module): # Kernels as DeepGEMM require local tensors rather than DTensors. @@ -899,7 +891,9 @@ def ep_forward(hidden_states, top_k_index, top_k_weights): tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens( hidden_states, top_k_index, module.num_experts, ep_group, ep_size ) - tokens = _maybe_wait_tensor(module, tokens) + # 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): + tokens = wait_tensor(tokens) expert_output = self._run_local_experts(experts_forward, tokens, expert_ids) output = self._combine_tokens( expert_output, top_k_weights, order, send_sizes, recv_sizes, ep_group From 112f43e06f2dd319548846c3cbc6d1d9c483e26d Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Wed, 14 Oct 2026 14:39:11 +0000 Subject: [PATCH 10/12] Always wait on the dispatched rows before the experts run Co-Authored-By: Claude Opus 5.5 --- .../distributed/tensor_parallel.py | 5 ++-- tests/tensor_parallel/test_tensor_parallel.py | 23 ++++++------------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index 2399374f3236..9ffa34abe343 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -891,9 +891,8 @@ def ep_forward(hidden_states, top_k_index, top_k_weights): tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens( hidden_states, top_k_index, module.num_experts, ep_group, ep_size ) - # 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): - tokens = wait_tensor(tokens) + # the received rows' pointer is null until a torch op waits on them, and some experts read raw pointers + tokens = wait_tensor(tokens) expert_output = self._run_local_experts(experts_forward, tokens, expert_ids) output = self._combine_tokens( expert_output, top_k_weights, order, send_sizes, recv_sizes, ep_group diff --git a/tests/tensor_parallel/test_tensor_parallel.py b/tests/tensor_parallel/test_tensor_parallel.py index ace335dcb617..7a4b0e6d95db 100644 --- a/tests/tensor_parallel/test_tensor_parallel.py +++ b/tests/tensor_parallel/test_tensor_parallel.py @@ -15,7 +15,6 @@ from unittest.mock import patch import torch -from torch.distributed._functional_collectives import AsyncCollectiveTensor from torch.distributed.device_mesh import init_device_mesh from transformers import AutoModelForCausalLM @@ -371,11 +370,10 @@ def test_sharding_does_not_create_unrelated_module_attributes(self): self.assertEqual(module.random_attr, 123) self.assertFalse(hasattr(module, "num_experts")) - def test_dispatch_waits_only_for_quantized_experts(self): + def test_dispatch_hands_experts_the_received_rows(self): """The all-to-all's pending result (`AsyncCollectiveTensor`) holds a null pointer until a torch op waits on - it. Torch experts get it as is and wait at that op's entry; quantized experts read raw pointers and get the - received rows.""" - _init_distributed(tp=2, backend="gloo")(_dispatch_waits_only_for_quantized_experts)() + it, and experts that launch kernels on raw pointers would read it: the dispatch waits before any experts run.""" + _init_distributed(tp=2, backend="gloo")(_dispatch_hands_experts_the_received_rows)() class _DummyExperts(torch.nn.Module): @@ -384,19 +382,12 @@ def __init__(self): self.num_experts = 2 def forward(self, tokens, expert_ids, weights): - if getattr(self, "_hf_quantized_needs_local_tp", False): - assert type(tokens) is torch.Tensor - else: - assert type(tokens) is AsyncCollectiveTensor + assert type(tokens) is torch.Tensor, type(tokens) return tokens # Worker functions for the expert-parallel layer tests, spawned through `_init_distributed`. -def _dispatch_waits_only_for_quantized_experts(rank): +def _dispatch_hands_experts_the_received_rows(rank): hidden_states = torch.arange(32.0).view(4, 8) + 100 * rank - for quantized in (False, True): - experts = _DummyExperts() - if quantized: - experts._hf_quantized_needs_local_tp = True - EpDispatchExpertsParallel().install_forward(experts, init_device_mesh("cpu", (2,))) - experts(hidden_states, torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]), torch.ones(4, 2)) + experts = EpDispatchExpertsParallel().install_forward(_DummyExperts(), init_device_mesh("cpu", (2,))) + experts(hidden_states, torch.tensor([[0, 3], [1, 2], [2, 1], [3, 0]]), torch.ones(4, 2)) From 402ac3bb2b69ade6f3f7cc552af1fd73cd71ed08 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Wed, 14 Oct 2026 14:48:00 +0000 Subject: [PATCH 11/12] Link the dispatch wait to its benchmarks Co-Authored-By: Claude Opus 5.5 --- src/transformers/distributed/tensor_parallel.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index 9ffa34abe343..e278d88fcea2 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -891,7 +891,8 @@ def ep_forward(hidden_states, top_k_index, top_k_weights): tokens, expert_ids, order, send_sizes, recv_sizes = self._dispatch_tokens( hidden_states, top_k_index, module.num_experts, ep_group, ep_size ) - # the received rows' pointer is null until a torch op waits on them, and some experts read raw pointers + # 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 tokens = wait_tensor(tokens) expert_output = self._run_local_experts(experts_forward, tokens, expert_ids) output = self._combine_tokens( From a40a8d5cdbdf88f36985d9e17aeca2c99d337ace Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Wed, 14 Oct 2026 14:55:47 +0000 Subject: [PATCH 12/12] Link the PR rather than the discussion in the dispatch wait comment Co-Authored-By: Claude Opus 5.5 --- src/transformers/distributed/tensor_parallel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transformers/distributed/tensor_parallel.py b/src/transformers/distributed/tensor_parallel.py index e278d88fcea2..48c6850ac41c 100644 --- a/src/transformers/distributed/tensor_parallel.py +++ b/src/transformers/distributed/tensor_parallel.py @@ -892,7 +892,7 @@ def ep_forward(hidden_states, top_k_index, top_k_weights): 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 + # waited on): https://github.com/huggingface/transformers/pull/49421 tokens = wait_tensor(tokens) expert_output = self._run_local_experts(experts_forward, tokens, expert_ids) output = self._combine_tokens(