Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_argsort.py: 97%
35 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-07-06 05:41 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-07-06 05:41 +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 Argsort operator.
17"""
19from typing import Tuple
21from .parallel_ops import DistributedOp
24def _normalize_argsort_args(x, dim=-1, descending=False, stable=False):
25 """Normalize torch.argsort arguments to (args, kwargs).
27 torch.argsort(input, dim=-1, descending=False, *, stable=False)
28 Only `stable` is keyword-only; all other params are positional.
29 """
30 return (x, dim, descending), {'stable': stable}
33class ArgsortDistributedOp(DistributedOp):
34 """Distributed implementation for torch.argsort."""
36 _MS_PRIMITIVE_OP_NAMES = frozenset({'ArgSort'})
38 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
39 """
40 Preprocess arguments for Argsort operator.
42 Args:
43 args (tuple): Input arguments, first element is the input tensor.
44 kwargs (dict): Keyword arguments (dim, descending, stable).
46 Returns:
47 tuple: (local_args, local_kwargs, cache_values)
48 """
49 args, kwargs = _normalize_argsort_args(*args, **kwargs)
50 input_tensor = args[0]
51 dim = args[1]
52 descending = args[2]
53 stable = kwargs['stable']
55 if self.op_name in self._MS_PRIMITIVE_OP_NAMES:
56 local_args = (input_tensor.to_local(), dim, descending, stable)
57 local_kwargs = {}
58 else:
59 local_args = (input_tensor.to_local(),)
60 local_kwargs = {'dim': dim, 'descending': descending, 'stable': stable}
62 cache_values = [input_tensor.layout, dim]
63 return local_args, local_kwargs, cache_values
65 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
66 """
67 Infer output layout for Argsort operator.
69 Rules:
70 1. Input must not have Partial status.
71 2. dim must be an integer within the valid range [-ndim, ndim-1].
72 3. The sort dimension must not be sharded.
73 4. Output layout is identical to the input layout.
75 Args:
76 cache_values (list): [input_layout, dim] where dim is the sort dimension.
78 Returns:
79 tuple: ((output_layout,), None)
81 Raises:
82 ValueError: If input has Partial status, dim is out of range, or the sort
83 dimension is sharded.
84 """
85 layout = cache_values[0]
86 dim = cache_values[1]
88 if not self._allow_partial_inputs:
89 self._check_partial_inputs([layout])
91 if not isinstance(dim, int):
92 raise ValueError(
93 f"For {self.op_name}, dimension should be int, but got {type(dim)}"
94 )
96 alias_map = layout.alias_tensor_map
97 ndim = len(alias_map)
99 if dim < -ndim or dim >= ndim:
100 raise ValueError(
101 f"For {self.op_name}, dimension out of range "
102 f"(expected to be in range of [{-ndim}, {ndim - 1}], but got {dim})"
103 )
105 if dim < 0:
106 dim += ndim
108 if alias_map[dim] != "None":
109 raise ValueError(
110 f"For {self.op_name}, sorting along a sharded dimension "
111 f"(dim {dim} mapped to {alias_map[dim]}) is not supported. "
112 f"Please redistribute the tensor to Replicate on this dimension before sorting."
113 )
115 return ((layout,), None)