Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_conv3d.py: 73%
93 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 Conv3d operator.
17"""
19from typing import Callable, Optional, 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_conv3d_args(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
28 return (input, weight, bias, stride, padding, dilation, groups), {}
31class Conv3dDistributedOp(DistributedOp):
32 """
33 Distributed implementation for torch.nn.functional.conv3d.
34 Supports Data Parallel, Tensor Parallel (Column/Row), and Spatial Parallel.
35 """
37 def __init__(self, op_name):
38 super().__init__(op_name)
39 self._allow_partial_inputs = False
41 def _validate_row_parallelism(self, in_map, w_map, groups):
42 """
43 Validate constraints for Row Parallelism.
44 """
45 # 1. Handle Groups Constraint for Row Parallelism
46 if groups > 1:
47 if in_map[1] != "None" or w_map[1] != "None":
48 # Row Parallelism with groups > 1 requires advanced group-wise communication
49 raise ValueError(f"For {self.op_name}, Sharding on C_in with groups > 1 is not supported.")
51 # 2. Check Row Parallelism (Sharding on Channel In)
52 # Input: (N, C_in, D, H, W), Weight: (C_out, C_in/groups, kD, kH, kW)
53 if in_map[1] != "None":
54 if in_map[1] != w_map[1]:
55 raise ValueError(f"For {self.op_name}, Input C_in and Weight C_in must be sharded on the same axis.")
57 def _validate_column_parallelism(self, w_layout, b_layout, groups):
58 """
59 Validate constraints for Column Parallelism.
60 """
61 w_map = w_layout.alias_tensor_map
62 w_map_0 = w_map[0]
64 if w_map_0 != "None":
65 # Check bias alignment
66 if b_layout is not None:
67 b_map = b_layout.alias_tensor_map
68 b_map_0 = b_map[0]
69 if w_map_0 != b_map_0:
70 raise ValueError(
71 f"For {self.op_name}, Weight C_out and Bias C_out must be sharded on the same axis."
72 )
74 # Check groups divisibility for Column Parallelism
75 if groups > 1:
76 dev_num = 1
77 axes = w_map_0 if isinstance(w_map_0, tuple) else (w_map_0,)
78 for axis_name in axes:
79 dev_num *= w_layout.mesh.get_device_num_along_axis(axis_name)
81 if groups % dev_num != 0:
82 raise ValueError(
83 f"For {self.op_name}, groups ({groups}) "
84 f"must be divisible by tp_size ({dev_num})."
85 )
87 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
88 """
89 Preprocess arguments for Conv3d operator.
91 Args:
92 args (tuple): Conv3d positional arguments.
93 kwargs (dict): Conv3d keyword arguments.
95 Returns:
96 tuple: (local_args, local_kwargs, cache_values)
97 """
98 args, _ = _normalize_conv3d_args(*args, **kwargs)
99 input_tensor, weight, bias, stride, padding, dilation, groups = args
100 local_args = (
101 input_tensor.to_local(),
102 weight.to_local(),
103 bias.to_local() if hasattr(bias, '_layout') else bias,
104 stride,
105 padding,
106 dilation,
107 groups,
108 )
109 local_kwargs = {}
110 cache_values = [
111 input_tensor.layout,
112 weight.layout,
113 bias.layout if hasattr(bias, '_layout') else None,
114 stride,
115 padding,
116 dilation,
117 groups,
118 ]
119 return local_args, local_kwargs, cache_values
121 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
122 """
123 Infer output layout for Conv3d operator.
125 Rules:
126 1. Input and weight must not have Partial status.
127 2. Input and weight must both be 5D.
128 3. Input C_in and weight C_in sharding must match for row parallelism.
129 4. Sharding C_in with groups > 1 is not supported.
130 5. Bias C_out sharding must match weight C_out sharding.
131 6. Output layout inherits N/D/H/W sharding from input and C_out sharding from weight.
132 7. Row parallelism marks output as Partial('sum') on the C_in mesh axis.
134 Args:
135 cache_values (list): [input_layout, weight_layout, bias_layout_or_None,
136 stride, padding, dilation, groups]
138 Returns:
139 tuple: ((output_layout,), None)
141 Raises:
142 ValueError: If layouts are missing, partial, malformed, or violate Conv3d
143 sharding constraints.
144 """
146 in_layout, w_layout, b_layout = cache_values[0], cache_values[1], cache_values[2]
147 groups = cache_values[6]
149 if not in_layout or not w_layout:
150 raise ValueError(f"For {self.op_name}, Requires at least input and weight layouts.")
152 self._check_partial_inputs([in_layout, w_layout])
154 if b_layout is not None:
155 self._check_partial_inputs([b_layout])
157 if in_layout.mesh_shape != w_layout.mesh_shape:
158 raise ValueError(
159 f"For {self.op_name}, input and weight must have the same mesh_shape, "
160 f"but got input: {in_layout.mesh_shape} and weight: {w_layout.mesh_shape}"
161 )
162 if b_layout is not None and b_layout.mesh_shape != in_layout.mesh_shape:
163 raise ValueError(
164 f"For {self.op_name}, bias and input must have the same mesh_shape, "
165 f"but got bias: {b_layout.mesh_shape} and input: {in_layout.mesh_shape}"
166 )
168 in_map = in_layout.alias_tensor_map
169 w_map = w_layout.alias_tensor_map
171 # Validate dimensions
172 if len(in_map) != 5 or len(w_map) != 5:
173 raise ValueError(f"For {self.op_name}, Input and weight must be 5D.")
175 # Delegate validation to helper methods to reduce cyclomatic complexity
176 self._validate_row_parallelism(in_map, w_map, groups)
177 self._validate_column_parallelism(w_layout, b_layout, groups)
179 # Construct Output Map (N, C_out, D_out, H_out, W_out)
180 out_map = [
181 in_map[0], # N
182 w_map[0], # C_out
183 in_map[2], # D
184 in_map[3], # H
185 in_map[4] # W
186 ]
188 # Build Layout
189 output_layout = Layout(
190 mesh_shape=in_layout.mesh_shape,
191 alias_name=in_layout.alias_name,
192 rank_list=in_layout.rank_list,
193 )
194 output_layout = output_layout(*tuple(out_map))
196 # Set Partial status for Row Parallelism
197 if in_map[1] != "None":
198 axes = in_map[1] if isinstance(in_map[1], tuple) else (in_map[1],)
199 for axis in axes:
200 output_layout.set_partial_by_dev_axis(axis, "sum")
202 return (output_layout,), None
204 def get_expand_impl(self, func: Optional[Callable], infer_result: tuple, # pylint: disable=W0221
205 cache_values: list) -> Optional[Callable]:
206 """
207 Get expand implementation for the operator.
208 Intercepts the execution to handle Grouped Convolution with Column Parallelism.
209 """
210 w_layout = cache_values[1]
211 w_map = w_layout.alias_tensor_map
212 w_map_0 = w_map[0]
214 # If Weight is NOT sharded on C_out (dim=0), native conv3d works fine.
215 if w_map_0 == "None":
216 return None
218 parsed_groups = cache_values[6]
219 if parsed_groups == 1:
220 return None
222 mesh = w_layout.mesh
223 axes = w_map_0 if isinstance(w_map_0, tuple) else (w_map_0,)
224 dev_num = 1
225 local_rank = 0
226 for axis_name in axes:
227 axis_size = mesh.get_device_num_along_axis(axis_name)
228 dev_num *= axis_size
229 local_rank = local_rank * axis_size + mesh.get_local_rank(axis_name)
231 # Pre-calculate local groups and group boundaries for the current device ahead of time.
232 # This hoisting optimization avoids redundant calculations during every forward pass.
233 local_groups = parsed_groups // dev_num
234 start_group = local_rank * local_groups
235 end_group = start_group + local_groups
237 def distributed_conv3d_impl(input_tensor, weight_tensor, bias=None, stride=1, padding=0, dilation=1, groups=1):
238 # --- Handling Groups > 1 with Column Parallelism ---
239 # Calculate the input channel chunk size
240 c_in = input_tensor.shape[1]
241 c_in_per_group = c_in // groups
243 # Map the pre-calculated groups to the actual input channels
244 # Uses start_group and end_group captured from the outer scope
245 start_channel = start_group * c_in_per_group
246 end_channel = end_group * c_in_per_group
248 # Slice the replicated input to match the local groups
249 sliced_input = input_tensor[:, start_channel:end_channel, ...]
251 # Execute native conv3d with the sliced input and adjusted local groups
252 return func(sliced_input, weight_tensor, bias, stride, padding, dilation, local_groups)
254 return distributed_conv3d_impl