Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_argsort.py: 97%
32 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 Argsort operator.
17"""
19import copy
20from typing import Tuple
22from .parallel_ops import DistributedOp
25# Preserve Torch keyword names for calls forwarded by __torch_function__.
26# pylint: disable-next=redefined-builtin
27def _normalize_argsort_args(input, dim=-1, descending=False, stable=False):
28 """Normalize torch.argsort arguments to (args, kwargs).
30 torch.argsort(input, dim=-1, descending=False, *, stable=False)
31 Only `stable` is keyword-only; all other params are positional.
32 """
33 return (input, dim, descending), {'stable': stable}
36class ArgsortDistributedOp(DistributedOp):
37 """Distributed implementation for torch.argsort."""
39 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
40 """
41 Preprocess arguments for Argsort operator.
43 Args:
44 args (tuple): Input arguments, first element is the input tensor.
45 kwargs (dict): Keyword arguments (dim, descending, stable).
47 Returns:
48 tuple: (local_args, local_kwargs, cache_values)
49 """
50 args, kwargs = _normalize_argsort_args(*args, **kwargs)
51 input_tensor = args[0]
52 dim = args[1]
53 descending = args[2]
54 stable = kwargs['stable']
56 local_args = (input_tensor.to_local(),)
57 local_kwargs = {'dim': dim, 'descending': descending, 'stable': stable}
59 cache_values = [input_tensor.layout, dim]
60 return local_args, local_kwargs, cache_values
62 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
63 """
64 Infer output layout for Argsort operator.
66 Rules:
67 1. Input must not have Partial status.
68 2. dim must be an integer within the valid range [-ndim, ndim-1].
69 3. The sort dimension must not be sharded.
70 4. Output layout is identical to the input layout.
72 Args:
73 cache_values (list): [input_layout, dim] where dim is the sort dimension.
75 Returns:
76 tuple: ((output_layout,), None)
78 Raises:
79 ValueError: If input has Partial status, dim is out of range, or the sort
80 dimension is sharded.
81 """
82 layout = cache_values[0]
83 dim = cache_values[1]
85 if not self._allow_partial_inputs:
86 self._check_partial_inputs([layout])
88 if not isinstance(dim, int):
89 raise ValueError(
90 f"For {self.op_name}, dimension should be int, but got {type(dim)}"
91 )
93 alias_map = layout.alias_tensor_map
94 ndim = len(alias_map)
96 if dim < -ndim or dim >= ndim:
97 raise ValueError(
98 f"For {self.op_name}, dimension out of range "
99 f"(expected to be in range of [{-ndim}, {ndim - 1}], but got {dim})"
100 )
102 if dim < 0:
103 dim += ndim
105 if alias_map[dim] != "None":
106 raise ValueError(
107 f"For {self.op_name}, sorting along a sharded dimension "
108 f"(dim {dim} mapped to {alias_map[dim]}) is not supported. "
109 f"Please redistribute the tensor to Replicate on this dimension before sorting."
110 )
112 return ((copy.deepcopy(layout),), None)