Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_topk.py: 98%
40 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 TopK operator.
17"""
19from copy import deepcopy
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_topk_args(input, k, dim=-1, largest=True, sorted=True):
28 return (input, k, dim, largest, sorted), {}
31class TopKDistributedOp(DistributedOp):
32 """Distributed implementation for TopK operator."""
34 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
35 """
36 Preprocess arguments for TopK operator.
38 Args:
39 args (tuple): Input arguments, first element is the input tensor.
40 kwargs (dict): Keyword arguments.
42 Returns:
43 tuple: (local_args, local_kwargs, cache_values)
44 """
45 args, kwargs = _normalize_topk_args(*args, **kwargs)
46 input_tensor = args[0]
47 k = args[1]
48 dim = args[2]
49 largest = args[3]
50 sorted_flag = args[4]
52 local_args = (input_tensor.to_local(), k, dim, largest, sorted_flag)
53 local_kwargs = {}
54 cache_values = [input_tensor.layout, dim]
55 return local_args, local_kwargs, cache_values
57 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
58 """
59 Infer output layouts for TopK operator.
61 TopK: values, indices = topk(input, k, dim)
63 Rules:
64 1. Input must not have Partial status.
65 2. dim must be an integer within the valid range [-ndim, ndim-1].
66 3. The topk dimension must not be sharded (including StridedShard multi-axis mappings).
67 4. Both values and indices output layouts are identical to the input layout.
69 Args:
70 cache_values (list): [input_layout, dim] where dim is the topk dimension.
72 Returns:
73 tuple: ((values_layout, indices_layout), None)
75 Raises:
76 ValueError: If input has Partial status, dim is out of range, or the topk dimension
77 is sharded.
78 """
79 layout = cache_values[0]
80 dim = cache_values[1]
82 if not self._allow_partial_inputs:
83 self._check_partial_inputs([layout])
85 if dim is None:
86 dim = -1
87 if not isinstance(dim, int):
88 raise ValueError(
89 f"For {self.op_name}, dimension should be int, but got {type(dim)}"
90 )
92 alias_map = layout.alias_tensor_map
93 ndim = len(alias_map)
95 original_dim = dim
96 if dim < 0:
97 dim += ndim
98 if not 0 <= dim < ndim:
99 raise ValueError(
100 f"For {self.op_name}, dimension out of range "
101 f"(expected to be in range of [{-ndim}, {ndim - 1}], but got {original_dim})"
102 )
104 # Check if the topk dimension is sharded.
105 # In alias_tensor_map, "None" means Replicate (not sharded); any other value implies sharding.
106 mapping = alias_map[dim]
107 if isinstance(mapping, (list, tuple)):
108 is_sharded = any(m != "None" for m in mapping)
109 else:
110 is_sharded = mapping != "None"
112 if is_sharded:
113 raise ValueError(
114 f"For {self.op_name}, topk along a sharded dimension "
115 f"(dim {dim} mapped to {mapping}) is not supported. "
116 f"Please redistribute the tensor to Replicate on this dimension before topk."
117 )
119 return ((deepcopy(layout), deepcopy(layout)), None)