Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_reduce.py: 89%
199 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 2025-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"""
16Distributed implementation for Reduce operator.
17"""
19from copy import deepcopy
20from typing import Sequence, Union, Tuple, List
22from hyper_parallel.core.dtensor.layout import Layout
23from .parallel_ops import DistributedOp
26StrOrTuple = Union[str, Tuple["StrOrTuple", ...], List["StrOrTuple"]]
29# Preserve Torch keyword names for calls forwarded by __torch_function__.
30# pylint: disable-next=redefined-builtin
31def _normalize_reduce_args(input, dim=None, keepdim=False, dtype=None):
32 """Normalize reduce-family arguments to consistent positional form.
34 Handles torch.sum / torch.mean / torch.prod / torch.all, where *dim* and
35 *keepdim* are ordinary positional parameters. SumExt and MeanExt also pass
36 a trailing dtype slot positionally; normalize it here while keeping layout
37 inference based only on ``input_layout``, ``dim``, and ``keepdim``.
39 Args:
40 input: The input tensor (DTensor or Tensor).
41 dim: Dimension(s) to reduce. None means all dimensions, () means no reduction.
42 keepdim: Whether to retain reduced dimensions.
43 dtype: Optional output dtype.
45 Returns:
46 tuple: ``((input, dim, keepdim, dtype), {})`` — all-positional, empty kwargs.
47 """
48 return (input, dim, keepdim, dtype), {}
51class ReduceExtDistributedOpBase(DistributedOp):
52 """
53 Base class for distributed reduce operators.
55 Args:
56 op_name (str): Name of the operator to register.
57 partial_type (list): List of the operator for allreduce.
58 """
60 _TORCH_DTYPE_OP_NAMES = frozenset({"sum", "mean", "prod"})
61 _MS_POSITIONAL_DTYPE_OP_NAMES = frozenset({"SumExt", "MeanExt"})
63 def __init__(self, op_name, partial_type=None):
64 super().__init__(op_name)
65 if partial_type is None:
66 partial_type = ["sum"]
67 self.partial_type = partial_type
68 self._allow_partial_inputs = True
70 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
71 """
72 Preprocess arguments for reduce operators.
74 Normalizes ``(input, dim, keepdim)``, converts DTensor inputs to local
75 tensors, and builds ``cache_values`` for layout inference.
77 Args:
78 args (tuple): Positional arguments passed to the operator call.
79 kwargs (dict): Keyword arguments passed to the operator call.
81 Returns:
82 tuple: ``(local_args, local_kwargs, cache_values)`` where
83 ``local_args`` is ``(input_local, dim, keepdim)`` and
84 ``cache_values`` is ``[input_layout, dim, keepdim]``.
85 """
86 has_dtype_arg = len(args) >= 4 or "dtype" in kwargs
87 normalized_args, _ = _normalize_reduce_args(*args, **kwargs)
88 input_tensor, dim, keepdim, dtype = normalized_args
89 local_args = (input_tensor.to_local(), dim, keepdim)
90 # torch.prod has a separate global overload that takes no dim/keepdim.
91 if self.op_name == "prod" and dim is None:
92 local_args = (input_tensor.to_local(),)
93 local_kwargs = {}
94 if has_dtype_arg:
95 if self.op_name in self._TORCH_DTYPE_OP_NAMES:
96 local_kwargs["dtype"] = dtype
97 elif self.op_name in self._MS_POSITIONAL_DTYPE_OP_NAMES:
98 local_args += (dtype,)
99 else:
100 raise TypeError(
101 f"For {self.op_name}, the `dtype` argument is not supported."
102 )
103 cache_values = [input_tensor.layout, dim, keepdim]
104 return local_args, local_kwargs, cache_values
106 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
107 """
108 Infer output layout for reduce operators.
110 Rules:
111 1. Input must have a valid mesh_shape.
112 2. ``dim`` must be ``None``, ``int``, ``tuple[int]``, or ``list[int]`` —
113 never a ``Tensor``.
114 3. ``dim`` values must be valid axis indices for the input tensor.
115 4. Reduce axes are replaced with ``"None"`` (keepdim) or dropped;
116 Partial status is applied on sharded reduced axes.
118 Args:
119 cache_values (list): ``[input_layout, dim, keepdim]``.
121 Returns:
122 tuple: ``((output_layout,), None)``
124 Raises:
125 ValueError: If the input layout is missing or ``mesh_shape`` is ``None``.
126 TypeError: If ``dim`` is a ``Tensor``.
127 ValueError: If a ``dim`` axis index is out of range.
128 """
129 x_layout = cache_values[0]
130 dim = cache_values[1]
131 keepdim = cache_values[2]
133 if x_layout is None or x_layout.mesh_shape is None:
134 raise ValueError(
135 f"For {self.op_name}, input layout cannot be None."
136 )
138 # Check partial inputs
139 if not self._allow_partial_inputs:
140 self._check_partial_inputs([x_layout])
142 if dim is not None and not isinstance(dim, (int, tuple, list)):
143 raise TypeError(
144 f"For {self.op_name}, the `dim` argument should be `None`, `int`, "
145 f"`tuple[int]`, or `list[int]`, but got {type(dim).__name__}."
146 )
148 # Infer the output shape based on dim and keepdim
149 output_layout = self._infer_output_layout(x_layout, dim, keepdim)
151 return ((output_layout,), None)
153 def _infer_output_layout(self, x_layout, dim, keepdim):
154 """Infer output layout for reduce operator."""
155 # Case 1: dim is None — reduce all dimensions (scalar output or all-None when keepdim).
156 if dim is None:
157 return self._handle_all_axis_reduce(x_layout, keepdim)
159 # Case 2: dim is an empty tuple/list — reduce no dimensions, output layout equals input.
160 if isinstance(dim, (tuple, list)) and len(dim) == 0:
161 output_layout = Layout(
162 mesh_shape=x_layout.mesh_shape,
163 alias_name=x_layout.alias_name,
164 rank_list=x_layout.rank_list
165 )
166 return output_layout(*x_layout.alias_tensor_map)
168 # Case 3: dim is int, tuple, or list with at least one element.
169 output_layout = Layout(
170 mesh_shape=x_layout.mesh_shape,
171 alias_name=x_layout.alias_name,
172 rank_list=x_layout.rank_list
173 )
174 x_map = x_layout.alias_tensor_map
175 reduce_alias, x_map = self.replace_axis_with_none(dim, x_layout, keepdim)
176 output_layout = output_layout(*x_map)
177 self._apply_partial(output_layout, reduce_alias)
178 return output_layout
180 def _handle_all_axis_reduce(self, x_layout, keepdim):
181 """Handle the case where dim is None, meaning reduce all dimensions."""
182 layout = Layout(
183 mesh_shape=x_layout.mesh_shape,
184 alias_name=x_layout.alias_name,
185 rank_list=x_layout.rank_list
186 )
188 if not keepdim:
189 output_layout = layout()
190 else:
191 tensor_map = tuple(["None"] * len(x_layout.alias_tensor_map))
192 output_layout = layout(*tensor_map)
194 self._apply_partial(output_layout, x_layout.alias_tensor_map)
195 return output_layout
197 def replace_axis_with_none(self, dim, x_layout, keepdim):
198 """Replace or drop dimensions depending on keepdim."""
199 if not isinstance(dim, (tuple, list)):
200 dim = [dim]
201 else:
202 dim = list(dim)
204 rank = len(x_layout.alias_tensor_map)
205 for i, axis_id in enumerate(dim):
206 if axis_id < 0:
207 dim[i] = rank + axis_id
208 if not isinstance(axis_id, int) or dim[i] >= rank or dim[i] < 0:
209 raise ValueError(f"Invalid reduce axis index {axis_id} at position {i}.")
211 alias_tensor_map = x_layout.alias_tensor_map
212 reduce_alias = [alias_tensor_map[axis_id] for axis_id in dim if
213 alias_tensor_map[axis_id] is not None and alias_tensor_map[axis_id] != "None"]
214 reduce_alias = self._flatten_aliases(reduce_alias)
216 if keepdim:
217 return self._replace_keepdim(alias_tensor_map, reduce_alias)
218 return self._replace_dropdim(alias_tensor_map, reduce_alias, dim)
220 def _flatten_aliases(self, reduce_alias):
221 """Flatten reduce_alias into a list of atomic alias strings."""
222 flat = []
223 for alias in reduce_alias:
224 if isinstance(alias, (tuple, list)):
225 flat.extend(alias)
226 else:
227 flat.append(alias)
228 return flat
230 def _replace_keepdim(self, alias_tensor_map, reduce_alias):
231 """keepdim, replace reduce alias with 'None'."""
232 new_alias_map = []
233 for alias in alias_tensor_map:
234 if isinstance(alias, (tuple, list)):
235 new_alias = tuple("None" if item in reduce_alias else item for item in alias)
236 new_alias_map.append(new_alias)
237 else:
238 if alias in reduce_alias:
239 new_alias_map.append("None")
240 else:
241 new_alias_map.append(alias)
242 new_alias_map = self._compact_tensor_map(new_alias_map)
243 return reduce_alias, tuple(new_alias_map)
245 def _replace_dropdim(self, alias_tensor_map, reduce_alias, dim):
246 """Compress reduce dim."""
247 new_alias_map = []
248 for i, alias in enumerate(alias_tensor_map):
249 if i in dim:
250 continue
251 if isinstance(alias, (tuple, list)):
252 new_alias = tuple(item for item in alias if item not in reduce_alias)
253 if new_alias:
254 new_alias_map.append(new_alias)
255 else:
256 if alias in reduce_alias:
257 continue
258 new_alias_map.append(alias)
259 new_alias_map = self._compact_tensor_map(new_alias_map)
260 return reduce_alias, tuple(new_alias_map)
262 def _compact_tensor_map(self, alias_map: Sequence[StrOrTuple]) -> Tuple[StrOrTuple, ...]:
263 """Extend tensor map of 'None'."""
265 def _compress(elem: StrOrTuple) -> StrOrTuple:
266 if isinstance(elem, (list, tuple)):
267 compressed = tuple(_compress(e) for e in elem)
268 if len(compressed) == 1:
269 return compressed[0]
270 if all(x == 'None' for x in compressed):
271 return 'None'
272 return compressed
273 return elem
275 return tuple(_compress(elem) for elem in alias_map)
277 def _apply_partial(self, out_layout, alias):
278 """Apply all partial to given alias (string, tuple, list)."""
279 if alias == "None":
280 return
281 if isinstance(alias, (tuple, list)):
282 for elem in alias:
283 self._apply_partial(out_layout, elem)
284 else:
285 for ops in self.partial_type:
286 out_layout.set_partial_by_dev_axis(alias, ops)
289class SumExtDistributedOp(ReduceExtDistributedOpBase):
290 """Distributed implementation for SumExt operator."""
292 def __init__(self, op_name="SumExt"):
293 super().__init__(op_name, partial_type=["sum"])
296class MeanExtDistributedOp(ReduceExtDistributedOpBase):
297 """Distributed implementation for MeanExt operator."""
299 def __init__(self, op_name="MeanExt"):
300 super().__init__(op_name, partial_type=["avg"])
303class ReduceMaxDistributedOp(ReduceExtDistributedOpBase):
304 """Distributed implementation for ReduceMax operator."""
306 def __init__(self, op_name="ReduceMax"):
307 super().__init__(op_name, partial_type=["max"])
310class ProdExtDistributedOp(ReduceExtDistributedOpBase):
311 """
312 Distributed implementation for ProdExt operator (product of all elements or along a dim).
313 Compatible with torch.prod arguments.
314 """
316 def __init__(self, op_name="prod"):
317 super().__init__(op_name, partial_type=["prod"])
320class AllExtDistributedOp(ReduceExtDistributedOpBase):
321 """
322 Distributed implementation for All operator
323 Returns the cumulative sum of elements of input in the dimension dim.
324 """
326 def __init__(self, op_name="all"):
327 super().__init__(op_name, partial_type=["all"])
330class MaxDistributedOp(ReduceExtDistributedOpBase):
331 """
332 Distributed implementation for Pytorch style Max operator.
334 Supports three Pytorch behaviors:
335 1. torch.max(input) -> Global reduction (returns single Tensor)
336 2. torch.max(input, dim, keepdim=False) -> Dimension reduction (returns (values, indices))
337 3. torch.max(input, other) -> Element-wise max (returns single Tensor)
338 """
340 def __init__(self, op_name="max"):
341 super().__init__(op_name, partial_type=["max"])
343 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
344 """
345 Preprocess arguments for Max/Min operators.
347 Routes between element-wise mode (two DTensor inputs) and reduction
348 mode (input, dim, keepdim). All parameters are positional with empty
349 kwargs.
351 Args:
352 args (tuple): Positional arguments passed to the operator call.
353 kwargs (dict): Keyword arguments passed to the operator call.
355 Returns:
356 tuple: ``(local_args, local_kwargs, cache_values)``.
357 """
358 # Normalize named operands before choosing the elementwise overload.
359 kwargs = dict(kwargs)
360 if not args and "input" in kwargs:
361 args = (kwargs.pop("input"),)
362 if "other" in kwargs:
363 other = kwargs.pop("other")
364 if len(args) != 1 or kwargs:
365 raise TypeError(f"For {self.op_name}, other cannot be combined with reduction arguments.")
366 args += (other,)
367 # Element-wise mode: torch.max(a, b) — second arg is a DTensor.
368 if len(args) >= 2 and hasattr(args[1], "_layout"):
369 input_tensor = args[0]
370 other_tensor = args[1]
371 local_args = (input_tensor.to_local(), other_tensor.to_local())
372 local_kwargs = {}
373 cache_values = [input_tensor.layout, other_tensor.layout]
374 return local_args, local_kwargs, cache_values
376 # Reduction mode: torch.max(input, dim, keepdim) / MaxDim(input, dim, keepdim).
377 has_dtype_arg = len(args) >= 4 or "dtype" in kwargs
378 args, kwargs = _normalize_reduce_args(*args, **kwargs)
379 input_tensor, dim, keepdim, _ = args
380 if has_dtype_arg:
381 raise TypeError(
382 f"For {self.op_name}, the `dtype` argument is not supported."
383 )
384 # torch.max(x) global reduction: only pass the tensor so the call
385 # remains torch.max(local_x), not torch.max(local_x, None, False).
386 if dim is None:
387 local_args = (input_tensor.to_local(),)
388 else:
389 local_args = (input_tensor.to_local(), dim, keepdim)
390 local_kwargs = {}
392 cache_values = [input_tensor.layout, dim, keepdim]
393 return local_args, local_kwargs, cache_values
395 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
396 """
397 Infer output layouts for Max/Min operators.
399 Rules:
400 1. Element-wise mode (two Layouts in *cache_values*): output layout
401 equals the first input layout.
402 2. Reduction mode: same rules as ``ReduceExtDistributedOpBase``.
403 3. When ``dim`` is ``None`` (global reduction), returns a single layout.
404 4. When ``dim`` is specified, returns ``(values_layout, indices_layout)``.
405 5. ``dim`` must be ``None``, ``int``, ``tuple[int]``, or ``list[int]``.
407 Args:
408 cache_values (list): ``[input_layout, dim, keepdim]`` for reduction,
409 or ``[input_layout, other_layout]`` for element-wise.
411 Returns:
412 tuple: ``((output_layout,), None)`` or ``((values_layout, indices_layout), None)``.
414 Raises:
415 ValueError: If the input layout is missing or ``mesh_shape`` is ``None``.
416 TypeError: If ``dim`` is not ``None``, ``int``, ``tuple``, or ``list``.
417 """
418 # Element-wise mode: two Layout objects in cache_values.
419 if len(cache_values) == 2 and hasattr(cache_values[1], "mesh_shape"):
420 # Check partial inputs
421 if not self._allow_partial_inputs:
422 self._check_partial_inputs(cache_values)
423 return ((deepcopy(cache_values[0]),), None)
425 x_layout = cache_values[0]
426 dim = cache_values[1]
427 keepdim = cache_values[2]
429 if x_layout is None or x_layout.mesh_shape is None:
430 raise ValueError(
431 f"For {self.op_name}, input layout cannot be None."
432 )
434 # Check partial inputs
435 if not self._allow_partial_inputs:
436 self._check_partial_inputs([x_layout])
438 if dim is not None and not isinstance(dim, (int, tuple, list)):
439 raise TypeError(
440 f"For {self.op_name}, the `dim` argument should be `None`, `int`, "
441 f"`tuple[int]`, or `list[int]`, but got {type(dim).__name__}."
442 )
444 values_layout = self._infer_output_layout(x_layout, dim, keepdim)
446 if dim is None:
447 # torch.max(input) -> Single Tensor
448 return ((values_layout,), None)
450 # torch.max(input, dim) -> (values, indices)
451 indices_layout = deepcopy(values_layout)
452 return ((values_layout, indices_layout), None)
455class MinDistributedOp(MaxDistributedOp):
456 """
457 Distributed implementation for Pytorch style Min operator.
459 Supports three Pytorch behaviors:
460 1. torch.min(input) -> Global reduction (returns single Tensor)
461 2. torch.min(input, dim, keepdim=False) -> Dimension reduction (returns (values, indices))
462 3. torch.min(input, other) -> Element-wise min (returns single Tensor)
463 """
465 def __init__(self, op_name="min"):
466 # Call the parent class (MaxDistributedOp) initialization
467 super().__init__(op_name=op_name)
468 # Override the partial_type to use "min" instead of "max" for the underlying communication
469 self.partial_type = ["min"]