Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_expand.py: 91%
120 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 Expand operator.
17"""
19from typing import Callable, Optional, Tuple
21from hyper_parallel.core.dtensor.layout import Layout
22from .parallel_ops import DistributedOp
25def _normalize_expand_args(input_tensor, *sizes, size=None, implicit=False):
26 if size is not None:
27 if sizes:
28 raise TypeError("expand got size from both args and kwargs.")
29 sizes = (size,)
30 if len(sizes) == 1 and isinstance(sizes[0], (tuple, list)):
31 sizes = tuple(sizes[0])
32 return (input_tensor, *sizes), {'implicit': implicit}
35def _normalize_expand_as_args(input_tensor, other):
36 return (input_tensor, other), {}
39class ExpandDistributedOp(DistributedOp):
40 """Distributed implementation for torch.Tensor.expand."""
42 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
43 """
44 Preprocess arguments for Expand operator.
46 Args:
47 args (tuple): Input arguments (input_tensor, *sizes).
48 kwargs (dict): Optional size and implicit arguments.
50 Returns:
51 tuple: (local_args, local_kwargs, cache_values)
52 """
53 args, kwargs = _normalize_expand_args(*args, **kwargs)
54 input_tensor = args[0]
55 sizes = tuple(args[1:])
56 local_args = (input_tensor.to_local(), *sizes)
57 cache_values = [input_tensor.layout, input_tensor.shape, sizes]
58 return local_args, kwargs, cache_values
60 @staticmethod
61 def _validate_input_layouts(
62 cache_values: list,
63 op_name: str,
64 ) -> Tuple[Layout, tuple, tuple, int]:
65 """Validate all inputs for expand layout inference.
67 Performs type checks, shape validation, sizes validation,
68 and dimension compatibility checks.
70 Rules:
71 1. input_shape and sizes must be tuples of positive ints.
72 2. Cannot reduce dimensions (output_ndim < input_ndim).
73 3. -1 cannot be used for new (prepended) dimensions.
75 Args:
76 cache_values: [input_layout, input_shape, sizes]
77 op_name: Operator name for error messages.
79 Returns:
80 tuple: (input_layout, input_shape, sizes, num_new_dims)
82 Raises:
83 ValueError: If any validation rule is violated.
84 """
85 if not cache_values:
86 raise ValueError(
87 f"For {op_name}, cache_values should contain input layout, "
88 f"but got empty cache_values."
89 )
90 input_layout = cache_values[0]
92 if not isinstance(input_layout, Layout):
93 raise ValueError(
94 f"For {op_name}, input layout should be a Layout, "
95 f"but got {type(input_layout)}."
96 )
98 input_shape = cache_values[1] if len(cache_values) > 1 else None
99 if not isinstance(input_shape, tuple):
100 raise ValueError(
101 f"For {op_name}, input_shape should be a tuple, "
102 f"but got {type(input_shape)}."
103 )
105 sizes = cache_values[2] if len(cache_values) > 2 else None
106 if sizes is None or len(sizes) < 1:
107 raise ValueError(
108 f"For {op_name}, sizes should be a non-empty tuple of ints, "
109 f"but got {sizes}."
110 )
111 for i, sz in enumerate(sizes):
112 if not isinstance(sz, int):
113 raise ValueError(
114 f"For {op_name}, elements in sizes should be int, "
115 f"but got {type(sz)} at position {i}."
116 )
118 in_alias_map = input_layout.alias_tensor_map
119 input_ndim = len(in_alias_map)
120 output_ndim = len(sizes)
121 num_new_dims = output_ndim - input_ndim
123 if len(input_shape) != input_ndim:
124 raise ValueError(
125 f"For {op_name}, input_shape length ({len(input_shape)}) "
126 f"must match input_ndim ({input_ndim})."
127 )
129 if num_new_dims < 0:
130 raise ValueError(
131 f"For {op_name}, cannot reduce dimensions with expand, "
132 f"input has {input_ndim} dims but requested {output_ndim} dims."
133 )
135 # New dimensions cannot use -1
136 for i in range(num_new_dims):
137 if sizes[i] == -1:
138 raise ValueError(
139 f"For {op_name}, cannot use -1 for new dimension at position {i}, "
140 f"sizes should be positive integers."
141 )
143 return input_layout, input_shape, sizes, num_new_dims
145 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
146 """
147 Infer output layout for torch.Tensor.expand.
149 Rules:
150 1. Input must not have Partial status.
151 2. input_shape and sizes must be tuples of positive ints.
152 3. Cannot reduce dimensions (output_ndim < input_ndim).
153 4. -1 cannot be used for new (prepended) dimensions.
154 5. Same-size dimension: preserve original sharding.
155 6. True broadcast (1 → N): the input dimension must be replicated.
156 7. New dimensions are replicated.
158 Args:
159 cache_values (list): [input_layout, input_shape, sizes]
161 Returns:
162 tuple: ((output_layout,), None)
164 Raises:
165 ValueError: If any rule above is violated.
166 """
167 if not self._allow_partial_inputs and cache_values:
168 self._check_partial_inputs([cache_values[0]])
170 input_layout, input_shape, sizes, num_new_dims = self._validate_input_layouts(
171 cache_values, self.op_name
172 )
174 in_alias_map = input_layout.alias_tensor_map
175 input_ndim = len(in_alias_map)
177 output_map = []
179 # New dimensions: always replicated
180 for _ in range(num_new_dims):
181 output_map.append("None")
183 # Process existing dimensions
184 for i in range(input_ndim):
185 output_dim_idx = num_new_dims + i
186 requested_size = sizes[output_dim_idx]
187 input_size = input_shape[i]
189 if requested_size in (-1, input_size):
190 # Dimension unchanged — preserve original sharding
191 output_map.append(in_alias_map[i])
192 elif input_size == 1 and requested_size > 1:
193 # True broadcast: 1 → N — must be replicated
194 if in_alias_map[i] != "None":
195 raise ValueError(
196 f"For {self.op_name}, cannot expand dimension {i} "
197 f"which is sharded "
198 f"(size {input_size} → {requested_size}), "
199 f"got mapping {in_alias_map[i]}."
200 )
201 output_map.append("None")
202 else:
203 raise ValueError(
204 f"For {self.op_name}, cannot expand dimension {i} "
205 f"from size {input_size} to {requested_size}."
206 )
208 output_layout = Layout(
209 mesh_shape=input_layout.mesh_shape,
210 alias_name=input_layout.alias_name,
211 rank_list=input_layout.rank_list
212 )
213 output_layout = output_layout(*output_map)
214 return ((output_layout,), None)
216 @staticmethod
217 def get_expand_impl(
218 func: Optional[Callable], infer_result: tuple, cache_values: list,
219 ) -> Optional[Callable]:
220 """Keep preserved sharded dimensions at their local sizes.
222 Explicit expand sizes describe the global tensor. In dimensions whose
223 layout is preserved, -1 lets Torch retain each rank's local extent.
225 Args:
226 func: Native expand callable.
227 infer_result: Output layouts and unused extra information.
228 cache_values: Input layout, global input shape and requested sizes.
230 Returns:
231 Local expand callable, or None when sizes need no adjustment.
232 """
233 sizes = cache_values[2]
234 output_layout = infer_result[0][0]
235 local_sizes = tuple(
236 -1 if mapping != "None" else size
237 for mapping, size in zip(output_layout.alias_tensor_map, sizes)
238 )
239 if local_sizes == tuple(sizes):
240 return None
242 def _expand_impl(input_tensor, *_sizes, **kwargs):
243 return func(input_tensor, *local_sizes, **kwargs)
245 return _expand_impl
248class ExpandAsDistributedOp(DistributedOp):
249 """Distributed implementation for torch.Tensor.expand_as."""
251 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
252 """
253 Preprocess arguments for ExpandAs operator.
255 Args:
256 args (tuple): Input arguments (input_tensor, target_tensor).
257 kwargs (dict): Keyword arguments (none for expand_as).
259 Returns:
260 tuple: (local_args, local_kwargs, cache_values)
261 """
262 args, kwargs = _normalize_expand_as_args(*args, **kwargs)
263 input_tensor = args[0]
264 target_tensor = args[1]
265 local_args = (input_tensor.to_local(), target_tensor.to_local())
266 cache_values = [input_tensor.layout, input_tensor.shape, target_tensor.shape]
267 return local_args, {}, cache_values
269 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
270 """
271 Infer output layout for expand_as.
273 Rules:
274 1. Input must not have Partial status.
275 2. target_shape must have at least as many dims as input_global_shape.
276 3. Matching-size dimensions preserve input sharding.
277 4. Singleton (size 1) dimensions being expanded to >1 must be unsharded in input.
278 5. Non-singleton dimensions must match exactly.
280 Args:
281 cache_values (list): [input_layout, input_global_shape, target_shape]
283 Returns:
284 tuple: ((output_layout,), None)
286 Raises:
287 ValueError: If any rule above is violated.
288 """
289 if not cache_values:
290 raise ValueError(
291 f"For {self.op_name}, cache_values should contain input layout, "
292 f"but got empty cache_values."
293 )
294 input_layout = cache_values[0]
295 if not self._allow_partial_inputs:
296 self._check_partial_inputs([input_layout])
298 in_alias_map = input_layout.alias_tensor_map
299 input_global_shape = cache_values[1]
300 target_shape = cache_values[2]
302 if not isinstance(target_shape, tuple):
303 raise ValueError(
304 f"For {self.op_name}, target_shape should be tuple, "
305 f"but got {type(target_shape)}."
306 )
307 if not isinstance(input_global_shape, tuple):
308 raise ValueError(
309 f"For {self.op_name}, input_global_shape should be tuple, "
310 f"but got {type(input_global_shape)}."
311 )
313 if len(target_shape) < len(in_alias_map):
314 raise ValueError(
315 f"For {self.op_name}, target shape {target_shape} (ndim={len(target_shape)}) "
316 f"cannot be smaller than input shape {input_global_shape} (ndim={len(in_alias_map)})."
317 )
319 # Align dimensions: right-align input to target shape
320 num_leading_implicit = len(target_shape) - len(in_alias_map)
321 aligned_input_shape = (1,) * num_leading_implicit + input_global_shape
322 aligned_tensor_map = ("None",) * num_leading_implicit + in_alias_map
324 # Validate expansion rules and build output tensor_map
325 output_tensor_map = []
326 for i, (in_size, tgt_size, shard_spec) in enumerate(
327 zip(aligned_input_shape, target_shape, aligned_tensor_map)
328 ):
329 if in_size == tgt_size:
330 # Dimension unchanged - preserve sharding pattern
331 output_tensor_map.append(shard_spec)
332 elif in_size == 1 and tgt_size > 1:
333 # Dimension is expanded (broadcast) - must be unsharded
334 if shard_spec != "None":
335 raise ValueError(
336 f"For {self.op_name}, cannot expand sharded dimension {i} "
337 f"which is going to broadcast (global size 1 -> {tgt_size}), "
338 f"got mapping {shard_spec}."
339 )
340 output_tensor_map.append("None")
341 else:
342 raise ValueError(
343 f"For {self.op_name}, cannot expand dimension {i} from size "
344 f"{in_size} to {tgt_size}."
345 )
347 output_layout = Layout(
348 mesh_shape=input_layout.mesh_shape,
349 alias_name=input_layout.alias_name,
350 rank_list=input_layout.rank_list
351 )
352 output_layout = output_layout(*output_tensor_map)
353 return ((output_layout,), None)