Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_scatter.py: 98%
49 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 Scatter operator.
17"""
19from typing import Tuple
21from .parallel_ops import DistributedOp
24# Preserve Torch keyword names for calls forwarded by __torch_function__.
25# pylint: disable-next=redefined-builtin
26def _normalize_scatter_args(input, dim, index, src=None, *, value=None, reduce=None):
27 """Canonicalize tensor-src and scalar-value scatter overloads."""
28 if value is not None:
29 if src is not None:
30 raise TypeError("scatter received both src and value.")
31 src = value
32 kwargs = {} if reduce is None else {'reduce': reduce}
33 return (input, dim, index, src), kwargs
36class ScatterDistributedOp(DistributedOp):
37 """Distributed implementation for torch.scatter."""
39 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
40 """
41 Preprocess arguments for Scatter operator.
43 Args:
44 args (tuple): Input arguments (input, dim, index, src).
45 kwargs (dict): Keyword arguments (unused for scatter).
47 Returns:
48 tuple: (local_args, local_kwargs, cache_values) where local_args contains
49 local tensors and cache_values contains layouts plus dim.
50 """
51 args, kwargs = _normalize_scatter_args(*args, **kwargs)
52 input_tensor, dim, index_tensor, src = args
54 input_local = input_tensor.to_local()
55 index_local = index_tensor.to_local() if hasattr(index_tensor, '_layout') else index_tensor
56 src_local = src.to_local() if hasattr(src, '_layout') else src
57 local_args = (input_local, dim, index_local, src_local)
58 local_kwargs = kwargs
60 cache_values = [
61 input_tensor.layout,
62 dim,
63 index_tensor.layout if hasattr(index_tensor, '_layout') else None,
64 src.layout if hasattr(src, '_layout') else None,
65 ]
66 return local_args, local_kwargs, cache_values
68 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
69 """
70 Infer output layout for Scatter operator.
72 Rules:
73 1. Input must not have Partial status.
74 2. Input must be a DTensor with a valid layout.
75 3. dim must be an integer within the valid range [-ndim, ndim-1].
76 4. The scatter dimension must be replicated (not sharded).
77 5. Index layout must match input layout (if index is a DTensor).
78 6. Src layout must match input layout (if src is a DTensor).
79 7. Output layout is identical to input layout.
81 Args:
82 cache_values (list): [input_layout, dim, index_layout, src_layout]
83 where index_layout and src_layout may be None.
85 Returns:
86 tuple: ((output_layout,), None)
88 Raises:
89 ValueError: If any rule above is violated.
90 """
91 if not self._allow_partial_inputs:
92 self._check_partial_inputs([cache_values[0]])
94 input_layout = cache_values[0]
95 if input_layout is None:
96 raise ValueError(
97 f"For {self.op_name}, input should be a DTensor with a valid layout, "
98 f"but got None."
99 )
101 dim = cache_values[1]
102 if not isinstance(dim, int):
103 raise ValueError(
104 f"For {self.op_name}, dim should be an integer, "
105 f"but got {type(dim)}."
106 )
108 alias_map = input_layout.alias_tensor_map
109 ndim = len(alias_map)
111 if dim < 0:
112 dim += ndim
114 if dim < 0 or dim >= ndim:
115 raise ValueError(
116 f"For {self.op_name}, dim should be in range [{-ndim}, {ndim - 1}], "
117 f"but got {cache_values[1]}."
118 )
120 # Scatter dimension must be replicated
121 dim_alias = alias_map[dim]
122 if dim_alias != "None":
123 raise ValueError(
124 f"For {self.op_name}, scatter dim should be replicated, "
125 f"but dim {cache_values[1]} is mapped to {dim_alias}."
126 )
128 # Index layout must match input layout
129 index_layout = cache_values[2]
130 if index_layout is not None:
131 index_alias = index_layout.alias_tensor_map
132 if index_alias != alias_map:
133 raise ValueError(
134 f"For {self.op_name}, index layout should match input layout, "
135 f"but got {index_alias} vs {alias_map}."
136 )
138 # Src layout must match input layout
139 src_layout = cache_values[3]
140 if src_layout is not None:
141 src_alias = src_layout.alias_tensor_map
142 if src_alias != alias_map:
143 raise ValueError(
144 f"For {self.op_name}, src layout should match input layout, "
145 f"but got {src_alias} vs {alias_map}."
146 )
148 return ((input_layout,), None)