Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_sort.py: 94%
34 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 Sort 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_sort_args(input, dim=-1, descending=False, stable=False):
27 return (input,), {'dim': dim, 'descending': descending, 'stable': stable}
30class SortDistributedOp(DistributedOp):
31 """Distributed implementation for Sort operator."""
33 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
34 """
35 Preprocess arguments for Sort operator.
37 Args:
38 args (tuple): Input arguments, first element is the input tensor.
39 kwargs (dict): Keyword arguments (dim, descending, stable).
41 Returns:
42 tuple: (local_args, local_kwargs, cache_values)
43 """
44 args, kwargs = _normalize_sort_args(*args, **kwargs)
45 input_tensor = args[0]
46 dim = kwargs['dim']
47 descending = kwargs['descending']
48 stable = kwargs['stable']
50 local_args = (input_tensor.to_local(),)
51 local_kwargs = {'dim': dim, 'descending': descending, 'stable': stable}
53 cache_values = [input_tensor.layout, dim]
54 return local_args, local_kwargs, cache_values
56 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
57 """
58 Infer output layouts for Sort operator.
60 Rules:
61 1. Input must not have Partial status.
62 2. dim must be an integer within the valid range [-ndim, ndim-1].
63 3. The sort dimension must not be sharded (including StridedShard multi-axis mappings).
64 4. Output values and indices layouts are identical to the input layout.
66 Args:
67 cache_values (list): [input_layout, dim] where dim is the sort dimension.
69 Returns:
70 tuple: ((values_layout, indices_layout), None)
72 Raises:
73 ValueError: If input has Partial status, dim is out of range, or the sort dimension
74 is sharded.
75 """
76 layout = cache_values[0]
77 dim = cache_values[1]
79 self._check_partial_inputs([layout])
81 if not isinstance(dim, int):
82 raise ValueError(
83 f"For {self.op_name}, dimension should be int, but got {type(dim)}"
84 )
86 # Get tensor map to check sharding status
87 in_tensor_map = layout.tensor_map
88 ndim = len(in_tensor_map)
90 if dim < -ndim or dim >= ndim:
91 raise ValueError(
92 f"For {self.op_name}, dimension out of range "
93 f"(expected to be in range of [{-ndim}, {ndim - 1}], but got {dim})"
94 )
96 if dim < 0:
97 dim += ndim
99 # Check if the sorting dimension is sharded.
100 # In tensor_map, -1 means Replicate (not sharded); any other value implies sharding.
101 mapping = in_tensor_map[dim]
102 if isinstance(mapping, (list, tuple)):
103 is_sharded = any(m != -1 for m in mapping)
104 else:
105 is_sharded = mapping != -1
107 if is_sharded:
108 raise ValueError(
109 f"For {self.op_name}, sorting along a sharded dimension "
110 f"(dim {dim} mapped to {mapping}) is not supported. "
111 f"Please redistribute the tensor to Replicate on this dimension before sorting."
112 )
114 return ((layout, layout), None)