Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_reshape.py: 83%
180 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 Reshape operator.
17"""
19from typing import Callable, Optional, Tuple
21import torch
23from hyper_parallel.core.dtensor.layout import Layout
24from .parallel_ops import DistributedOp
27# Preserve Torch keyword names for calls forwarded by __torch_function__.
28# pylint: disable-next=redefined-builtin
29def _normalize_reshape_args(input, *shape, **kwargs):
30 """Normalize reshape/view arguments into positional args and empty kwargs."""
31 unexpected_kwargs = set(kwargs) - {'shape', 'size'}
32 if unexpected_kwargs:
33 unexpected = next(iter(unexpected_kwargs))
34 raise TypeError(f"reshape got an unexpected keyword argument '{unexpected}'.")
35 if len(kwargs) > 1 or (shape and kwargs):
36 raise TypeError("reshape got shape from both args and kwargs.")
37 if not shape and kwargs:
38 shape = (next(iter(kwargs.values())),)
39 if not shape:
40 raise TypeError("reshape missing required shape argument.")
41 return (input,) + shape, {}
44def _filter_none_split_tensor_map(tensor_map, mesh_shape):
45 """
46 Filter out the elements in tensor_map where the size of the corresponding dimension in device_matrix is 1.
48 Args:
49 tensor_map (list): A list of tensor mappings, which may contain integers or tuples.
50 device_matrix (list): A device matrix representing the device distribution across each dimension.
52 Returns:
53 list: The filtered list of tensor mappings, where invalid mappings are replaced with -1 or valid mappings are
54 retained.
55 """
56 filtered_tensor_map = []
57 for item in tensor_map:
58 if isinstance(item, tuple):
59 filtered = []
60 for i in item:
61 if mesh_shape[-1 - i] != 1:
62 filtered.append(i)
63 if len(filtered) == 0:
64 filtered_tensor_map.append(-1)
65 elif len(filtered) == 1:
66 filtered_tensor_map.append(filtered[0])
67 else:
68 filtered_tensor_map.append(tuple(filtered))
69 else:
70 filtered_tensor_map.append(item if mesh_shape[-1 - item] != 1 else -1)
71 return filtered_tensor_map
74class ReshapeDistributedOp(DistributedOp):
75 """Distributed implementation for Reshape operator."""
77 def __init__(self, op_name):
78 super().__init__(op_name)
79 self._allow_partial_inputs = True
81 def _get_dynamic_shape_info(self, shape):
82 total_size = 1
83 dynamic_axis = -1
84 for axis, s in enumerate(shape):
85 total_size *= s
86 if s < 0:
87 dynamic_axis = axis
88 return total_size < 0, dynamic_axis, total_size
90 def _handle_dynamic_shape(self, input_shape, output_shape):
91 """
92 Check dynamic shape. Calculate unknown axis if one of input and output shape is known. If both are unknown,
93 calculate the relative multiple.
94 [2, -1, 8], [4, -1, 8] -> [2, -2, 8], [4, -1, 8]
95 """
96 input_shape = list(input_shape)
97 output_shape = list(output_shape)
98 is_input_dynamic, input_dynamic_axis, input_total_size = self._get_dynamic_shape_info(input_shape)
99 is_output_dynamic, output_dynamic_axis, output_total_size = self._get_dynamic_shape_info(output_shape)
100 dynamic_can_shard = False
101 if not is_input_dynamic and not is_output_dynamic:
102 if input_total_size != output_total_size:
103 raise ValueError(f"The total elements number of input shape {input_shape} and output shape "
104 f"{output_shape} are different.")
105 return input_shape, output_shape, dynamic_can_shard
107 if not is_input_dynamic:
108 accurate_output_shape = output_shape
109 accurate_output_shape[output_dynamic_axis] = -input_total_size // output_total_size
110 return input_shape, accurate_output_shape, dynamic_can_shard
112 if not is_output_dynamic:
113 accurate_input_shape = input_shape
114 accurate_input_shape[input_dynamic_axis] = -output_total_size // input_total_size
115 return accurate_input_shape, output_shape, dynamic_can_shard
117 if output_total_size >= input_total_size:
118 output_shape[output_dynamic_axis] = -(input_total_size // output_total_size)
119 dynamic_can_shard = True
120 else:
121 input_shape[input_dynamic_axis] = -(output_total_size // input_total_size)
122 return input_shape, output_shape, dynamic_can_shard
124 def _merge_unshared_axis(self, global_shape, tensor_map):
125 """
126 Merge those axes that are not sharded to the high dimension which is shared.
127 shape[4, 2, 6, 8], tensor map[-1, -1, 0, -1] -> merged shape[8, 48]
129 Returns:
130 tuple: (merged_shape, merge_tensor_map).
131 merge_tensor_map may contain -1 for merged unsharded axis groups.
132 """
133 merged_size = 1
134 merged_shape = []
135 merged_tensor_map = []
136 for axis in range(len(global_shape) - 1, -1, -1):
137 merged_size *= global_shape[axis]
138 if tensor_map[axis] != -1:
139 merged_shape.insert(0, merged_size)
140 merged_tensor_map.insert(0, tensor_map[axis])
141 merged_size = 1
142 if tensor_map[0] == -1:
143 merged_shape.insert(0, merged_size)
144 merged_tensor_map.insert(0, -1)
145 return merged_shape, merged_tensor_map
148 def _cal_output_layout_and_dst_shape(self, output_tensor_map, dst_shape, x_dict):
149 """
150 calculate output layout tensor map and local dst shape.
151 """
152 x_mesh_shape = x_dict["mesh_shape"]
153 output_map = []
154 local_dst_shape = []
155 for idx, map_id in enumerate(output_tensor_map):
156 if isinstance(map_id, tuple):
157 shard_size = 1
158 map_idx = []
159 for shard_id in map_id:
160 map_idx.append(x_dict["alias_name"][-1 - shard_id])
161 shard_size *= x_mesh_shape[-1 - shard_id]
162 output_map.append(tuple(map_idx))
163 local_dst_shape.append(dst_shape[idx] // shard_size if dst_shape[idx] > 0 else -1)
164 continue
165 if map_id < 0:
166 output_map.append("None")
167 local_dst_shape.append(dst_shape[idx] if dst_shape[idx] > 0 else -1)
168 else:
169 output_map.append(x_dict["alias_name"][-1 - map_id])
170 local_dst_shape.append(dst_shape[idx] // x_mesh_shape[-1 - map_id] if dst_shape[idx] > 0 else -1)
171 return output_map, local_dst_shape
173 def _normalize_shape(self, dst_shape):
174 """Normalize dst_shape to list format."""
175 if isinstance(dst_shape, torch.Tensor):
176 dst_shape = dst_shape.tolist()
177 if not isinstance(dst_shape, (list, tuple)):
178 raise ValueError("Shape should be a tensor or a tuple or a list.")
179 return dst_shape
181 def _compute_output_tensor_map(self, merged_shape, merge_tensor_map, dst_shape, x_mesh_shape, dynamic_can_shard,
182 input_shape, x_map):
183 """Compute output tensor_map from merged information.
185 Args:
186 merged_shape: Merged shape from _merge_unshared_axis
187 merge_tensor_map: Merged tensor_map from _merge_unshared_axis
188 dst_shape: Target shape
189 x_mesh_shape: Mesh shape
190 dynamic_can_shard: Whether dynamic shape can be sharded
191 input_shape: Original input shape
192 x_map: Input tensor_map
194 Returns:
195 list: Output tensor_map
196 """
197 output_tensor_map = []
198 cur_axis = len(merged_shape) - 1
199 cur_size = merged_shape[cur_axis]
201 for shape in reversed(dst_shape):
202 if cur_size % shape != 0:
203 raise ValueError(f"Can not reshape {input_shape} to {dst_shape} with tensor map {x_map}")
204 cur_size = cur_size // shape
206 if cur_size == 1:
207 map_val = merge_tensor_map[cur_axis]
208 if map_val != -1:
209 self._validate_reshape_shard(
210 map_val, x_mesh_shape, shape,
211 dynamic_can_shard, input_shape, x_map, dst_shape
212 )
213 output_tensor_map.insert(0, map_val)
214 cur_axis -= 1
215 cur_size = merged_shape[cur_axis]
216 else:
217 output_tensor_map.insert(0, -1)
219 return output_tensor_map
221 def _validate_reshape_shard(self, map_val, x_mesh_shape, shape,
222 dynamic_can_shard, input_shape, x_map, dst_shape):
223 """Validate that a sharded axis can be reshaped to the target shape dimension."""
224 if isinstance(map_val, tuple):
225 shard_size = 1
226 for axis in map_val:
227 shard_size *= x_mesh_shape[-axis - 1]
228 else:
229 shard_size = x_mesh_shape[-map_val - 1]
231 if shape < 0:
232 if not dynamic_can_shard:
233 raise ValueError(f"Can not reshape {input_shape} to {dst_shape} with tensor map {x_map}")
234 elif shard_size > shape or shape % shard_size != 0:
235 raise ValueError(f"Can not reshape {input_shape} to {dst_shape} with tensor map {x_map}")
237 def _apply_partial_status(self, x_layout, out_layout):
238 """Apply partial status from input to output layout."""
239 if x_layout.is_partial():
240 input_partial = x_layout.partial
241 for i, partial_op in enumerate(input_partial):
242 if partial_op is not None and i < len(out_layout.alias_name):
243 out_layout.set_partial_by_dev_axis(out_layout.alias_name[i], partial_op)
245 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
246 """
247 Preprocess arguments for Reshape operator.
249 Args:
250 args (tuple): Input tensor followed by target shape arguments.
251 kwargs (dict): Keyword arguments.
253 Returns:
254 tuple: (local_args, local_kwargs, cache_values)
255 """
256 args, _ = _normalize_reshape_args(*args, **kwargs)
257 input_tensor = args[0]
258 dst_shape = args[1:] if len(args) > 2 else args[1]
260 local_args = (input_tensor.to_local(), dst_shape)
261 local_kwargs = {}
262 cache_values = [input_tensor.layout, dst_shape, tuple(input_tensor.shape)]
263 return local_args, local_kwargs, cache_values
265 def _infer_reshape_layout(self, x_layout, dst_shape, input_shape):
266 """Infer reshape output layout and local destination shape."""
267 x_dict = x_layout.to_dict()
268 dst_shape = self._normalize_shape(dst_shape)
270 x_map = _filter_none_split_tensor_map(x_dict["tensor_map"], x_dict["mesh_shape"])
271 x_mesh_shape = x_dict["mesh_shape"]
273 input_shape, dst_shape, dynamic_can_shard = self._handle_dynamic_shape(input_shape, dst_shape)
274 merged_shape, merge_tensor_map = self._merge_unshared_axis(input_shape, x_map)
276 output_tensor_map = self._compute_output_tensor_map(
277 merged_shape, merge_tensor_map, dst_shape, x_mesh_shape, dynamic_can_shard, input_shape, x_map
278 )
280 output_layout = Layout(
281 mesh_shape=x_mesh_shape,
282 alias_name=x_layout.alias_name,
283 rank_list=x_layout.rank_list
284 )
285 output_map, local_dst_shape = self._cal_output_layout_and_dst_shape(output_tensor_map, dst_shape, x_dict)
286 out_layout = output_layout(*output_map)
288 self._apply_partial_status(x_layout, out_layout)
290 return out_layout, local_dst_shape
292 def infer_layout(self, cache_values: list) -> Tuple[tuple, list]: # pylint: disable=W0221
293 """
294 Infer output layout for Reshape operator.
296 Rules:
297 1. Partial input is allowed and preserved on the output layout.
298 2. Target shape must be a Tensor, tuple, or list.
299 3. Input and output total element counts must match after resolving one dynamic axis.
300 4. Reshape must preserve each device's local data slice; sharded axes can only be
301 split or merged when the shard boundary remains valid.
302 5. Output Partial status follows the input Partial status.
304 Args:
305 cache_values (list): [input_layout, dst_shape, input_shape].
307 Returns:
308 tuple: ((output_layout,), local_dst_shape)
310 Raises:
311 ValueError: If target shape is invalid or the reshape would change sharded slices.
312 """
313 if len(cache_values) != 3:
314 raise ValueError(
315 f"For {self.op_name}, cache_values length should be 3, but got {len(cache_values)}"
316 )
318 x_layout, dst_shape, input_shape = cache_values[0], cache_values[1], cache_values[2]
319 if x_layout is None:
320 raise ValueError(f"For {self.op_name}, reshape requires a valid input tensor layout.")
322 out_layout, local_dst_shape = self._infer_reshape_layout(x_layout, dst_shape, input_shape)
323 return ((out_layout,), local_dst_shape)
325 def get_expand_impl(self, func: Optional[Callable], infer_result: tuple, # pylint: disable=W0221
326 cache_values: list) -> Optional[Callable]:
327 """Return a closure that calls reshape/view with the inferred local target shape."""
328 del cache_values
329 if func is None:
330 return None
332 local_dst_shape = infer_result[1]
333 if local_dst_shape is None:
334 return None
336 def expand_impl(x: object, shape: object) -> object:
337 del shape
338 return func(x, local_dst_shape)
340 return expand_impl