Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_squeeze.py: 91%
102 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 Squeeze operator.
17"""
18from copy import deepcopy
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_squeeze_args(input, dim=None):
28 return (input, dim), {}
31class SqueezeDistributedOp(DistributedOp):
32 """Distributed implementation for Squeeze operator."""
34 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
35 args, _ = _normalize_squeeze_args(*args, **kwargs)
36 input_tensor, axis = args[0], args[1]
38 if axis is None:
39 local_args = (input_tensor.to_local(),)
40 else:
41 local_args = (input_tensor.to_local(), axis)
43 input_shape = getattr(input_tensor, "shape", None)
44 cache_values = [input_tensor.layout, axis, input_shape]
45 return local_args, {}, cache_values
47 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
48 """
49 Infer output layout for Squeeze operator.
51 Rules:
52 1. Input must not have Partial status.
53 2. input_shape rank must match input layout rank.
54 3. If axis is None, only size-1 replicated dimensions are removed.
55 4. If axis is specified, every axis must be in range, have size 1, and
56 must not be sharded.
57 5. Output layout removes the squeezed dimensions and preserves the
58 remaining input dimension mappings.
60 Args:
61 cache_values (list): [input_layout, axis, input_shape]
63 Returns:
64 tuple: ((output_layout,), None)
66 Raises:
67 ValueError: If input has Partial status, input_shape is missing, axis
68 is invalid, or a requested squeeze dimension is sharded.
69 """
70 if not cache_values:
71 raise ValueError(
72 f"For {self.op_name}, cache_values should contain input layout, "
73 f"but got empty cache_values."
74 )
76 x_layout = cache_values[0]
77 if not self._allow_partial_inputs:
78 self._check_partial_inputs([x_layout])
80 if x_layout.mesh_shape is None:
81 raise ValueError(
82 f"For {self.op_name}, input layout mesh_shape should not be None, "
83 f"but got None."
84 )
86 axis = cache_values[1] if len(cache_values) > 1 else None
87 input_shape = cache_values[2] if len(cache_values) > 2 else None
88 if input_shape is None:
89 raise ValueError(
90 f"For {self.op_name}, input_shape should be provided in cache_values, "
91 f"but got None."
92 )
93 if not isinstance(input_shape, (list, tuple)):
94 raise ValueError(
95 f"For {self.op_name}, input_shape should be list or tuple, "
96 f"but got {type(input_shape)}."
97 )
99 output_layout = self._compute_squeeze_layout(x_layout, axis, input_shape)
100 return ((output_layout,), None)
102 def _compute_squeeze_layout(self, x_layout, axis, input_shape):
103 """Compute the squeezed layout."""
104 # Handle scalar case
105 if not input_shape:
106 return self._handle_scalar_case(x_layout, axis)
108 # Validate input_shape matches layout rank
109 self._validate_input_shape(x_layout, input_shape)
111 # Find dimensions to squeeze
112 dims_to_squeeze = self._get_dims_to_squeeze(x_layout, axis, input_shape)
114 # Create output layout
115 return self._create_output_layout(x_layout, dims_to_squeeze)
117 def _handle_scalar_case(self, x_layout, axis):
118 """Handle scalar input case."""
119 if axis is not None and axis != [] and axis != ():
120 raise ValueError(
121 f"For {self.op_name}, axis should be None for scalar input, "
122 f"but got {axis}."
123 )
125 return deepcopy(x_layout)
127 def _validate_input_shape(self, x_layout, input_shape):
128 """Validate that input shape matches layout rank."""
129 x_map = list(x_layout.alias_tensor_map)
130 in_rank = len(x_map)
132 if len(input_shape) != in_rank:
133 raise ValueError(
134 f"For {self.op_name}, input shape rank should match layout rank, "
135 f"but got {len(input_shape)} and {in_rank}."
136 )
138 def _get_dims_to_squeeze(self, x_layout, axis, input_shape):
139 """Get list of dimensions to squeeze."""
140 x_map = list(x_layout.alias_tensor_map)
141 in_rank = len(x_map)
143 if axis is None:
144 return self._get_all_squeezable_dims(x_map, input_shape)
145 return self._get_specified_dims_to_squeeze(x_map, axis, input_shape, in_rank)
147 def _get_all_squeezable_dims(self, x_map, input_shape):
148 """Get all squeezable dimensions when axis is None."""
149 dims_to_squeeze = []
150 for i, shape in enumerate(input_shape):
151 if shape == 1 and x_map[i] == "None":
152 dims_to_squeeze.append(i)
153 return dims_to_squeeze
155 def _get_specified_dims_to_squeeze(self, x_map, axis, input_shape, in_rank):
156 """Get dimensions to squeeze when axis is specified."""
157 # Convert axis to list if it's a single integer
158 if isinstance(axis, int):
159 axis = [axis]
160 elif isinstance(axis, tuple):
161 axis = list(axis)
162 elif not isinstance(axis, list):
163 raise ValueError(
164 f"For {self.op_name}, axis should be int, list or tuple, "
165 f"but got {type(axis)}."
166 )
168 if not all(isinstance(ax, int) for ax in axis):
169 raise ValueError(
170 f"For {self.op_name}, every axis value should be int, "
171 f"but got {axis}."
172 )
174 # Convert negative indices to positive
175 axis = [ax if ax >= 0 else ax + in_rank for ax in axis]
177 # Validate axis range
178 self._validate_axis_range(axis, in_rank)
180 # Check all specified axes
181 for ax in axis:
182 self._validate_axis_for_squeeze(x_map, input_shape, ax)
184 # Return sorted unique axes
185 return sorted(set(axis))
187 def _validate_axis_range(self, axis, in_rank):
188 """Validate axis values are within range."""
189 for ax in axis:
190 if ax < 0 or ax >= in_rank:
191 raise ValueError(
192 f"For {self.op_name}, axis should be in range [{-in_rank}, {in_rank-1}], "
193 f"but got {ax}."
194 )
196 def _validate_axis_for_squeeze(self, x_map, input_shape, ax):
197 """Validate a specific axis can be squeezed."""
198 # Check shape == 1
199 if input_shape[ax] != 1:
200 raise ValueError(
201 f"For {self.op_name}, dimension should have size 1, "
202 f"but got shape {input_shape[ax]} at dimension {ax}."
203 )
205 # Check mapping is "None" (not distributed)
206 if x_map[ax] != "None":
207 raise ValueError(
208 f"For {self.op_name}, dimension should not be distributed, "
209 f"but got dimension {ax} mapped to device axis {x_map[ax]}."
210 )
212 def _create_output_layout(self, x_layout, dims_to_squeeze):
213 """Create output layout after squeezing dimensions."""
214 if not dims_to_squeeze:
215 return deepcopy(x_layout)
217 # Get current alias tensor map
218 x_map = list(x_layout.alias_tensor_map)
220 # Sort in descending order for safe removal
221 dims_to_squeeze = sorted(set(dims_to_squeeze), reverse=True)
223 # Remove specified dimensions
224 for dim in dims_to_squeeze:
225 del x_map[dim]
227 new_map = x_map
229 # Create output layout with new mapping
230 output_layout = Layout(
231 mesh_shape=x_layout.mesh_shape,
232 alias_name=x_layout.alias_name,
233 rank_list=x_layout.rank_list
234 )
236 if new_map:
237 output_layout = output_layout(*new_map)
238 else:
239 # For scalar result
240 output_layout = output_layout()
242 # Copy partial operations from input layout
243 self._copy_partial_operations(x_layout, output_layout, new_map)
245 return output_layout
247 def _copy_partial_operations(self, x_layout, output_layout, new_map):
248 """Copy partial operations from input to output layout."""
249 for i, partial_op in enumerate(x_layout.partial):
250 if partial_op is not None:
251 dev_axis_name = x_layout.alias_name[i]
252 # Check if this device axis is still used in the output
253 if dev_axis_name in new_map:
254 output_layout.set_partial_by_dev_axis(dev_axis_name, partial_op)