Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_norm.py: 95%
83 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 Norm operators (RmsNorm, layer_norm).
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_rmsnorm_args(input, gamma, epsilon=1e-6):
28 """Normalize RmsNorm args to positional form.
30 RmsNorm takes (input, gamma, epsilon) as positional arguments.
31 """
32 return (input, gamma, epsilon), {}
35# Preserve Torch keyword names for calls forwarded by __torch_function__.
36# pylint: disable-next=redefined-builtin
37def _normalize_layernorm_args(input, normalized_shape, weight=None, bias=None, eps=1e-5, cudnn_enable=None):
38 """Normalize layer_norm args to positional form.
40 The functional API has five positional parameters. Only forward the extra
41 cudnn_enable flag when supplied by a call to the torch.layer_norm builtin.
42 """
43 kwargs = {} if cudnn_enable is None else {'cudnn_enable': cudnn_enable}
44 return (input, normalized_shape, weight, bias, eps), kwargs
47class NormDistributedOp(DistributedOp):
48 """Distributed implementation for RmsNorm operator."""
50 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
51 """
52 Preprocess arguments for RmsNorm operator.
54 Args:
55 args (tuple): Positional arguments (x, gamma) where both are DTensors.
56 kwargs (dict): Keyword arguments (none expected).
58 Returns:
59 tuple: (local_args, local_kwargs, cache_values)
60 """
61 args, kwargs = _normalize_rmsnorm_args(*args, **kwargs)
62 x, gamma, epsilon = args
63 local_args = (x.to_local(), gamma.to_local(), epsilon)
64 local_kwargs = {}
65 cache_values = [x.layout, gamma.layout]
66 return local_args, local_kwargs, cache_values
68 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
69 """
70 Infer output layouts for RmsNorm operator.
72 Rules:
73 1. Inputs must not have Partial status.
74 2. x and gamma must share the same mesh_shape.
75 3. Dimensions being normalized (the last len(gamma_tensor_map) dims of x)
76 must not be sharded.
77 4. The sharding of the normalized dimensions of x must match gamma's sharding.
78 5. Output layout keeps sharding on non-normalized dims and replicates
79 on normalized dims.
81 Args:
82 cache_values (list): [x_layout, gamma_layout]
84 Returns:
85 tuple: ((x_layout, out_layout), None)
87 Raises:
88 ValueError: If any rule above is violated.
89 """
90 if len(cache_values) < 2:
91 raise ValueError(
92 f"For {self.op_name}, cache_values size {len(cache_values)} is less than 2."
93 )
94 x_layout = cache_values[0]
95 gamma_layout = cache_values[1]
96 # Check partial inputs
97 if not self._allow_partial_inputs:
98 self._check_partial_inputs([x_layout, gamma_layout])
99 if x_layout.mesh_shape != gamma_layout.mesh_shape:
100 raise ValueError(f"{self.op_name} inputs must have same mesh_shape")
101 x_alias_map = x_layout.alias_tensor_map
102 gamma_alias_map = gamma_layout.alias_tensor_map
103 if len(gamma_alias_map) > len(x_alias_map):
104 raise ValueError(
105 f"For {self.op_name}, gamma ndim {len(gamma_alias_map)} cannot exceed "
106 f"input ndim {len(x_alias_map)}."
107 )
108 begin_norm_axis = len(x_alias_map) - len(gamma_alias_map)
109 for alias_entry in x_alias_map[begin_norm_axis:]:
110 entries = alias_entry if isinstance(alias_entry, tuple) else (alias_entry,)
111 for name in entries:
112 if name == "None":
113 continue
114 axis_idx = x_layout.alias_name.index(name)
115 if x_layout.mesh_shape[axis_idx] > 1:
116 raise ValueError(f"{self.op_name} is disabled to support the splitting after "
117 f"begin_norm_axis {begin_norm_axis} for input 0.")
118 if x_alias_map[begin_norm_axis:] != gamma_alias_map:
119 raise ValueError(f"For {self.op_name}, input sharding from begin_norm_axis "
120 f"{begin_norm_axis}, {x_alias_map[begin_norm_axis:]}, should equal "
121 f"gamma sharding {gamma_alias_map}.")
122 output_layout = Layout(
123 mesh_shape=x_layout.mesh_shape,
124 alias_name=x_layout.alias_name,
125 rank_list=x_layout.rank_list
126 )
127 output_map = x_alias_map[:begin_norm_axis] + ("None",) * len(gamma_alias_map)
128 out_layout = output_layout(*output_map)
129 return ((x_layout, out_layout), None)
132class LayerNormDistributedOp(DistributedOp):
133 """Distributed implementation for torch.nn.functional.layer_norm."""
135 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
136 """
137 Preprocess arguments for layer_norm operator.
139 Args:
140 args (tuple): Positional arguments (input, normalized_shape, weight, bias, eps).
141 kwargs (dict): Keyword arguments (none expected for this functional API).
143 Returns:
144 tuple: (local_args, local_kwargs, cache_values)
145 """
146 args, kwargs = _normalize_layernorm_args(*args, **kwargs)
147 input_tensor, normalized_shape, weight, bias, eps = args
149 # Normalize normalized_shape: int → (int,), list → tuple
150 if isinstance(normalized_shape, int):
151 normalized_shape = (normalized_shape,)
152 elif isinstance(normalized_shape, list):
153 normalized_shape = tuple(normalized_shape)
155 local_args = [
156 input_tensor.to_local(),
157 normalized_shape,
158 weight.to_local() if weight is not None and hasattr(weight, 'to_local') else weight,
159 bias.to_local() if bias is not None and hasattr(bias, 'to_local') else bias,
160 eps,
161 ]
162 local_kwargs = kwargs
164 cache_values = [input_tensor.layout, normalized_shape]
165 return tuple(local_args), local_kwargs, cache_values
167 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
168 """
169 Infer output layout for layer_norm operator.
171 Rules:
172 1. Input must not have Partial status.
173 2. normalized_shape must be int, list, or tuple.
174 3. normalized_shape dimensions must be ≤ input ndim.
175 4. All dimensions in normalized_shape must be unsharded.
176 5. Output layout is identical to input layout.
178 Args:
179 cache_values (list): [input_layout, normalized_shape]
181 Returns:
182 tuple: ((output_layout,), None)
184 Raises:
185 ValueError: If any rule above is violated.
186 """
187 input_layout = cache_values[0]
188 if input_layout is None:
189 raise ValueError(f"{self.op_name} requires a valid input tensor layout.")
190 normalized_shape = cache_values[1]
191 # Check partial inputs
192 if not self._allow_partial_inputs:
193 self._check_partial_inputs([input_layout])
195 if normalized_shape is None:
196 raise ValueError(f"{self.op_name} requires normalized_shape.")
198 if not isinstance(normalized_shape, tuple):
199 raise ValueError(f"normalized_shape must be int, list, or tuple, got {type(normalized_shape)}")
201 in_alias_map = input_layout.alias_tensor_map
202 input_ndim = len(in_alias_map)
203 norm_ndim = len(normalized_shape)
205 if norm_ndim > input_ndim:
206 raise ValueError(
207 f"normalized_shape {normalized_shape} (dims={norm_ndim}) is larger than input ndim={input_ndim}."
208 )
210 # The last `norm_ndim` dimensions are going to be normalized
211 dims_to_normalize = list(range(input_ndim - norm_ndim, input_ndim))
213 # All normalized dims must be unsharded
214 for dim in dims_to_normalize:
215 alias_entry = in_alias_map[dim]
216 entries = alias_entry if isinstance(alias_entry, tuple) else (alias_entry,)
217 for name in entries:
218 if name == "None":
219 continue
220 raise ValueError(
221 f"Operation {self.op_name}: Cannot perform sharding on normalized dimension {dim}, "
222 f"but found sharding assignment: {in_alias_map[dim]}"
223 )
225 output_layout = Layout(
226 mesh_shape=input_layout.mesh_shape,
227 alias_name=input_layout.alias_name,
228 rank_list=input_layout.rank_list
229 )
230 output_layout = output_layout(*in_alias_map)
231 return ((output_layout,), None)