Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_histc_ext.py: 95%
42 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 HistcExt operator.
17"""
19from typing import Tuple
21from hyper_parallel.core.dtensor.layout import Layout
22from .parallel_ops import DistributedOp
25# Preserve Torch keyword names for calls forwarded by __torch_function__.
26# pylint: disable-next=redefined-builtin
27def _normalize_histc_args(input, bins=100, min=0, max=0):
28 return (input, bins, min, max), {}
31class HistcExtDistributedOp(DistributedOp):
32 """
33 Distributed implementation for HistcExt operator.
35 HistcExt computes the histogram of a tensor. In distributed setting:
36 - Each device computes a local histogram
37 - Local histograms are aggregated using AllReduce(SUM)
38 - Output is always replicated (1D tensor with shape (bins,))
39 """
41 def __init__(self, op_name: str = "HistcExt") -> None:
42 """Initialize HistcExtDistributedOp."""
43 super().__init__(op_name)
45 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
46 """
47 Preprocess arguments for HistcExt operator.
49 Args:
50 args (tuple): Input arguments, first element is the input tensor.
51 kwargs (dict): Keyword arguments (bins, min, max).
53 Returns:
54 tuple: (local_args, local_kwargs, cache_values)
55 """
56 args, kwargs = _normalize_histc_args(*args, **kwargs)
57 x, bins, min_val, max_val = args
58 local_args = (x.to_local(), bins, min_val, max_val)
59 local_kwargs = {}
60 cache_values = [x.layout, bins, min_val, max_val]
61 return local_args, local_kwargs, cache_values
63 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
64 """
65 Infer output layout for HistcExt operator.
67 Rules:
68 1. Input layout must not be None.
69 2. bins must be a positive integer.
70 3. min and max must be numbers with min <= max.
71 4. Output is always a 1D replicated tensor of shape (bins,).
72 5. When input is sharded, output carries Partial(sum) on sharded device axes.
74 Args:
75 cache_values (list): [input_layout, bins, min, max]
77 Returns:
78 tuple: ((output_layout,), None)
80 Raises:
81 ValueError: If any rule above is violated.
82 """
83 x_layout = cache_values[0]
84 bins = cache_values[1]
85 min_val = cache_values[2]
86 max_val = cache_values[3]
88 if not self._allow_partial_inputs:
89 self._check_partial_inputs([x_layout])
91 if x_layout is None or x_layout.mesh_shape is None:
92 raise ValueError(
93 f"For {self.op_name}, input layout should not be None, "
94 f"but got {x_layout}"
95 )
97 if not isinstance(bins, int):
98 raise ValueError(
99 f"For {self.op_name}, bins should be an integer, "
100 f"but got {type(bins).__name__}"
101 )
102 if bins <= 0:
103 raise ValueError(
104 f"For {self.op_name}, bins should be a positive integer, "
105 f"but got {bins}"
106 )
107 if not isinstance(min_val, (int, float)):
108 raise ValueError(
109 f"For {self.op_name}, min should be a number, "
110 f"but got {type(min_val).__name__}"
111 )
112 if not isinstance(max_val, (int, float)):
113 raise ValueError(
114 f"For {self.op_name}, max should be a number, "
115 f"but got {type(max_val).__name__}"
116 )
117 if min_val > max_val:
118 raise ValueError(
119 f"For {self.op_name}, min should be less than or equal to max, "
120 f"but got min={min_val}, max={max_val}"
121 )
123 output_layout = Layout(
124 mesh_shape=x_layout.mesh_shape,
125 alias_name=x_layout.alias_name,
126 rank_list=x_layout.rank_list,
127 )
128 out_layout = output_layout("None",)
130 has_sharding = any(
131 alias is not None and alias != "None"
132 for alias in x_layout.alias_tensor_map
133 )
135 if has_sharding:
136 for alias, tensor_map_val in zip(x_layout.alias_name, x_layout.alias_tensor_map):
137 if tensor_map_val is not None and tensor_map_val != "None":
138 out_layout.set_partial_by_dev_axis(alias, "sum")
140 return ((out_layout,), None)