Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / utils / communication.py: 51%
278 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Communication helpers shared by the ``core`` modules.
17Everything here is collective-related and therefore Torch-only:
18differentiable collective wrappers (plus the autograd ``Function``s backing
19them), the process-group cache, and the P2P exchange. The synchronous
20collectives each caller needs are thin enough to stay local; what is shared
21here is the part with nontrivial autograd/stream-lifetime semantics, which
22must stay identical across dtensor, expert_parallel and context_parallel.
23"""
24# pylint: disable=C9006,C9007
25from typing import Any, Optional, Sequence, Union
27from packaging.version import Version
28import torch
29import torch.distributed as dist
30import torch.distributed.nn.functional as dist_func
31from torch import Tensor
32from torch._C._distributed_c10d import ProcessGroup
33from torch.distributed import _functional_collectives
35from hyper_parallel.tools.dryrun.simulation import simulated_accelerator
38def _resolve_functional_collective(operation, *, autograd=True):
39 """Prefer the current API name while retaining older Torch support."""
40 suffix = "_autograd" if autograd else ""
41 collective = getattr(_functional_collectives, f"{operation}_single{suffix}", None)
42 if collective is None:
43 collective = getattr(_functional_collectives, f"{operation}_single", None)
44 if collective is None:
45 collective = getattr(_functional_collectives, f"{operation}_tensor{suffix}", None)
46 if collective is None:
47 raise RuntimeError(f"Torch lacks a functional {operation}{suffix} API")
48 return collective
51# Resolve before tracing; inference avoids autograd-only ops without Meta kernels.
52_functional_all_gather = _resolve_functional_collective("all_gather")
53_functional_reduce_scatter = _resolve_functional_collective("reduce_scatter")
54_functional_all_gather_forward = _resolve_functional_collective("all_gather", autograd=False)
55_functional_reduce_scatter_forward = _resolve_functional_collective("reduce_scatter", autograd=False)
57# The legacy autograd collectives on Torch 2.10/2.11 pass gradients directly
58# to native collectives that require contiguous inputs.
59_LEGACY_COLLECTIVES_NEED_CONTIGUOUS_GRAD = Version(torch.__version__).release[:2] in ((2, 10), (2, 11))
62def get_group_local_rank(group: Optional[ProcessGroup] = None) -> int:
63 """Return the current rank's index within ``group``, or 0 before init.
65 Args:
66 group: The group to index into. ``None`` means the default group.
68 Returns:
69 int: The rank of the current process inside ``group``.
70 """
71 if not torch.distributed.is_available() or not torch.distributed.is_initialized():
72 return 0
73 if group is None:
74 return torch.distributed.get_rank()
75 if hasattr(group, "rank"):
76 return group.rank()
77 return torch.distributed.get_group_rank(group, torch.distributed.get_rank())
80def get_device_handle(device_type: str = "npu"):
81 """Return the ``torch`` device module for ``device_type``.
83 Args:
84 device_type: Device backend name, e.g. ``"npu"`` or ``"cuda"``.
86 Returns:
87 The matching ``torch.<device_type>`` module.
89 Raises:
90 RuntimeError: If torch exposes no module for ``device_type``.
91 """
92 try:
93 handle = getattr(torch, device_type)
94 except AttributeError as e:
95 raise RuntimeError(f"Failed to resolve device handle: 'torch.{device_type}'.") from e
96 return handle
99def comm_device_type(backend: Optional[str]) -> Optional[str]:
100 """Return the device type a collective backend stages on, if any.
102 Collective backends run on accelerator devices; CPU-offload paths stage
103 scalars and buffers on the backend's device before the collective. Under
104 logical simulation the group is a fake backend and the simulated
105 accelerator plays that role, so simulated runs allocate communication
106 buffers where real runs do.
108 Args:
109 backend: Collective backend name (``nccl``/``hccl``/``fake``/...).
111 Returns:
112 Device type name (``cuda``/``npu``), or ``None`` for backends with no
113 accelerator staging target (``gloo``, ``None``, or a fake backend with
114 no simulated accelerator).
115 """
116 return {"nccl": "cuda", "hccl": "npu", "fake": simulated_accelerator()}.get(backend)
119def get_world_size() -> int:
120 """Return the Torch distributed world size.
122 Kept as a thin wrapper so single-process call sites and white-box unit
123 tests share one patchable seam; ``torch.distributed.get_world_size`` itself
124 raises before ``init_process_group``.
125 """
126 return dist.get_world_size()
129# Process-group cache keyed by the string form of the sorted rank tuple, e.g.
130# ``"(0, 1, 2, 3)"``. Lives here rather than in a module-specific ``utils`` so
131# that every sub-group creator in ``core`` shares one map. Values are
132# framework-native groups, hence ``Any``.
133EXISTING_COMM_GROUPS: dict[str, Any] = {}
136def ensure_contiguous(x):
137 """Return a contiguous copy of *x* if not already contiguous.
139 Under ``torch.compile`` the contiguity of a graph input is not knowable at
140 trace time, so the copy is emitted unconditionally.
141 """
142 if torch.compiler.is_compiling():
143 return x.contiguous()
144 if not x.is_contiguous() or x.storage_offset() != 0:
145 return x.contiguous()
146 return x
149# ---------------------------------------------------------------------------
150# Process group helpers
151# ---------------------------------------------------------------------------
153def get_created_group(rank_list: Union[list[int], tuple[int, ...]]):
154 """Return an existing process group by rank list, or ``None``."""
155 group_key = str(tuple(sorted(rank_list)))
156 if group_key in EXISTING_COMM_GROUPS:
157 return EXISTING_COMM_GROUPS[group_key]
158 return None
161def split_group(parent_pg=None,
162 split_ranks: Optional[list] = None,
163 timeout=None,
164 pg_options=None,
165 group_desc=None,
166 ):
167 """Create split groups for every rank list in *split_ranks*.
169 Returns the split process group relative to the current rank id.
170 """
171 del parent_pg, timeout, group_desc
172 if split_ranks is None or len(split_ranks) == 0:
173 raise ValueError("split_ranks cannot be None or empty")
175 split_group_pg = None
176 for split_rank in split_ranks:
177 dist_group = get_created_group(split_rank)
178 if dist_group is None:
179 dist_group = dist.new_group(ranks=split_rank, pg_options=pg_options)
180 EXISTING_COMM_GROUPS[str(tuple(sorted(split_rank)))] = dist_group
181 if dist.get_rank() in split_rank:
182 split_group_pg = dist_group
184 return split_group_pg
187def init_process_group(*args, **kwargs) -> None:
188 """Initialize the default torch distributed process group."""
189 if not dist.is_initialized():
190 dist.init_process_group(*args, **kwargs)
193# ---------------------------------------------------------------------------
194# Differentiable collectives
195# ---------------------------------------------------------------------------
197# Mapping from string op names to torch.distributed.ReduceOp
198_OP_MAP = {
199 'sum': dist.ReduceOp.SUM,
200 'prod': dist.ReduceOp.PRODUCT,
201 'max': dist.ReduceOp.MAX,
202 'min': dist.ReduceOp.MIN,
203 # convert tensor elements to int32 and use MIN
204 'all': dist.ReduceOp.MIN,
205 # 'avg' is typically handled by SUM followed by division in current implementation logic
206 'avg': dist.ReduceOp.SUM,
207}
209# Try to add AVG for 'mean' if supported by current torch version
210if hasattr(dist.ReduceOp, "AVG"):
211 _OP_MAP['mean'] = dist.ReduceOp.AVG
212else:
213 # Fallback for older torch versions if necessary, though this might require manual division upstream
214 # Assuming standard behavior where 'mean' implies native AVG support or upstream handling
215 _OP_MAP['mean'] = dist.ReduceOp.SUM
218def resolve_reduce_op(op: Union[str, Any]) -> Any:
219 """Resolve a string op name (or pass through an already-resolved ``ReduceOp``)."""
220 return _OP_MAP.get(op, dist.ReduceOp.SUM) if isinstance(op, str) else op
223def _is_tracing_or_compiling() -> bool:
224 """Return True if we are inside a make_fx trace or torch.compile.
226 ``TracingContext.get()`` raises ``RuntimeError`` when no trace is active,
227 so we catch it and return False.
228 """
229 if torch.compiler.is_compiling():
230 return True
231 try:
232 return torch._guards.TracingContext.get() is not None # pylint: disable=protected-access
233 except Exception: # pylint: disable=W0718
234 return False
237def _reduce_op_to_str(reduce_op: Any) -> str:
238 """Map a ``dist.ReduceOp`` to the string name ``_functional_collectives`` expects."""
239 op_str = {
240 dist.ReduceOp.SUM: 'sum',
241 dist.ReduceOp.PRODUCT: 'product',
242 dist.ReduceOp.MAX: 'max',
243 dist.ReduceOp.MIN: 'min',
244 }.get(reduce_op, 'sum')
245 if hasattr(dist.ReduceOp, 'AVG') and reduce_op == dist.ReduceOp.AVG:
246 op_str = 'avg'
247 return op_str
250class _TorchContiguousGrad(torch.autograd.Function): # pylint: disable=abstract-method
251 """Autograd identity that materializes gradients before upstream collectives."""
253 @staticmethod
254 def forward(ctx: Any, tensor: Tensor) -> Tensor: # pylint: disable=arguments-differ
255 """Return the input unchanged in the forward pass."""
256 del ctx
257 return tensor
259 @staticmethod
260 def backward(ctx: Any, grad_output: Tensor) -> Tensor: # pylint: disable=arguments-differ
261 """Return a contiguous gradient to the preceding autograd node."""
262 del ctx
263 return grad_output.contiguous()
266class _AsyncA2ALazyBwd(torch.autograd.Function):
267 """All-to-all whose forward AND backward return ``AsyncCollectiveTensor``.
269 PyTorch's stock ``all_to_all_single_autograd`` calls ``wait_tensor`` in
270 its backward eagerly, and the autograd engine binds backward stream
271 context to the forward stream — so even if the BWD thread is wrapped
272 in a side-stream context, that wait still lands on the FWD main
273 stream and blocks Attention launches.
275 This Function bypasses the engine's binding by calling the
276 non-autograd functional op in both directions and returning ACT.
277 The wait is deferred to the next consumer's first non-view access
278 (e.g. the indexing backward of ``_unpermute``), giving the FWD
279 thread a small Python window to enqueue its Attention kernels onto
280 the main stream **before** the wait lands there.
281 """
283 @staticmethod
284 def forward(ctx, input_tensor, output_splits, input_splits, group): # pylint: disable=arguments-differ
285 """Perform the forward all-to-all single collective, saving splits and group for backward."""
286 ctx.input_splits = input_splits
287 ctx.output_splits = output_splits
288 ctx.group = group
289 # pylint: disable=C0415
290 from torch.distributed._functional_collectives import all_to_all_single
291 return all_to_all_single(
292 input_tensor, output_splits, input_splits, group,
293 )
295 @staticmethod
296 def backward(ctx, grad_output):
297 """Compute the backward pass by performing the inverse all-to-all with swapped splits."""
298 # pylint: disable=C0415
299 from torch.distributed._functional_collectives import all_to_all_single
300 grad_input = all_to_all_single(
301 grad_output, ctx.input_splits, ctx.output_splits, ctx.group,
302 )
303 return grad_input, None, None, None
306class _TorchP2PExchangeFunction(torch.autograd.Function):
307 """Symmetric bidirectional P2P: send local tensor to peer, receive peer's tensor."""
309 @staticmethod
310 def forward(ctx, tensor: Tensor, peer_rank: int, group) -> Tensor: # pylint: disable=arguments-differ
311 """Perform symmetric bidirectional P2P exchange with ``peer_rank``."""
312 ctx.peer_rank = peer_rank
313 ctx.group = group
314 send_buf = tensor.contiguous()
315 recv_buf = torch.empty_like(send_buf)
316 reqs = dist.batch_isend_irecv([
317 dist.P2POp(dist.isend, send_buf, peer_rank, group),
318 dist.P2POp(dist.irecv, recv_buf, peer_rank, group),
319 ])
320 for req in reqs:
321 req.wait()
322 return recv_buf
324 @staticmethod
325 def backward(ctx, grad_output: Tensor):
326 """Perform symmetric P2P exchange for the backward gradient pass."""
327 send_buf = grad_output.contiguous()
328 recv_buf = torch.empty_like(send_buf)
329 reqs = dist.batch_isend_irecv([
330 dist.P2POp(dist.isend, send_buf, ctx.peer_rank, ctx.group),
331 dist.P2POp(dist.irecv, recv_buf, ctx.peer_rank, ctx.group),
332 ])
333 for req in reqs:
334 req.wait()
335 return recv_buf, None, None
338class _TorchDifferentiableVariableAllGather(torch.autograd.Function):
339 """Variable dim-zero all-gather with an uneven reduce-scatter backward."""
341 @staticmethod
342 def forward(ctx, input_tensor, output_splits, group): # pylint: disable=arguments-differ
343 """Gather each rank's true row count without replicating inputs for A2A."""
344 if input_tensor.ndim == 0:
345 raise ValueError("variable all-gather input must have at least one dimension")
346 splits = tuple(output_splits)
347 if not splits:
348 raise ValueError("output_splits must contain at least one group rank")
349 if any(not isinstance(rows, int) or isinstance(rows, bool) or rows < 0 for rows in splits):
350 raise ValueError(f"output_splits must contain non-negative integers, got {splits!r}")
352 group_rank = dist.get_rank(group=group)
353 if group_rank < 0 or group_rank >= len(splits):
354 raise ValueError(f"group rank must be in [0, {len(splits)}), got {group_rank}")
355 if input_tensor.shape[0] != splits[group_rank]:
356 raise ValueError(
357 "variable all-gather local rows must match output_splits at the group rank, "
358 f"got local_rows={input_tensor.shape[0]}, group_rank={group_rank}, "
359 f"output_splits={splits!r}"
360 )
362 input_tensor = input_tensor.contiguous()
363 feature_shape = tuple(input_tensor.shape[1:])
364 if input_tensor.device.type == "npu":
365 gathered = [input_tensor.new_empty((rows, *feature_shape)) for rows in splits]
366 dist.all_gather(gathered, input_tensor, group=group)
367 else:
368 max_rows = max(splits)
369 if max_rows == 0:
370 gathered = [input_tensor.new_empty((0, *feature_shape)) for _ in splits]
371 else:
372 padded = input_tensor.new_zeros((max_rows, *feature_shape))
373 if input_tensor.shape[0] > 0:
374 padded[:input_tensor.shape[0]].copy_(input_tensor)
375 padded_outputs = [torch.empty_like(padded) for _ in splits]
376 dist.all_gather(padded_outputs, padded, group=group)
377 gathered = [
378 output[:rows].contiguous()
379 for output, rows in zip(padded_outputs, splits)
380 ]
382 ctx.output_splits = splits
383 ctx.group = group
384 ctx.group_rank = group_rank
385 return torch.cat(gathered, dim=0)
387 @staticmethod
388 def backward(ctx, grad_output):
389 """Sum replicated output gradients and return this rank's uneven shard."""
390 output_rows = ctx.output_splits[ctx.group_rank]
391 output = grad_output.new_empty((output_rows, *grad_output.shape[1:]))
392 if sum(ctx.output_splits) == 0:
393 return output, None, None
395 grad_output = grad_output.contiguous()
396 if grad_output.device.type == "npu":
397 from torch_npu.distributed import reduce_scatter_tensor_uneven # pylint: disable=C0415
398 reduce_scatter_tensor_uneven(
399 output,
400 grad_output,
401 input_split_sizes=list(ctx.output_splits),
402 op=dist.ReduceOp.SUM,
403 group=ctx.group,
404 )
405 else:
406 reduced = grad_output.clone()
407 dist.all_reduce(reduced, op=dist.ReduceOp.SUM, group=ctx.group)
408 start = sum(ctx.output_splits[:ctx.group_rank])
409 output.copy_(reduced.narrow(0, start, output_rows))
410 return output, None, None
413def differentiable_all_gather_concat(data: Tensor, group, concat_size: int, concat_dim: int,
414 rank_list=None) -> Tensor:
415 """Autograd-aware all-gather whose results are concatenated along ``concat_dim``.
417 Args:
418 data: Local shard to gather.
419 group: Process group to gather over.
420 concat_size: Unused; kept for call-site compatibility.
421 concat_dim: Dimension the gathered shards are concatenated along.
422 rank_list: Optional global-rank order for the gathered shards. When it
423 differs from the group's own rank order the shards are permuted, so
424 callers can request mesh order without changing the group.
426 Returns:
427 The gathered shards concatenated along ``concat_dim``.
428 """
429 del concat_size
430 data = ensure_contiguous(data)
431 # Eager path: use legacy autograd API (dist_func.all_gather) to preserve
432 # original numerical behavior. Compile/graph-trace path: use functional
433 # collectives for torch.compile / make_fx.
434 if rank_list is not None:
435 group_ranks = dist.get_process_group_ranks(group)
436 if tuple(rank_list) != tuple(group_ranks):
437 # Rank subset gathering (not common path) — same for both modes.
438 output = [
439 _TorchContiguousGrad.apply(tensor)
440 for tensor in dist_func.all_gather(data, group=group)
441 ]
442 rank_to_idx = {int(rank): idx for idx, rank in enumerate(group_ranks)}
443 output = [output[rank_to_idx[int(rank)]] for rank in rank_list]
444 return torch.cat(output, dim=concat_dim)
445 if not _is_tracing_or_compiling():
446 # Eager: original implementation using torch.distributed.nn.functional.
447 output = [
448 _TorchContiguousGrad.apply(tensor)
449 for tensor in dist_func.all_gather(data, group=group)
450 ]
451 return torch.cat(output, dim=concat_dim)
452 if not -data.ndim <= concat_dim < data.ndim:
453 raise IndexError("All-gather concatenation dimension is out of range")
454 concat_dim %= data.ndim
455 if hasattr(_functional_collectives, "all_gather_single"):
456 return _functional_collectives.all_gather_single(data, concat_dim, group) # pylint: disable=no-member
457 # Older Torch needs an explicit autograd API and gather-on-zero reshape.
458 # Functional all-gather only reliably supports gather_dim=0; for other dims we
459 # gather on dim 0 then reshape to avoid _maybe_view_chunk_cat view() bugs
460 # in Dynamo fake tensor tracing.
461 group_size = dist.get_world_size(group)
462 gather = _functional_all_gather if torch.is_grad_enabled() else _functional_all_gather_forward
463 gathered = gather(data, 0, group)
464 if hasattr(gathered, 'wait'):
465 gathered = gathered.wait()
466 # Keep the gradient copy before the collective's backward, after any layout changes.
467 if _LEGACY_COLLECTIVES_NEED_CONTIGUOUS_GRAD and torch.is_grad_enabled():
468 gathered = _TorchContiguousGrad.apply(gathered)
469 if concat_dim == 0:
470 return gathered
471 # Reshape from [group_size * d0, d1, ...] to [d0 * group_size, d1, ...]
472 # by moving the group_size factor from dim 0 to concat_dim.
473 orig_shape = list(data.shape)
474 gathered_shape = [orig_shape[0] * group_size] + orig_shape[1:]
475 gathered = gathered.view(gathered_shape)
476 # Move group_size from dim 0 to concat_dim via unflatten + movedim + flatten
477 unflattened = gathered.unflatten(0, (group_size, orig_shape[0]))
478 moved = torch.movedim(unflattened, 0, concat_dim)
479 result_shape = list(orig_shape)
480 result_shape[concat_dim] *= group_size
481 return moved.reshape(result_shape).contiguous()
484def differentiable_all_to_all_single(input_tensor: Tensor, input_splits: Sequence[int],
485 output_splits: Sequence[int], group) -> Tensor:
486 """Variable-split all-to-all with autograd support for EP token dispatch/combine."""
487 out_total = sum(output_splits)
488 output = torch.empty(
489 out_total, *input_tensor.shape[1:],
490 dtype=input_tensor.dtype, device=input_tensor.device,
491 )
492 return dist_func.all_to_all_single(
493 output, input_tensor,
494 output_split_sizes=output_splits,
495 input_split_sizes=input_splits,
496 group=group,
497 )
500def differentiable_all_to_all_single_async(input_tensor: Tensor, input_splits: Sequence[int],
501 output_splits: Sequence[int], group) -> Tensor:
502 """Truly-async variant of :func:`differentiable_all_to_all_single`.
504 Both forward AND backward return ``AsyncCollectiveTensor``, so the
505 ``wait_tensor`` op is queued lazily — only when a downstream kernel
506 actually reads the result. See :class:`_AsyncA2ALazyBwd` for why the
507 backward needs the same treatment.
509 Args:
510 input_tensor: Input tensor, split along dim 0 by ``input_splits``.
511 input_splits: ``list[int]`` — rows sent to each rank.
512 output_splits: ``list[int]`` — rows received from each rank.
513 group: Process group.
515 Returns:
516 ``AsyncCollectiveTensor`` of shape
517 ``[sum(output_splits), *input_tensor.shape[1:]]``.
518 """
519 return _AsyncA2ALazyBwd.apply(input_tensor, output_splits, input_splits, group)
522def differentiable_all_to_all(input_data: Tensor, output_shape: Sequence[int], group) -> Tensor:
523 """Autograd-aware all-to-all producing a tensor of ``output_shape``."""
524 input_data = ensure_contiguous(input_data)
525 output_tensor = torch.empty(output_shape, device=input_data.device, dtype=input_data.dtype)
526 return dist_func.all_to_all_single(output_tensor, input_data, group=group)
529def differentiable_all_reduce(data: Tensor, op: Union[str, Any], group) -> Tensor:
530 """Autograd-aware all-reduce with string or ``ReduceOp`` *op*."""
531 data = ensure_contiguous(data)
532 reduce_op = resolve_reduce_op(op)
533 # Eager: use legacy autograd API. Compile/graph-trace: use functional collectives.
534 if not _is_tracing_or_compiling():
535 return dist_func.all_reduce(data, op=reduce_op, group=group)
536 # Compile: use functional collective API for torch.compile compatibility.
537 # _functional_collectives.all_reduce expects a string reduceOp and a ProcessGroup.
538 if isinstance(op, str):
539 # Avoid hashing ReduceOp enums while tracing the normal string-op path.
540 op_name = {
541 "sum": "sum", "prod": "product", "max": "max", "min": "min",
542 "all": "min", "avg": "sum", "mean": "avg" if hasattr(dist.ReduceOp, "AVG") else "sum",
543 }.get(op, "sum")
544 else:
545 op_name = _reduce_op_to_str(reduce_op)
546 return _functional_collectives.all_reduce(data, op_name, group)
549def differentiable_reduce_scatter(data: Tensor, dev_num: int, axis: int,
550 op: Union[str, Any], group) -> Tensor:
551 """Autograd-aware reduce-scatter splitting ``axis`` into ``dev_num`` parts."""
552 data = ensure_contiguous(data)
553 reduce_op = resolve_reduce_op(op)
555 # Eager: use legacy autograd API. Compile/graph-trace: use functional collectives.
556 if not _is_tracing_or_compiling():
557 input_tuple = torch.chunk(data, dev_num, dim=axis)
558 output_tensor = torch.empty(input_tuple[0].shape, device=data.device, dtype=data.dtype)
559 output_tensor = dist_func.reduce_scatter(
560 output_tensor, input_tuple, op=reduce_op, group=group
561 )
562 # 'avg' maps to SUM in _OP_MAP, so the division stays manual.
563 if op == 'avg':
564 output_tensor = output_tensor / dev_num
565 return output_tensor
567 if hasattr(_functional_collectives, "reduce_scatter_single"):
568 result = _functional_collectives.reduce_scatter_single( # pylint: disable=no-member
569 data, _reduce_op_to_str(reduce_op), axis, group
570 )
571 return result / dev_num if isinstance(op, str) and op == "avg" else result
572 # The legacy autograd API supports SUM; string 'avg' uses SUM then divides below.
573 # ReduceOp equality/hash methods are not traceable in older Dynamo versions.
574 supported = op in ("sum", "avg") if isinstance(op, str) else op is dist.ReduceOp.SUM
575 if not supported:
576 raise ValueError("Compiled differentiable reduce-scatter supports only sum or string 'avg'")
577 scatter = _functional_reduce_scatter if torch.is_grad_enabled() else _functional_reduce_scatter_forward
578 result = scatter(data, "sum", axis, group)
579 if hasattr(result, 'wait'):
580 result = result.wait()
581 if _LEGACY_COLLECTIVES_NEED_CONTIGUOUS_GRAD and torch.is_grad_enabled():
582 result = _TorchContiguousGrad.apply(result)
583 # 'avg' maps to SUM in _OP_MAP, so the division stays manual.
584 if isinstance(op, str) and op == 'avg':
585 result = result / dev_num
586 return result
589def differentiable_variable_all_gather(
590 input_tensor: Tensor, output_splits: Sequence[int], group) -> Tensor:
591 """Gather variable dim-zero shards on HCCL or Gloo with autograd support."""
592 return _TorchDifferentiableVariableAllGather.apply(
593 input_tensor, tuple(output_splits), group
594 )
597def wait_async_tensor(tensor: Tensor) -> Tensor:
598 """Wait for an async collective tensor to become materialised.
600 Idempotent — calling on an already-waited tensor is a no-op.
601 """
602 from torch.distributed._functional_collectives import wait_tensor # pylint: disable=C0415
603 wait_tensor(tensor)
604 return tensor
607def p2p_exchange(tensor: Tensor, peer_rank: int, group=None) -> Tensor:
608 """Symmetric bidirectional P2P exchange with ``peer_rank``."""
609 if peer_rank == dist.get_rank(group):
610 return tensor
611 return _TorchP2PExchangeFunction.apply(tensor, peer_rank, group)
614def exchange_splits_via_all_to_all(input_tensor: Tensor, group) -> Tensor:
615 """All-to-all a per-rank split vector, returning the received counts.
617 Used by the token dispatchers to learn how many tokens every peer sends
618 them; the exchange carries no gradient, so plain ``dist`` collectives are
619 used. Runs asynchronously with an explicit ``handle.wait()`` rather than
620 ``async_op=False``: the implicit cross-stream sync is NCCL-only, and on
621 HCCL the compute stream may read the output before the collective write is
622 visible, producing garbage values that blow up downstream allocations.
623 """
624 output = torch.empty(
625 [input_tensor.shape[0]],
626 dtype=input_tensor.dtype, device=input_tensor.device,
627 )
628 handle = dist.all_to_all_single(
629 output, input_tensor, group=group, async_op=True,
630 )
631 if handle is not None:
632 handle.wait()
633 return output
636def gather_counts_via_all_gather(input_tensor: Tensor, group, world_size: int) -> Tensor:
637 """All-gather a per-rank count vector into an ``[world_size, *shape]`` view.
639 Same async-with-explicit-wait rationale as
640 :func:`exchange_splits_via_all_to_all`.
641 """
642 output = torch.empty(
643 [world_size * input_tensor.shape[0]],
644 dtype=input_tensor.dtype,
645 device=input_tensor.device,
646 )
647 handle = dist.all_gather_into_tensor(
648 output, input_tensor, group=group, async_op=True,
649 )
650 if handle is not None:
651 handle.wait()
652 return output.view(world_size, input_tensor.shape[0])