Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_gather.py: 72%
239 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"""
16Distributed implementation for Gather operator.
17"""
19from typing import Tuple
21from hyper_parallel.core.dtensor.layout import Layout
22from hyper_parallel.core.utils.communication import get_group_local_rank
23from .parallel_ops import DistributedOp
26# Preserve Torch keyword names for calls forwarded by __torch_function__.
27# pylint: disable-next=redefined-builtin
28def _normalize_index_select_args(input, dim, index):
29 return (input, dim, index), {}
32# Preserve Torch keyword names for calls forwarded by __torch_function__.
33# pylint: disable-next=redefined-builtin
34def _normalize_gatherd_args(input, dim, index, **kwargs):
35 """Normalize torch.gather / GatherD args, forwarding keyword-only params."""
36 return (input, dim, index), kwargs
39def _normalize_gathernd_args(input_tensor, indices):
40 return (input_tensor, indices), {}
43class IndexSelectDistributedOp(DistributedOp):
44 """Distributed implementation for Index Select operator."""
46 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
47 """
48 Preprocess arguments for IndexSelect operator.
50 Args:
51 args (tuple): Input arguments (input, dim, index).
52 kwargs (dict): Keyword arguments.
54 Returns:
55 tuple: (local_args, local_kwargs, cache_values)
56 """
57 args, _ = _normalize_index_select_args(*args, **kwargs)
58 input_tensor, dim, index = args[0], args[1], args[2]
59 local_args = (input_tensor.to_local(), dim, index.to_local())
60 local_kwargs = {}
61 cache_values = [input_tensor.layout, index.layout, dim]
62 return local_args, local_kwargs, cache_values
64 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
65 """
66 Infer output layouts for Index Select operations.
68 Rules:
69 1. Input and index must not have Partial status.
70 2. cache_values must contain [input_layout, index_layout, dim].
71 3. dim must be within the valid input rank range.
72 4. index must be one-dimensional.
73 5. Output replaces the selected input dimension with the index layout.
74 6. If the selected input dimension is sharded, output carries Partial('sum').
76 Args:
77 cache_values (list): [input_layout, index_layout, dim].
79 Returns:
80 tuple: ((output_layout,), None)
82 Raises:
83 ValueError: If input layouts are not compatible or have partial status.
84 """
85 if not self._allow_partial_inputs:
86 self._check_partial_inputs(cache_values[:2])
88 # Parse layout info
89 p_layout, i_layout, axis = cache_values[0], cache_values[1], cache_values[2]
91 p_tensor_map = p_layout.alias_tensor_map
92 i_tensor_map = i_layout.alias_tensor_map
94 # 1. Validate the axis range before any manipulation
95 if axis < -len(p_tensor_map) or axis >= len(p_tensor_map):
96 raise ValueError(
97 f"For {self.op_name}, dim value {axis} is out of valid range"
98 )
100 # 2. Convert negative axis to positive index to avoid Python slicing bugs
101 if axis < 0:
102 axis += len(p_tensor_map)
104 if len(i_tensor_map) != 1:
105 raise ValueError(
106 f"For {self.op_name}, index is not a one-dimensional Tensor"
107 )
109 # 3. Create output layout map
110 # We allow sharding on the `axis`. Since `index_select` replaces the `axis`
111 # dimension with the `index` dimension, if `axis` was sharded, that mesh
112 # dimension is removed from the output tensor map.
113 output_tensor_map = list(p_tensor_map[:axis]) + list(i_tensor_map) + list(p_tensor_map[axis + 1 :])
115 output_layout = Layout(
116 mesh_shape=p_layout.mesh_shape,
117 alias_name=p_layout.alias_name,
118 rank_list=p_layout.rank_list,
119 )
120 output_layout = output_layout(*output_tensor_map)
122 # 4. Implicit Communication via Partial Layout
123 # If the gather axis was sharded, the local output will only be a masked partial result.
124 # We set the output layout to Partial('sum') for that specific mesh dimension so the
125 # OpDispatcher handles the AllReduce automatically when this tensor is used later.
126 shard_mesh_dim_name = p_tensor_map[axis]
127 if shard_mesh_dim_name != "None":
128 # Handle possible multi-axis sharding tuple
129 if isinstance(shard_mesh_dim_name, tuple):
130 for dim_name in shard_mesh_dim_name:
131 if dim_name != "None":
132 output_layout.set_partial_by_dev_axis(dim_name, 'sum')
133 else:
134 output_layout.set_partial_by_dev_axis(shard_mesh_dim_name, 'sum')
136 return ((output_layout,), None)
138 def get_expand_impl(self, func, infer_result, cache_values): # pylint: disable=W0221
139 """
140 Get the expanded execution implementation for Index Select.
141 """
142 p_layout = cache_values[0]
143 axis = cache_values[2]
144 if axis < 0:
145 axis += len(p_layout.alias_tensor_map)
147 shard_mesh_dim_name = p_layout.alias_tensor_map[axis]
149 # If the axis is NOT sharded, fallback to standard execution
150 if shard_mesh_dim_name == "None":
151 return None
153 # If the axis IS sharded, return a custom function with Masking ONLY.
154 # The explicit AllReduce is completely removed.
155 def expand_impl(input_tensor, dim, index, **kwargs):
156 mesh = p_layout.mesh
158 # Fetch the communication group for the sharded mesh dimension
159 if isinstance(shard_mesh_dim_name, tuple):
160 target_dim_name = next(d for d in shard_mesh_dim_name if d != "None")
161 else:
162 target_dim_name = shard_mesh_dim_name
164 comm_group_info = mesh.get_comm_group_by_axis(target_dim_name)
165 group = comm_group_info.group if hasattr(comm_group_info, 'group') else comm_group_info
167 # Get the rank of the current device within this specific communication group
168 group_rank = get_group_local_rank(group)
170 # Calculate global index boundaries for the local chunk
171 local_dim_size = input_tensor.shape[dim]
172 start_idx = group_rank * local_dim_size
173 end_idx = start_idx + local_dim_size
175 # 1. Compute mask: True for indices that belong to the current rank
176 mask = (index >= start_idx) & (index < end_idx)
178 # 2. Shift global indices to local indices
179 safe_index = index - start_idx
181 # Clamp safe_index to valid local ranges to prevent CUDA out-of-bounds
182 # errors during the local index_select (invalid ones will be masked out anyway).
183 safe_index = safe_index.clamp(min=0, max=local_dim_size - 1)
185 # 3. Perform local index_select using tensor's built-in method
186 local_out = input_tensor.index_select(dim, safe_index, **kwargs)
188 # 4. Mask out the invalid indices (set them to 0)
189 # Reshape the 1D mask to broadcast against the output shape
190 mask_shape = [1] * local_out.ndim
191 mask_shape[dim] = -1
192 mask_reshaped = mask.reshape(mask_shape).to(local_out.dtype)
194 local_out = local_out * mask_reshaped
196 # Return the partial local tensor directly. The framework's layout engine
197 # and OpDispatcher will trigger the AllReduce when this Partial tensor
198 # is redistributed to a non-partial layout.
199 return local_out
201 return expand_impl
204class GatherDDistributedOp(DistributedOp):
205 """Distributed implementation for GatherD operator.
207 GatherD gathers values along a specified axis from the input tensor using the index tensor.
209 Signature: GatherD(input, dim, index) -> output
211 Key constraints:
212 - Input and index must have the same number of dimensions
213 - Output inherits the sharding pattern of the input tensor
214 """
216 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
217 """
218 Preprocess arguments for GatherD operator.
220 Args:
221 args (tuple): Input arguments (input, dim, index).
222 kwargs (dict): Keyword arguments.
224 Returns:
225 tuple: (local_args, local_kwargs, cache_values)
226 """
227 args, kwargs = _normalize_gatherd_args(*args, **kwargs)
228 input_tensor, dim, index = args[0], args[1], args[2]
229 local_args = (input_tensor.to_local(), dim, index.to_local())
230 local_kwargs = kwargs
231 cache_values = [input_tensor.layout, index.layout, dim]
232 return local_args, local_kwargs, cache_values
234 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
235 """
236 Infer output layouts for GatherD operations.
238 Rules:
239 1. Input and index must not have Partial status.
240 2. cache_values must contain [input_layout, index_layout, dim].
241 3. Input and index must have the same rank.
242 4. dim must be within the valid input rank range.
243 5. Input and index must use the same sharding on non-dim axes.
244 6. Output inherits index layout and becomes Partial('sum') when dim is sharded.
246 Args:
247 cache_values (list): [input_layout, index_layout, dim].
249 Returns:
250 tuple: ((output_layout,), None)
252 Raises:
253 ValueError: If input layouts are not compatible or have partial status.
254 """
255 if not self._allow_partial_inputs:
256 self._check_partial_inputs(cache_values[:2])
258 input_layout, index_layout, dim = cache_values[0], cache_values[1], cache_values[2]
259 # Validate layouts exist
260 if input_layout is None or not hasattr(input_layout, "tensor_map"):
261 raise ValueError(f"For {self.op_name}, input layout cannot be None")
262 if index_layout is None or not hasattr(index_layout, "tensor_map"):
263 raise ValueError(f"For {self.op_name}, index layout cannot be None")
264 input_tensor_map = input_layout.alias_tensor_map
265 index_tensor_map = index_layout.alias_tensor_map
266 # Validate same rank
267 if len(input_tensor_map) != len(index_tensor_map):
268 raise ValueError(
269 f"For {self.op_name}, input and index must have the same number of dimensions. "
270 f"Got input rank={len(input_tensor_map)}, index rank={len(index_tensor_map)}"
271 )
272 # Validate dim is in valid range
273 rank = len(input_tensor_map)
274 if dim < -rank or dim >= rank:
275 raise ValueError(
276 f"For {self.op_name}, dim value {dim} is out of valid range [{-rank}, {rank-1}]"
277 )
278 # Normalize negative dim
279 if dim < 0:
280 dim = dim + rank
281 for axis, (input_axis_map, index_axis_map) in enumerate(zip(input_tensor_map, index_tensor_map)):
282 if axis == dim:
283 continue
284 if input_axis_map != index_axis_map:
285 raise ValueError(
286 f"For {self.op_name}, input and index must use the same sharding on non-dim axis {axis}. "
287 f"Got input tensor_map={input_tensor_map}, index tensor_map={index_tensor_map}, dim={dim}"
288 )
289 # Output inherits index layout
290 output_layout = Layout(
291 mesh_shape=index_layout.mesh_shape,
292 alias_name=index_layout.alias_name,
293 rank_list=index_layout.rank_list,
294 )
295 output_layout.set_tensor_map(index_layout.tensor_map)
296 dim_axis_name = input_tensor_map[dim]
297 if dim_axis_name != "None":
298 # pylint: disable=protected-access
299 # Inherit current partial state from index layout
300 output_layout._partial = list(index_layout.partial)
301 if isinstance(dim_axis_name, tuple):
302 for axis_name in dim_axis_name:
303 if axis_name != "None":
304 output_layout.set_partial_by_dev_axis(axis_name, 'sum')
305 else:
306 output_layout.set_partial_by_dev_axis(dim_axis_name, 'sum')
307 # pylint: disable=protected-access
308 # Rebuild readable alias tensor map
309 output_layout._alias_tensor_map = output_layout._build_readable_tensor_map()
310 # pylint: disable=protected-access
311 # Sync tensor_map to placement representation
312 output_layout.tensor_map_to_placement()
313 # Update compact string description
314 output_layout.update_compact_str()
315 return ((output_layout,), None)
317 def get_expand_impl(self, func, infer_result, cache_values): # pylint: disable=W0221
318 """
319 Returns the execution implementation wrapper for distributed GatherD.
321 When the dim axis is sharded, each rank gathers from its local slice of the input tensor.
322 The indices need to be adjusted to account for the local partition offset.
324 Args:
325 func: The original GatherD function to wrap
326 infer_result: The inferred output layouts and extra info
327 cache_values: [input_layout, index_layout, dim]
329 Returns:
330 Callable: Distributed implementation wrapper, or None if no sharding
331 """
332 input_layout = cache_values[0]
333 dim = cache_values[2]
334 if dim < 0:
335 dim += len(input_layout.tensor_map)
336 input_alias_map = input_layout.alias_tensor_map
337 # Check if dim axis is sharded (enhanced MP)
338 if input_alias_map[dim] == "None": # native sharding, no need for custom implementation
339 return None
341 dim_axis_name = input_alias_map[dim]
342 if isinstance(dim_axis_name, tuple):
343 dim_axis_name = next(axis for axis in dim_axis_name if axis != "None")
345 def distributed_gatherd_impl(*args, **kwargs):
346 """
347 Distributed GatherD implementation for sharded dim axis.
349 Each rank gathers from its local slice of input tensor.
350 Indices are adjusted by subtracting the local partition offset.
351 """
352 input_tensor = args[0]
353 index_tensor = args[2]
354 # Calculate local partition offset for the dim axis
355 mesh = input_layout.mesh
356 mesh_dim_idx = input_layout.alias_name.index(dim_axis_name)
357 # Get the coordinate of current rank along the mesh dimension
358 dim_coord = mesh.get_local_rank(mesh_dim_idx)
359 # Calculate the size of input tensor's dim dimension per partition
360 input_dim_size = input_tensor.shape[dim]
361 # Calculate the starting index of local partition
362 local_start_index = int(dim_coord * input_dim_size)
363 local_end_index = int(local_start_index + input_dim_size)
364 # Adjust indices: subtract local_start_index to map global indices to local range
365 # This is similar to how Embedding shifts indices for Row Parallelism
366 adjusted_index = index_tensor - local_start_index
367 # Create mask to identify out-of-bounds indices
368 # Indices outside [0, local_dim_size) belong to other partitions
369 mask = (index_tensor >= local_start_index) & (index_tensor < local_end_index)
370 # Cross-platform cast to matching int dtype
371 mask_int = mask.to(index_tensor.dtype)
372 # Zero out invalid indices to prevent out-of-bounds access
373 safe_index = adjusted_index * mask_int
374 # Replace original index tensor with adjusted index
375 new_args = list(args)
376 new_args[2] = safe_index
377 # Execute native GatherD with adjusted indices
378 output = func(*new_args, **kwargs)
379 # Zero out outputs corresponding to invalid indices
380 mask_int = mask_int.to(output.dtype)
381 output = output * mask_int
382 return output
383 return distributed_gatherd_impl
386class GatherNdDistributedOp(DistributedOp):
387 """Distributed implementation for GatherNd operator."""
389 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
390 """
391 Preprocess arguments for GatherNd operator.
393 Args:
394 args (tuple): Input arguments (input, indices).
395 kwargs (dict): Keyword arguments.
397 Returns:
398 tuple: (local_args, local_kwargs, cache_values)
399 """
400 args, _ = _normalize_gathernd_args(*args, **kwargs)
401 input_tensor, indices = args[0], args[1]
402 local_input = input_tensor.to_local() if hasattr(input_tensor, "_layout") else input_tensor
403 local_indices = indices.to_local()
404 local_args = (local_input, local_indices)
405 local_kwargs = {}
406 cache_values = [
407 input_tensor.layout if hasattr(input_tensor, "_layout") else None,
408 indices.layout,
409 input_tensor.shape,
410 indices.shape,
411 ]
412 return local_args, local_kwargs, cache_values
414 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
415 """
416 Infer output layout for GatherNd.
418 Rules:
419 1. Input and indices must not have Partial status.
420 2. cache_values must contain [input_layout_or_None, indices_layout, input_shape, indices_shape].
421 3. indices[-1] (K) must be replicated.
422 4. input indexed dims [0:K) must be replicated when input layout is provided.
423 5. Output inherits indices[:-1] sharding plus input trailing dims input[K:].
425 For GatherNd: out.shape = indices.shape[:-1] + input_x.shape[K:], where K = indices.shape[-1].
427 This implementation:
428 - Inherits sharding from indices[:-1].
429 - Allows sharding on input_x trailing dims input_x[K:].
430 - Requires input_x[:K] to be replicated ("None") if input_layout is provided.
431 - Requires indices[-1] (K dim) to be replicated ("None").
433 Output Layout:
434 output_tensor_map = indices_tensor_map[:-1] + input_tensor_map[K:]
435 If input_layout is None, input trailing dims are treated as replicated ("None").
437 Args:
438 cache_values (list): [input_layout_or_None, indices_layout, input_shape, indices_shape].
440 Returns:
441 tuple: ((output_layout,), None)
443 Raises:
444 ValueError: If input layouts, tensor maps, or shapes violate the rules above.
445 """
446 input_layout, indices_layout = self._parse_input_layouts(cache_values[:2])
447 if not self._allow_partial_inputs:
448 self._check_partial_inputs([input_layout, indices_layout])
450 input_shape, indices_shape = self._get_input_shapes(cache_values[2:])
451 k, trail_rank = self._get_k_and_trailing_rank(input_shape, indices_shape)
453 input_tensor_map, indices_tensor_map = self._validate_tensor_maps(
454 input_layout, indices_layout, k
455 )
457 # Output sharding: inherit indices[:-1] + input_x[K:].
458 if input_tensor_map is None:
459 output_tensor_map = tuple(indices_tensor_map[:-1]) + ("None",) * trail_rank
460 else:
461 output_tensor_map = tuple(indices_tensor_map[:-1]) + tuple(input_tensor_map[k:])
463 output_layout = Layout(
464 mesh_shape=indices_layout.mesh_shape,
465 alias_name=indices_layout.alias_name,
466 rank_list=indices_layout.rank_list,
467 )
469 if output_tensor_map:
470 output_layout = output_layout(*output_tensor_map)
471 else:
472 output_layout = output_layout("None")
474 return ((output_layout,), None)
476 def _parse_input_layouts(self, layouts):
477 """Parse and validate input layouts."""
478 if len(layouts) < 2:
479 raise ValueError(
480 f"For {self.op_name}, requires at least 2 input layouts, but got {len(layouts)}"
481 )
483 input_layout, indices_layout = layouts[0], layouts[1]
485 # Extra inputs are allowed only when they are non-tensor args (layout is None).
486 for extra_layout in layouts[2:]:
487 if extra_layout is not None:
488 raise ValueError(
489 f"For {self.op_name}, only supports 2 tensor inputs, but got extra tensor layout: "
490 f"{extra_layout}"
491 )
493 # For GatherNd: input_layout can be None (treated as fully replicated), but indices_layout must exist.
494 if indices_layout is None or not hasattr(indices_layout, "alias_tensor_map"):
495 raise ValueError(f"For {self.op_name}, indices layout cannot be None")
497 return input_layout, indices_layout
499 def _validate_tensor_maps(self, input_layout, indices_layout, k):
500 """Validate tensor maps constraints for GatherNd."""
501 indices_tensor_map = indices_layout.alias_tensor_map
503 # Validate: indices tensor_map must exist and last dimension cannot be split.
504 if not indices_tensor_map:
505 raise ValueError(f"For {self.op_name}, indices tensor_map cannot be empty")
507 last_axis = indices_tensor_map[-1]
508 if not self._is_none_axis(last_axis):
509 raise ValueError(
510 f"For {self.op_name}, the last dimension of indices cannot be split. "
511 f"Got indices[-1] = {last_axis}"
512 )
514 # Validate input only when layout is provided.
515 input_tensor_map = None
516 if input_layout is not None:
517 input_tensor_map = input_layout.alias_tensor_map
519 if k > len(input_tensor_map):
520 raise ValueError(
521 f"For {self.op_name}, indices last dim (K={k}) is larger than input rank "
522 f"({len(input_tensor_map)})"
523 )
525 # Indexed dims [0:K) must be replicated.
526 for axis_name in input_tensor_map[:k]:
527 if not self._is_none_axis(axis_name):
528 raise ValueError(
529 f"For {self.op_name}, input_x cannot be split on indexed dims [0:{k}). "
530 f"These dims must be 'None', but got tensor_map: {input_tensor_map}"
531 )
533 return input_tensor_map, indices_tensor_map
535 def _get_input_shapes(self, shape_values):
536 """Get input and indices shapes from cache values."""
537 input_shapes = None
538 if shape_values and len(shape_values) == 2:
539 input_shapes = shape_values
541 if input_shapes is None:
542 raise ValueError(
543 f"For {self.op_name}, missing input_shapes in cache_values."
544 )
546 input_shape = input_shapes[0]
547 indices_shape = input_shapes[1]
548 if input_shape is None or indices_shape is None:
549 raise ValueError(f"For {self.op_name}, input_shapes contains None: {input_shapes}")
551 input_shape = self._normalize_shape(input_shape, "input")
552 indices_shape = self._normalize_shape(indices_shape, "indices")
554 if len(indices_shape) < 1:
555 raise ValueError(f"For {self.op_name}, indices shape invalid: {indices_shape}")
557 return input_shape, indices_shape
559 def _normalize_shape(self, shape, name):
560 """Normalize shape-like object to tuple of int."""
561 try:
562 norm = tuple(shape)
563 except TypeError as err:
564 raise ValueError(f"For {self.op_name}, {name} shape is not iterable: {shape}") from err
566 try:
567 norm = tuple(int(dim) for dim in norm)
568 except (TypeError, ValueError) as err:
569 raise ValueError(f"For {self.op_name}, {name} shape contains non-integer dims: {norm}") from err
571 return norm
573 def _get_k_and_trailing_rank(self, input_shape, indices_shape):
574 """Compute K and trailing rank = len(input_shape) - K, where K is indices_shape[-1]."""
575 k = indices_shape[-1]
576 try:
577 k = int(k)
578 except (TypeError, ValueError) as err:
579 raise ValueError(f"For {self.op_name}, indices last dim (K) is invalid: {k}") from err
581 if k <= 0:
582 raise ValueError(f"For {self.op_name}, indices last dim (K) must be positive, but got {k}")
584 trail_rank = len(input_shape) - k
585 if trail_rank < 0:
586 raise ValueError(
587 f"For {self.op_name}, indices last dim (K={k}) is larger than input rank ({len(input_shape)})"
588 )
590 return k, trail_rank
592 def _is_none_axis(self, axis_name):
593 """
594 Check if an axis name represents no sharding.
595 """
596 if axis_name == "None":
597 return True
599 if isinstance(axis_name, tuple):
600 return all(name == "None" for name in axis_name)
602 return False