Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mhc / pipelined_mhc.py: 74%
146 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"""Pipelined mHC coefficient and post computation."""
16from __future__ import annotations
17from collections.abc import Mapping
18from typing import Any
19from math import isfinite
20import torch
21from torch import nn
22from torch.nn import functional as F
23from hyper_parallel.components.functional.mhc_post import mhc_post
24from hyper_parallel.components.functional.sinkhorn import sinkhorn_knopps
25from hyper_parallel.core.dtensor.dtensor import DTensor
26from ._utils import _validate_settings
29class _UnweightedRMSNorm(nn.Module):
30 """Normalize coefficient predictors without introducing an extra learned scale."""
32 def __init__(self, eps: float) -> None:
33 super().__init__()
34 self.eps = eps
36 def forward(self, values: torch.Tensor) -> torch.Tensor:
37 """Preserve the source FP32 variance and input-dtype reciprocal scaling order."""
38 return values * torch.rsqrt(values.float().square().mean(-1, keepdim=True) + self.eps).to(values.dtype)
41class PipelinedMhcModule(nn.Module):
42 """Coefficient module for cross-sublayer pipelined mHC."""
44 def __init__(
45 self,
46 *,
47 module: nn.Module | None = None,
48 module_fqn: str = "",
49 context: Mapping[str, Any] | None = None,
50 config: Any = None,
51 token_tile: int = 32,
52 ) -> None:
53 """Reuse the source module's ``fn/base/scale`` parameter layout."""
54 super().__init__()
55 del module_fqn, context
56 if isinstance(token_tile, bool) or not isinstance(token_tile, int) or token_tile < 1:
57 raise ValueError("token_tile must be a positive integer")
58 self.token_tile = token_tile
59 if (module is None) == (config is None):
60 raise ValueError("provide exactly one of config or module")
61 source = config if config is not None else module
62 self.init_scale = getattr(source, "init_scale", 0.01 if config is not None else 1.0)
63 self.init_method_std = getattr(source, "init_method_std", 0.02)
64 if (isinstance(self.init_scale, bool) or not isinstance(self.init_scale, (int, float))
65 or not isfinite(self.init_scale)):
66 raise ValueError("init_scale must be finite")
67 if (isinstance(self.init_method_std, bool) or not isinstance(self.init_method_std, (int, float))
68 or not isfinite(self.init_method_std) or self.init_method_std <= 0):
69 raise ValueError("init_method_std must be positive and finite")
70 if config is not None:
71 self._init_from_config(config)
72 else:
73 self._adopt_source(module)
75 def _init_from_config(self, config: Any) -> None:
76 """Allocate coefficient state with the declared normalization and initialization policy."""
77 _validate_settings(config.num_stream, config.hidden_size, config.sinkhorn_iters,
78 config.hc_eps, config.norm_eps)
79 self.hc_mult = config.num_stream
80 width = config.hidden_size * config.num_stream
81 count = (config.num_stream + 2) * config.num_stream
82 self.input_norm = (nn.RMSNorm(width, eps=config.norm_eps, dtype=torch.float32)
83 if getattr(config, "use_gamma", True) else _UnweightedRMSNorm(config.norm_eps))
84 self.fn = nn.Parameter(torch.empty(count, width, dtype=torch.float32))
85 self.base = nn.Parameter(torch.empty(count, dtype=torch.float32))
86 self.scale = nn.Parameter(torch.empty(3, dtype=torch.float32))
87 self.hc_sinkhorn_iters, self.hc_eps = config.sinkhorn_iters, config.hc_eps
88 self.reset_parameters()
90 def _adopt_source(self, module: nn.Module) -> None:
91 """Adopt source coefficient matrices and validate stream-divisible mixing dimensions."""
92 required = ("input_norm", "fn", "base", "scale", "hc_mult")
93 missing = [name for name in required if not hasattr(module, name)]
94 if missing:
95 raise TypeError(f"pipelined MHC source is missing required attributes: {missing}")
96 self.input_norm = module.input_norm
97 self.fn = module.fn
98 self.base = module.base
99 self.scale = module.scale
100 if not all(isinstance(value, nn.Parameter) for value in (self.fn, self.base, self.scale)):
101 raise TypeError("pipelined MHC fn/base/scale must be Parameters")
102 self.hc_mult = int(module.hc_mult)
103 self.hc_sinkhorn_iters = int(module.hc_sinkhorn_iters)
104 self.hc_eps = float(module.hc_eps)
105 expected_mix = (self.hc_mult + 2) * self.hc_mult
106 if tuple(self.fn.shape)[0] != expected_mix or self.base.numel() != expected_mix:
107 raise ValueError("pipelined MHC fn/base shapes do not match hc_mult")
108 if self.scale.numel() != 3:
109 raise ValueError("pipelined MHC scale must contain three values")
110 if self.fn.ndim != 2 or self.fn.shape[1] % self.hc_mult:
111 raise ValueError("pipelined MHC fn must be a matrix with stream-divisible input width")
112 _validate_settings(self.hc_mult, self.fn.shape[1] // self.hc_mult,
113 self.hc_sinkhorn_iters, self.hc_eps)
114 self.train(module.training)
117 def reset_parameters(self) -> None:
118 """Initialize direct-build coefficient parameters after materialization."""
119 reset_norm = getattr(self.input_norm, "reset_parameters", None)
120 if callable(reset_norm):
121 reset_norm()
122 nn.init.normal_(self.fn, std=self.init_method_std)
123 nn.init.zeros_(self.base)
124 with torch.no_grad():
125 self.scale.fill_(self.init_scale)
127 def make_transforms(self) -> list:
128 """Declare that this member keeps parameter names and layouts unchanged.
130 Returns:
131 An empty converter list, matching members whose initialization is
132 fully owned by ``reset_parameters``.
133 """
134 return []
136 def forward(
137 self,
138 hidden_streams: torch.Tensor,
139 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
140 """Produce the coefficients consumed by the following sublayer."""
141 flattened = self.input_norm(hidden_streams.flatten(start_dim=2).float())
142 mix = F.linear( # pylint: disable=not-callable
143 flattened, self.fn.float()
144 )
145 num_stream = self.hc_mult
146 pre, post, residual = mix.split(
147 [num_stream, num_stream, num_stream * num_stream], dim=-1
148 )
149 pre_bias, post_bias, residual_bias = self.base.split(
150 [num_stream, num_stream, num_stream * num_stream]
151 )
152 pre_scale, post_scale, residual_scale = self.scale.unbind(0)
153 pre = torch.sigmoid(pre * pre_scale + pre_bias) + self.hc_eps
154 post = 2 * torch.sigmoid(post * post_scale + post_bias)
155 residual = residual.view(*residual.shape[:-1], num_stream, num_stream)
156 residual = residual * residual_scale + residual_bias.view(num_stream, num_stream)
157 residual = sinkhorn_knopps(residual, self.hc_sinkhorn_iters, self.hc_eps)
158 return pre, post, residual
161def pipelined_mhc_post(
162 sublayer_output: torch.Tensor,
163 residual: torch.Tensor,
164 post: torch.Tensor,
165 combine: torch.Tensor,
166) -> torch.Tensor:
167 """Apply mHC post locally and retain the input batch/sequence placements.
169 Args:
170 sublayer_output: Sublayer output with batch/sequence-local rows.
171 residual: Residual streams with replicated stream and feature dimensions.
172 post: Output mixing coefficients with the same batch/sequence layout.
173 combine: Residual mixing matrix with the same batch/sequence layout.
175 Returns:
176 Mixed streams retaining the input batch/sequence DTensor placements.
177 """
178 inputs = (sublayer_output, residual, post, combine)
179 reference = next((value for value in inputs if isinstance(value, DTensor)), None)
180 if reference is not None:
181 # Native bindings return local tensors; keep their reshape and autograd
182 # inside one local boundary before restoring the distributed metadata.
183 sublayer_output, residual, post, combine = (
184 value.to_local() if isinstance(value, DTensor) else value for value in inputs
185 )
186 num_stream = residual.shape[-2]
187 flattened = mhc_post(
188 sublayer_output,
189 residual.flatten(start_dim=2),
190 post,
191 combine,
192 num_stream,
193 )
194 output = flattened.unflatten(-1, (num_stream, residual.shape[-1]))
195 if reference is not None:
196 return DTensor.from_local(output, reference.device_mesh, reference.placements)
197 return output
200class ShiftedPipelinedMhcModule(PipelinedMhcModule):
201 """Advance a pending residual update, next coefficients and next sublayer normalization together."""
203 fp32_parameter_names = ("fn", "base", "scale")
205 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
206 module_fqn: str = "", context: Mapping[str, Any] | None = None,
207 token_tile: int = 32) -> None:
208 """Retain the ordinary coefficient state keys for the shifted training protocol."""
209 super().__init__(config=config, module=module, module_fqn=module_fqn, context=context, token_tile=token_tile)
210 if tuple(self.input_norm.parameters()):
211 raise ValueError("Shifted pipelined mHC requires unweighted coefficient normalization")
212 if self.hc_mult != 4 or self.hc_sinkhorn_iters != 20:
213 raise ValueError("Shifted pipelined mHC requires four streams and twenty Sinkhorn iterations")
214 if isinstance(token_tile, bool) or not isinstance(token_tile, int) or token_tile < 1:
215 raise ValueError("token_tile must be a positive integer")
216 self.token_tile = token_tile
217 self.norm_eps = getattr(self.input_norm, "eps", getattr(self.input_norm, "variance_epsilon", None))
218 if self.norm_eps is None:
219 raise ValueError("Shifted pipelined mHC requires the source normalization epsilon")
221 def _apply(self, fn: Any, recurse: bool = True) -> nn.Module:
222 """Keep coefficient, normalization and gradient storage in FP32 during dtype conversion."""
223 protected = {id(parameter) for parameter in self.parameters()}
224 protected.update(id(parameter.grad) for parameter in self.parameters() if parameter.grad is not None)
226 def preserve(tensor: torch.Tensor) -> torch.Tensor:
227 """Keep protected coefficients in FP32 without a lower-precision round trip."""
228 converted = fn(tensor)
229 if id(tensor) not in protected or converted.dtype == torch.float32:
230 return converted
231 return converted.float() if tensor.is_meta else tensor.to(device=converted.device, dtype=torch.float32)
233 return super()._apply(preserve, recurse=recurse)
235 def advance(self, previous_output: torch.Tensor, residual: torch.Tensor,
236 previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
237 previous_residual_mix: torch.Tensor, norm_weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
238 """Evaluate the source shifted boundary with ordinary differentiable Torch operations."""
239 updated = pipelined_mhc_post(previous_output, residual, previous_post_mix, previous_residual_mix)
240 pre, post, mixing = self(updated)
241 collapsed = (previous_pre_mix.unsqueeze(-1) * updated.float()).sum(dim=2)
242 reciprocal_std = torch.rsqrt(collapsed.square().mean(dim=-1, keepdim=True) + self.norm_eps)
243 block_input = (collapsed * reciprocal_std).to(residual.dtype) * norm_weight
244 return updated, pre, post, mixing, block_input
247class NativeShiftedPipelinedMhcModule(ShiftedPipelinedMhcModule):
248 """Use the native multicore kernel with the same coefficient and external-normalization ownership."""
250 def advance(self, previous_output: torch.Tensor, residual: torch.Tensor,
251 previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
252 previous_residual_mix: torch.Tensor, norm_weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
253 """Execute the selected NPU kernel on local token rows.
255 Args:
256 previous_output: Output of the previous sublayer.
257 residual: Residual streams awaiting the previous post-mix.
258 previous_pre_mix: Coefficients for collapsing updated streams.
259 previous_post_mix: Coefficients for the previous sublayer output.
260 previous_residual_mix: Coefficients for mixing residual streams.
261 norm_weight: Weight of the following sublayer normalization.
263 Returns:
264 Updated residual, next mixing coefficients and normalized block input.
265 """
266 if residual.device.type != "npu":
267 raise ValueError("Native shifted pipelined mHC requires NPU tensors")
268 # The multicore dependency is optional until its execution member is called.
269 from hyper_multicore.modules.mega_mhc.function import hyper_mega_mhc # pylint: disable=import-outside-toplevel
271 inputs = (previous_output, residual, previous_pre_mix, previous_post_mix, previous_residual_mix)
272 reference = next((value for value in inputs if isinstance(value, DTensor)), None)
273 # advance bypasses Module.__call__; keep the native autograd function on
274 # local CP rows while retaining differentiable parameter views.
275 local = tuple(value.to_local() if isinstance(value, DTensor) else value
276 for value in (*inputs, self.fn, self.scale, self.base, norm_weight))
277 output = hyper_mega_mhc(*local[:5], *(value.float() for value in local[5:8]), local[8],
278 hc_eps=self.hc_eps, norm_eps=self.norm_eps,
279 num_iters=self.hc_sinkhorn_iters, token_tile=self.token_tile)
280 if reference is None:
281 return output
282 return tuple(DTensor.from_local(value, reference.device_mesh, reference.placements) for value in output)