Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / gated_residual.py: 56%
106 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"""Gated Residual formulas with eager and optional CANN implementations."""
17import importlib
18from collections.abc import Callable
19from math import isfinite
21import torch
22import torch.nn.functional as F
25_BACKEND_ALIASES = {
26 "eager": "eager",
27 "torch": "eager",
28 "ascendc": "ascendc",
29 "cann": "ascendc",
30}
33def _validate_input_layout(x: torch.Tensor, channels: int) -> None:
34 """Validate the input layout needed by the Python dispatcher."""
35 if x.ndim < 1:
36 raise ValueError("Gated Residual input must have at least one dimension")
37 if isinstance(channels, bool) or not isinstance(channels, int) or channels <= 0:
38 raise ValueError("Gated Residual channels must be a positive integer")
39 if x.shape[-1] % channels:
40 raise ValueError("Gated Residual input width must be divisible by channels")
43def _validate_eps(eps: float) -> None:
44 """Validate epsilon for the eager and empty-input paths."""
45 if isinstance(eps, bool) or not isinstance(eps, (int, float)) or not isfinite(eps) or eps <= 0:
46 raise ValueError("Gated Residual eps must be finite and positive")
49def _validate_projection_shapes(
50 x: torch.Tensor,
51 w_down: torch.Tensor,
52 w_up: torch.Tensor,
53 w_gate: torch.Tensor | None,
54 gamma: torch.Tensor | None,
55 channels: int,
56) -> None:
57 """Validate projection and optional parameter shapes."""
58 hidden_size = x.shape[-1]
59 if w_down.ndim != 2 or w_down.shape[1] != hidden_size:
60 raise ValueError("Gated Residual w_down must have shape [rank, input_width]")
61 if w_up.ndim != 2 or tuple(w_up.shape) != (hidden_size, w_down.shape[0]):
62 raise ValueError("Gated Residual w_up must have shape [input_width, rank]")
63 if w_gate is not None and (w_gate.ndim != 2 or tuple(w_gate.shape) != (channels, hidden_size)):
64 raise ValueError("Gated Residual w_gate must have shape [channels, input_width]")
65 if gamma is not None and (gamma.ndim != 1 or gamma.shape[0] != hidden_size):
66 raise ValueError("Gated Residual gamma must have shape [input_width]")
69def _empty_result(
70 x: torch.Tensor,
71 w_down: torch.Tensor,
72 w_up: torch.Tensor,
73 w_gate: torch.Tensor | None,
74 gamma: torch.Tensor | None,
75 channels: int,
76) -> tuple[torch.Tensor, torch.Tensor | None]:
77 """Return shape-correct empty results while retaining all gradient edges."""
78 hidden_size = x.shape[-1] // channels
79 zero = x.reshape(-1)[:0].sum()
80 for tensor in (w_down, w_up, w_gate, gamma):
81 if tensor is not None:
82 zero = zero + tensor.reshape(-1)[:0].sum().to(dtype=zero.dtype)
83 mixed = x[..., :hidden_size].to(dtype=x.dtype) + zero.to(dtype=x.dtype)
84 if w_gate is None:
85 return mixed, None
86 injection = x[..., :channels].to(dtype=x.dtype) + zero.to(dtype=x.dtype)
87 return mixed, injection
90def _gated_residual_eager(
91 x: torch.Tensor,
92 w_down: torch.Tensor,
93 w_up: torch.Tensor,
94 w_gate: torch.Tensor | None,
95 gamma: torch.Tensor | None,
96 channels: int,
97 eps: float,
98) -> tuple[torch.Tensor, torch.Tensor | None]:
99 """Evaluate the Gated Residual formula with Torch operators."""
100 hidden_size = x.shape[-1] // channels
101 values = x.float().unflatten(-1, (channels, hidden_size))
102 normalized = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + eps)
103 if gamma is not None:
104 normalized = normalized * (1.0 + gamma.float().unflatten(-1, (channels, hidden_size)))
105 flattened = normalized.flatten(-2)
106 lowrank = F.silu(F.linear(flattened, w_down.float()) / channels)
107 gate = torch.sigmoid(F.linear(lowrank, w_up.float()))
108 mixed = (gate.unflatten(-1, (channels, hidden_size)) * normalized).mean(dim=-2).to(dtype=x.dtype)
109 if w_gate is None:
110 return mixed, None
111 injection = (2.0 * torch.sigmoid(F.linear(flattened, w_gate.float()) / channels)).to(dtype=x.dtype)
112 return mixed, injection
115def _load_text_gated_residual() -> Callable:
116 """Load the optional differentiable ops-transformer Python entry point."""
117 errors = []
118 for package_name in ("cann_ops_transformer", "cann_ops_transformer_custom"):
119 try:
120 module = importlib.import_module(f"{package_name}.ops.mhc.text_gated_residual")
121 except (ImportError, OSError) as error:
122 errors.append(f"{package_name}.ops.mhc.text_gated_residual: {error}")
123 continue
124 operator = getattr(module, "text_gated_residual", None)
125 if callable(operator):
126 return operator
127 errors.append(f"{module.__name__}: text_gated_residual is not exported")
128 detail = "; ".join(errors)
129 raise ImportError(
130 "Gated Residual backend='ascendc' requires the ops-transformer differentiable "
131 "text_gated_residual Python wrapper and matching native forward/backward kernels. Install the matching "
132 f"standalone package. Import details: {detail}"
133 )
136def _gated_residual_fused(
137 x: torch.Tensor,
138 w_down: torch.Tensor,
139 w_up: torch.Tensor,
140 w_gate: torch.Tensor | None,
141 gamma: torch.Tensor | None,
142 channels: int,
143 eps: float,
144) -> tuple[torch.Tensor, torch.Tensor | None]:
145 """Invoke the differentiable ops-transformer TextGatedResidual API."""
146 operator = _load_text_gated_residual()
147 output_shape = tuple(x.shape[:-1])
148 hidden_size = x.shape[-1] // channels
149 # The native API takes [B, S, D]. Flatten arbitrary leading token axes while
150 # preserving differentiable reshape edges back to the model's layout.
151 native_x = x.reshape(1, -1, x.shape[-1]).contiguous()
152 native_dtype = native_x.dtype
153 native_down = w_down.to(dtype=native_dtype).contiguous()
154 native_up = w_up.to(dtype=native_dtype).contiguous()
155 native_gate = None if w_gate is None else w_gate.to(dtype=native_dtype).contiguous()
156 native_gamma = None if gamma is None else gamma.float().contiguous()
157 result = operator(
158 native_x,
159 native_down,
160 native_up,
161 w_gate=native_gate,
162 channels=channels,
163 gamma=native_gamma,
164 eps=eps,
165 )
166 if w_gate is None:
167 mixed = result
168 injection = None
169 else:
170 if not isinstance(result, tuple) or len(result) != 2:
171 raise RuntimeError("TextGatedResidual must return (mixed, inject) when w_gate is provided")
172 mixed, injection = result
173 mixed = mixed.reshape(output_shape + (hidden_size,))
174 if injection is not None:
175 injection = injection.reshape(output_shape + (channels,))
176 return mixed, injection
179def gated_residual(
180 x: torch.Tensor,
181 w_down: torch.Tensor,
182 w_up: torch.Tensor,
183 w_gate: torch.Tensor | None = None,
184 *,
185 channels: int = 4,
186 gamma: torch.Tensor | None = None,
187 eps: float = 1e-6,
188 backend: str = "eager",
189) -> tuple[torch.Tensor, torch.Tensor | None]:
190 """Run Gated Residual with eager Torch or the CANN fused implementation.
192 Args:
193 x: Residual state with final width ``channels * hidden_size``.
194 w_down: Low-rank down projection with shape ``[rank, channels * hidden_size]``.
195 w_up: Low-rank up projection with shape ``[channels * hidden_size, rank]``.
196 w_gate: Optional write-gate projection with shape ``[channels, channels * hidden_size]``.
197 channels: Number of residual branches.
198 gamma: Optional zero-centered RMSNorm scale. The effective scale is ``1 + gamma``.
199 eps: RMSNorm epsilon.
200 backend: ``eager``/``torch`` or ``ascendc``/``cann``.
202 Returns:
203 A pair ``(mixed, injection)``. ``injection`` is ``None`` when ``w_gate`` is absent.
205 Raises:
206 ImportError: The selected native backend is unavailable or lacks its training API.
207 ValueError: The backend or input layout is invalid.
208 """
209 try:
210 resolved_backend = _BACKEND_ALIASES[backend]
211 except (KeyError, TypeError) as error:
212 raise ValueError("Gated Residual backend must be eager or ascendc") from error
214 _validate_input_layout(x, channels)
215 if x.numel() == 0 or any(size == 0 for size in x.shape[:-1]):
216 # The native kernel is skipped for empty inputs, so validate the complete
217 # eager contract here rather than relying on CANN's operator checks.
218 _validate_eps(eps)
219 _validate_projection_shapes(x, w_down, w_up, w_gate, gamma, channels)
220 return _empty_result(x, w_down, w_up, w_gate, gamma, channels)
221 if resolved_backend == "eager":
222 _validate_eps(eps)
223 _validate_projection_shapes(x, w_down, w_up, w_gate, gamma, channels)
224 return _gated_residual_eager(x, w_down, w_up, w_gate, gamma, channels, eps)
225 if x.device.type != "npu":
226 raise ValueError("Gated Residual backend='ascendc' requires NPU tensors")
227 if x.dtype not in (torch.float16, torch.bfloat16):
228 raise ValueError("Gated Residual backend='ascendc' supports float16 or bfloat16 inputs")
229 # For nonempty AscendC calls, CANN validates projection shapes, optional
230 # inputs, dtypes and epsilon. Keep only the checks needed before Python
231 # reshaping and backend dispatch above.
232 return _gated_residual_fused(x, w_down, w_up, w_gate, gamma, channels, eps)
235__all__ = ["gated_residual"]