Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mhc / mega_mhc.py: 87%
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"""Four-stream shifted mHC boundary with ordinary and multicore execution."""
16from __future__ import annotations
18from math import isfinite
19from typing import Any
21import torch
22from torch import nn
26class MegaMhcModule(nn.Module):
27 """Own predictors and input normalization; advance the complete shifted boundary."""
29 def __init__(self, *, config: Any = None, module: nn.Module | None = None) -> None:
30 """Initialize logical settings or retain compatible source Parameters."""
31 super().__init__()
32 if (config is None) == (module is None):
33 raise ValueError("provide exactly one of config or module")
34 source = config if config is not None else module
35 self._set_settings(source)
36 shapes = {"phi": (24, 4 * self.hidden_size), "alpha": (3,), "bias": (24,),
37 "norm_weight": (self.hidden_size,)}
38 for name, shape in shapes.items():
39 dtype = torch.bfloat16 if name == "norm_weight" else torch.float32
40 if module is None:
41 parameter = nn.Parameter(torch.empty(shape, dtype=dtype))
42 else:
43 parameter = getattr(module, name, None)
44 if (not isinstance(parameter, nn.Parameter) or tuple(parameter.shape) != shape
45 or parameter.dtype != dtype):
46 raise ValueError(f"source {name} must have shape {shape} and dtype {dtype}")
47 setattr(self, name, parameter)
48 if len({parameter.device for parameter in self.parameters()}) != 1:
49 raise ValueError("MegaMhc parameters must share a device")
50 if module is None:
51 self.reset_parameters()
52 else:
53 self.train(module.training)
55 def _set_settings(self, source: Any) -> None:
56 """Validate and retain dimensions, normalization and tiling settings."""
57 for name in ("hidden_size", "num_iters"):
58 value = getattr(source, name)
59 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
60 raise ValueError(f"{name} must be a positive integer")
61 setattr(self, name, value)
62 for name in ("hc_eps", "norm_eps"):
63 value = getattr(source, name)
64 if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value <= 0:
65 raise ValueError(f"{name} must be finite and positive")
66 setattr(self, name, value)
67 self.token_tile = getattr(source, "token_tile", 32)
68 if isinstance(self.token_tile, bool) or not isinstance(self.token_tile, int) or self.token_tile < 1:
69 raise ValueError("token_tile must be a positive integer")
71 def reset_parameters(self) -> None:
72 """Restore predictor and normalization initialization after materialization."""
73 nn.init.normal_(self.phi, std=(4 * self.hidden_size) ** -0.5)
74 nn.init.ones_(self.alpha)
75 nn.init.zeros_(self.bias)
76 nn.init.ones_(self.norm_weight)
78 def make_transforms(self) -> list:
79 """Declare that this member keeps parameter names and layouts unchanged.
81 Returns:
82 An empty converter list, matching members whose initialization is
83 fully owned by ``reset_parameters``.
84 """
85 return []
87 def _apply(self, fn: Any, recurse: bool = True) -> MegaMhcModule:
88 """Preserve declared FP32 parameters and gradients during conversion."""
89 # The predictor uses FP32 even when the enclosing model uses BF16.
90 protected = {id(getattr(self, name)) for name in ("phi", "alpha", "bias")}
91 protected.update(id(parameter.grad) for parameter in self.parameters() if parameter.grad is not None
92 and id(parameter) in protected)
94 def apply(tensor: torch.Tensor) -> torch.Tensor:
95 converted = fn(tensor)
96 if id(tensor) not in protected or converted.dtype == torch.float32:
97 return converted
98 return converted.float() if tensor.is_meta else tensor.to(device=converted.device, dtype=torch.float32)
100 return super()._apply(apply, recurse=recurse)
102 def forward(self, previous_output: torch.Tensor, residual: torch.Tensor,
103 previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
104 previous_residual_mix: torch.Tensor) -> tuple[torch.Tensor, ...]:
105 """Return residual, three next mappings and normalized next-block input."""
106 if residual.shape[-2:] != (4, self.hidden_size):
107 raise ValueError("residual must end in [4, hidden_size]")
108 prefix = residual.shape[:-2]
109 expected = ((previous_output, (*prefix, self.hidden_size)), (previous_pre_mix, (*prefix, 4)),
110 (previous_post_mix, (*prefix, 4)), (previous_residual_mix, (*prefix, 4, 4)))
111 if any(tuple(value.shape) != shape for value, shape in expected):
112 raise ValueError("shifted boundary tensors must share the same token dimensions")
113 updated = (torch.einsum("...ji,...jh->...ih", previous_residual_mix.float(), residual.float())
114 + previous_post_mix.float().unsqueeze(-1) * previous_output.float().unsqueeze(-2)).to(residual.dtype)
115 updated_fp32 = updated.float()
116 variance = updated_fp32.square().mean((-2, -1), keepdim=True)
117 normalized = updated_fp32 * torch.rsqrt(variance + self.norm_eps)
118 logits = normalized.flatten(-2) @ self.phi.float().T
119 pre, post, mixing = logits.split((4, 4, 16), dim=-1)
120 pre_bias, post_bias, mixing_bias = self.bias.float().split((4, 4, 16))
121 pre = torch.sigmoid(pre * self.alpha[0] + pre_bias) + self.hc_eps
122 post = 2 * torch.sigmoid(post * self.alpha[1] + post_bias)
123 mixing = (mixing * self.alpha[2] + mixing_bias).reshape(*prefix, 4, 4).softmax(-1) + self.hc_eps
124 mixing = mixing / (mixing.sum(-2, keepdim=True) + self.hc_eps)
125 for _ in range(self.num_iters - 1):
126 mixing = mixing / (mixing.sum(-1, keepdim=True) + self.hc_eps)
127 mixing = mixing / (mixing.sum(-2, keepdim=True) + self.hc_eps)
128 block_input = (updated.float() * previous_pre_mix.float().unsqueeze(-1)).sum(-2)
129 block_input = block_input * torch.rsqrt(block_input.square().mean(-1, keepdim=True) + self.norm_eps)
130 block_input = (block_input * self.norm_weight.float()).to(residual.dtype)
131 return updated, pre, post, mixing, block_input
134class FusedMegaMhcModule(MegaMhcModule):
135 """Execute the existing multicore kernel with its unchanged native contract."""
137 def __init__(self, *, config: Any = None, module: nn.Module | None = None) -> None:
138 """Validate native training dimensions and fixed Sinkhorn iterations before execution."""
139 source = config if config is not None else module
140 if source is not None:
141 # The optional native package owns its supported training dimensions.
142 from hyper_multicore.modules.mega_mhc_common import ( # pylint: disable=import-outside-toplevel
143 validate_mega_mhc_hidden_size,
144 )
145 validate_mega_mhc_hidden_size(source.hidden_size, need_backward=True)
146 if source.num_iters != 20:
147 raise ValueError("fused MegaMhc requires num_iters=20")
148 super().__init__(config=config, module=module)
150 def forward(self, previous_output: torch.Tensor, residual: torch.Tensor,
151 previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
152 previous_residual_mix: torch.Tensor) -> tuple[torch.Tensor, ...]:
153 """Delegate native shape/dtype validation and execution to multicore."""
154 # Native operators are optional and loaded only when fused execution is requested.
155 from hyper_multicore.modules.mega_mhc.function import hyper_mega_mhc # pylint: disable=C0415
156 return hyper_mega_mhc(previous_output, residual, previous_pre_mix, previous_post_mix,
157 previous_residual_mix, self.phi, self.alpha, self.bias, self.norm_weight,
158 hc_eps=self.hc_eps, norm_eps=self.norm_eps, num_iters=self.num_iters,
159 token_tile=self.token_tile)