Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_split.py: 62%
173 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 Split operator.
17"""
19import copy
20import math
21from typing import Tuple
23from .parallel_ops import DistributedOp
26def _normalize_split_with_size_args(x, split_sections, dim):
27 return (x, split_sections, dim), {}
30def _normalize_split_args(tensor, split_size_or_sections, dim=0):
31 return (tensor, split_size_or_sections, dim), {}
34def _normalize_split_tensor_args(x, split_size, dim):
35 return (x, split_size, dim), {}
38# Preserve Torch keyword names for calls forwarded by __torch_function__.
39# pylint: disable-next=redefined-builtin
40def _normalize_tensor_split_args(input, indices_or_sections=None, dim=0, *,
41 sections=None, indices=None, tensor_indices_or_sections=None):
42 """Accept the keyword names of torch.tensor_split's three overloads."""
43 split_args = [value for value in (indices_or_sections, sections, indices, tensor_indices_or_sections)
44 if value is not None]
45 if len(split_args) != 1:
46 raise TypeError("tensor_split requires exactly one indices or sections argument.")
47 indices_or_sections = split_args[0]
48 return (input, indices_or_sections, dim), {}
51class SplitWithSizeDistributedOp(DistributedOp):
52 """Distributed implementation for SplitWithSize operator."""
54 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
55 """
56 Preprocess arguments for SplitWithSize operator.
58 Args:
59 args (tuple): Input arguments (input, split_sections, dim).
60 kwargs (dict): Keyword arguments (empty for this operator).
62 Returns:
63 tuple: (local_args, local_kwargs, cache_values)
64 """
65 args, kwargs = _normalize_split_with_size_args(*args, **kwargs)
66 input_tensor, split_sections, dim = args
67 output_num = len(split_sections)
68 local_args = (input_tensor.to_local(), split_sections, dim)
69 local_kwargs = {}
70 cache_values = [input_tensor.layout, dim, output_num]
71 return local_args, local_kwargs, cache_values
73 # pylint: disable=W0237
74 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
75 """
76 Infer output layouts for SplitWithSize operator.
78 Rules:
79 1. Input must not have Partial status.
80 2. The split dimension must not be sharded.
82 Args:
83 cache_values (list): [input_layout, dim, output_num]
85 Returns:
86 tuple: ((output_layouts,), None)
88 Raises:
89 ValueError: If any rule above is violated.
90 """
91 layout = cache_values[0]
92 dim = cache_values[1]
93 output_num = cache_values[2]
95 if not self._allow_partial_inputs:
96 self._check_partial_inputs([layout])
98 in_tensor_map = layout.alias_tensor_map
99 ndim = len(in_tensor_map)
101 if dim < 0:
102 dim = ndim + dim
103 if not 0 <= dim < ndim:
104 raise ValueError(
105 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
106 f"but got {dim}."
107 )
109 if in_tensor_map[dim] != "None":
110 raise ValueError(
111 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
112 f"but got layout: {layout}."
113 )
115 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)
118class SplitWithSizeViewDistributedOp(DistributedOp):
119 """Distributed implementation for SplitWithSizeView operator."""
121 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
122 """
123 Preprocess arguments for SplitWithSizeView operator.
125 Args:
126 args (tuple): Input arguments (input, split_sections, dim).
127 kwargs (dict): Keyword arguments (empty for this operator).
129 Returns:
130 tuple: (local_args, local_kwargs, cache_values)
131 """
132 args, kwargs = _normalize_split_with_size_args(*args, **kwargs)
133 input_tensor, split_sections, dim = args
134 output_num = len(split_sections)
135 local_args = (input_tensor.to_local(), split_sections, dim)
136 local_kwargs = {}
137 cache_values = [input_tensor.layout, dim, output_num]
138 return local_args, local_kwargs, cache_values
140 # pylint: disable=W0237
141 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
142 """
143 Infer output layouts for SplitWithSizeView operator.
145 Rules:
146 1. Input must not have Partial status.
147 2. The split dimension must not be sharded.
149 Args:
150 cache_values (list): [input_layout, dim, output_num]
152 Returns:
153 tuple: ((output_layouts,), None)
155 Raises:
156 ValueError: If any rule above is violated.
157 """
158 layout = cache_values[0]
159 dim = cache_values[1]
160 output_num = cache_values[2]
162 if not self._allow_partial_inputs:
163 self._check_partial_inputs([layout])
165 in_tensor_map = layout.alias_tensor_map
166 ndim = len(in_tensor_map)
168 if dim < 0:
169 dim = ndim + dim
170 if not 0 <= dim < ndim:
171 raise ValueError(
172 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
173 f"but got {dim}."
174 )
176 if in_tensor_map[dim] != "None":
177 raise ValueError(
178 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
179 f"but got layout: {layout}."
180 )
182 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)
185class SplitDistributedOp(DistributedOp):
186 """Distributed implementation for the Split operator (torch.split)."""
188 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
189 """
190 Preprocess arguments for Split operator.
192 Args:
193 args (tuple): Input arguments (input, split_size_or_sections[, dim]).
194 kwargs (dict): Keyword arguments (may contain dim).
196 Returns:
197 tuple: (local_args, local_kwargs, cache_values)
198 """
199 args, kwargs = _normalize_split_args(*args, **kwargs)
200 input_tensor, split_size_or_sections, dim = args
202 if isinstance(split_size_or_sections, int):
203 output_num = math.ceil(input_tensor.shape[dim] / split_size_or_sections)
204 else:
205 output_num = len(split_size_or_sections)
207 local_args = (input_tensor.to_local(), split_size_or_sections, dim)
208 local_kwargs = {}
209 cache_values = [input_tensor.layout, dim, output_num]
210 return local_args, local_kwargs, cache_values
212 # pylint: disable=W0237
213 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
214 """
215 Infer output layouts for Split operator.
217 Rules:
218 1. Input must not have Partial status.
219 2. The split dimension must not be sharded.
220 3. dim must be within the valid range of input dimensions.
222 Args:
223 cache_values (list): [input_layout, dim, output_num]
225 Returns:
226 tuple: ((output_layouts,), None)
228 Raises:
229 ValueError: If any rule above is violated.
230 """
231 layout = cache_values[0]
232 dim = cache_values[1]
233 output_num = cache_values[2]
235 if not self._allow_partial_inputs:
236 self._check_partial_inputs([layout])
238 in_tensor_map = layout.alias_tensor_map
239 ndim = len(in_tensor_map)
241 if dim < 0:
242 dim = ndim + dim
243 if not 0 <= dim < ndim:
244 raise ValueError(
245 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
246 f"but got {dim}."
247 )
249 if in_tensor_map[dim] != "None":
250 raise ValueError(
251 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
252 f"but got layout: {layout}."
253 )
255 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)
258class SplitTensorDistributedOp(DistributedOp):
259 """Distributed implementation for SplitTensor operator."""
261 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
262 """
263 Preprocess arguments for SplitTensor operator.
265 Args:
266 args (tuple): Input arguments (input, split_size, dim).
267 kwargs (dict): Keyword arguments (empty for this operator).
269 Returns:
270 tuple: (local_args, local_kwargs, cache_values)
271 """
272 args, kwargs = _normalize_split_tensor_args(*args, **kwargs)
273 input_tensor, split_size, dim = args
274 output_num = math.ceil(input_tensor.shape[dim] / split_size)
275 local_args = (input_tensor.to_local(), split_size, dim)
276 local_kwargs = {}
277 cache_values = [input_tensor.layout, dim, output_num]
278 return local_args, local_kwargs, cache_values
280 # pylint: disable=W0237
281 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
282 """
283 Infer output layouts for SplitTensor operator.
285 Rules:
286 1. Input must not have Partial status.
287 2. The split dimension must not be sharded.
289 Args:
290 cache_values (list): [input_layout, dim, output_num]
292 Returns:
293 tuple: ((output_layouts,), None)
295 Raises:
296 ValueError: If any rule above is violated.
297 """
298 layout = cache_values[0]
299 dim = cache_values[1]
300 output_num = cache_values[2]
302 if not self._allow_partial_inputs:
303 self._check_partial_inputs([layout])
305 in_tensor_map = layout.alias_tensor_map
306 ndim = len(in_tensor_map)
308 if dim < 0:
309 dim = ndim + dim
310 if not 0 <= dim < ndim:
311 raise ValueError(
312 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
313 f"but got {dim}."
314 )
316 if in_tensor_map[dim] != "None":
317 raise ValueError(
318 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
319 f"but got layout: {layout}."
320 )
322 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)
325class SplitTensorViewDistributedOp(DistributedOp):
326 """Distributed implementation for SplitTensorView operator."""
328 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
329 """
330 Preprocess arguments for SplitTensorView operator.
332 Args:
333 args (tuple): Input arguments (input, split_size, dim).
334 kwargs (dict): Keyword arguments (empty for this operator).
336 Returns:
337 tuple: (local_args, local_kwargs, cache_values)
338 """
339 args, kwargs = _normalize_split_tensor_args(*args, **kwargs)
340 input_tensor, split_size, dim = args
341 output_num = math.ceil(input_tensor.shape[dim] / split_size)
342 local_args = (input_tensor.to_local(), split_size, dim)
343 local_kwargs = {}
344 cache_values = [input_tensor.layout, dim, output_num]
345 return local_args, local_kwargs, cache_values
347 # pylint: disable=W0237
348 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
349 """
350 Infer output layouts for SplitTensorView operator.
352 Rules:
353 1. Input must not have Partial status.
354 2. The split dimension must not be sharded.
356 Args:
357 cache_values (list): [input_layout, dim, output_num]
359 Returns:
360 tuple: ((output_layouts,), None)
362 Raises:
363 ValueError: If any rule above is violated.
364 """
365 layout = cache_values[0]
366 dim = cache_values[1]
367 output_num = cache_values[2]
369 if not self._allow_partial_inputs:
370 self._check_partial_inputs([layout])
372 in_tensor_map = layout.alias_tensor_map
373 ndim = len(in_tensor_map)
375 if dim < 0:
376 dim = ndim + dim
377 if not 0 <= dim < ndim:
378 raise ValueError(
379 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
380 f"but got {dim}."
381 )
383 if in_tensor_map[dim] != "None":
384 raise ValueError(
385 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
386 f"but got layout: {layout}."
387 )
389 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)
392class TensorSplitDistributedOp(DistributedOp):
393 """Distributed implementation for tensor_split operator."""
395 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
396 """
397 Preprocess arguments for tensor_split operator.
399 Args:
400 args (tuple): Input arguments (input, indices_or_sections[, dim]).
401 kwargs (dict): Keyword arguments (may contain dim).
403 Returns:
404 tuple: (local_args, local_kwargs, cache_values)
405 """
406 args, kwargs = _normalize_tensor_split_args(*args, **kwargs)
407 input_tensor, indices_or_sections, dim = args
409 if isinstance(indices_or_sections, int):
410 output_num = indices_or_sections
411 elif isinstance(indices_or_sections, (list, tuple)):
412 output_num = len(indices_or_sections) + 1
413 elif hasattr(indices_or_sections, "shape") and len(indices_or_sections.shape) == 0:
414 # Torch accepts a CPU scalar tensor for the sections overload.
415 output_num = int(indices_or_sections.item())
416 elif hasattr(indices_or_sections, "shape") and len(indices_or_sections.shape) == 1:
417 output_num = indices_or_sections.shape[0] + 1
418 else:
419 raise TypeError(
420 f"For {self.op_name}, indices_or_sections must be an integer, "
421 f"list, tuple, or 1D tensor."
422 )
424 local_indices = indices_or_sections
425 if hasattr(indices_or_sections, "_layout"):
426 local_indices = indices_or_sections.to_local()
428 local_args = (input_tensor.to_local(), local_indices, dim)
429 local_kwargs = {}
430 cache_values = [input_tensor.layout, dim, output_num]
431 return local_args, local_kwargs, cache_values
433 # pylint: disable=W0237
434 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
435 """
436 Infer output layouts for tensor_split operator.
438 Rules:
439 1. Input must not have Partial status.
440 2. The split dimension must not be sharded.
441 3. dim must be within the valid range of input dimensions.
443 Args:
444 cache_values (list): [input_layout, dim, output_num]
446 Returns:
447 tuple: ((output_layouts,), None)
449 Raises:
450 ValueError: If any rule above is violated.
451 """
452 layout = cache_values[0]
453 dim = cache_values[1]
454 output_num = cache_values[2]
456 if not self._allow_partial_inputs:
457 self._check_partial_inputs([layout])
459 in_tensor_map = layout.alias_tensor_map
460 ndim = len(in_tensor_map)
462 if dim < 0:
463 dim = ndim + dim
464 if not 0 <= dim < ndim:
465 raise ValueError(
466 f"For {self.op_name}, dimension should be in range [0, {ndim}), "
467 f"but got {dim}."
468 )
470 if in_tensor_map[dim] != "None":
471 raise ValueError(
472 f"For {self.op_name}, can not split tensor at sharded axis[{dim}], "
473 f"but got layout: {layout}."
474 )
476 return (tuple(copy.deepcopy(layout) for _ in range(output_num)), None)