Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_pad.py: 92%
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 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 Pad operator.
17"""
19from typing import Tuple
21from .parallel_ops import DistributedOp
24# Preserve Torch keyword names for calls forwarded by __torch_function__.
25# pylint: disable-next=redefined-builtin
26def _normalize_pad_args(input, pad, mode='constant', value=None):
27 return (input, pad, mode, value), {}
30class PadDistributedOp(DistributedOp):
31 """Distributed implementation for Pad operator."""
33 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
34 """
35 Preprocess arguments for Pad operator.
37 Args:
38 args (tuple): Input tensor followed by pad arguments.
39 kwargs (dict): Keyword arguments for pad.
41 Returns:
42 tuple: (local_args, local_kwargs, cache_values)
43 """
44 args, _ = _normalize_pad_args(*args, **kwargs)
45 input_tensor = args[0]
46 pad, mode, value = args[1], args[2], args[3]
48 local_args = (input_tensor.to_local(), pad, mode, value)
49 local_kwargs = {}
50 cache_values = [input_tensor.layout, pad]
51 return local_args, local_kwargs, cache_values
53 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
54 """
55 Infer output layout for Pad operator.
57 Rules:
58 1. Input must not have Partial status.
59 2. pad must be a tuple or list with even length.
60 3. The number of padded dimensions must not exceed input ndim.
61 4. Any dimension with non-zero padding must not be sharded.
62 5. Output layout is identical to the input layout.
64 Args:
65 cache_values (list): [input_layout, pad].
67 Returns:
68 tuple: ((output_layout,), None)
70 Raises:
71 ValueError: If input has Partial status, pad is invalid, or padding is
72 attempted on a sharded dimension.
73 """
74 if len(cache_values) != 2:
75 raise ValueError(
76 f"For {self.op_name}, cache_values length should be 2, but got {len(cache_values)}"
77 )
79 input_layout, pad = cache_values[0], cache_values[1]
80 if input_layout is None:
81 raise ValueError(f"For {self.op_name}, pad requires a valid input tensor layout.")
83 self._check_partial_inputs([input_layout])
85 tensor_map = input_layout.alias_tensor_map
86 ndim = len(tensor_map)
88 if not isinstance(pad, (tuple, list)):
89 raise ValueError(
90 f"For {self.op_name}, expected pad tuple or list, but got {type(pad)}"
91 )
93 pad_len = len(pad)
95 if pad_len % 2 != 0:
96 raise ValueError(f"For {self.op_name}, Pad tuple length must be even, but got {pad_len}")
98 # Pytorch pad tuple format: (last_dim_left, last_dim_right, 2nd_last_left, 2nd_last_right, ...)
99 # We need to check if any dimension being padded is currently sharded.
100 num_padded_dims = pad_len // 2
101 if num_padded_dims > ndim:
102 raise ValueError(
103 f"For {self.op_name}, Padding {num_padded_dims} dimensions but tensor only has {ndim} dimensions."
104 )
106 for i in range(num_padded_dims):
107 # Calculate the dimension index in the tensor (from 0 to ndim-1)
108 # pad index 0,1 -> last dimension (ndim - 1)
109 # pad index 2,3 -> second to last dimension (ndim - 2)
110 dim_index = ndim - 1 - i
112 pad_left = pad[2 * i]
113 pad_right = pad[2 * i + 1]
115 # If padding is applied on this dimension
116 if pad_left != 0 or pad_right != 0:
117 axis_alias = tensor_map[dim_index]
118 is_sharded = (any(alias != "None" for alias in axis_alias)
119 if isinstance(axis_alias, (tuple, list))
120 else axis_alias != "None")
122 if is_sharded:
123 raise ValueError(
124 f"For {self.op_name}, Distributed Pad operator does not support padding "
125 f"on a sharded dimension. "
126 f"Dimension {dim_index} (alias: {axis_alias}) is sharded. "
127 f"Please redistribute the tensor to Replicate status on this dimension before padding."
128 )
130 # If no sharded dimension is padded, the output layout is identical to the input layout.
131 # The local tensor shape changes, but the mapping from device mesh to tensor dimensions remains valid.
132 return ((input_layout,), None)
134 # Note: get_expand_impl is not overridden because we default to returning None.
135 # OpDispatcher will use the original function (e.g., torch.nn.functional.pad) on the local tensor.
136 # Since we ensured the padded dimensions are Replicated, local padding is mathematically correct.