Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / common / rotary_embedding.py: 77%
192 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"""Explicit rotary-position mathematics and rebuildable frequency state."""
16from __future__ import annotations
18from math import ceil, floor, isfinite, log, pi
19from typing import Any
21import torch
22from torch import nn
24from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family
25from hyper_parallel.models.materialization import register_rebuildable_buffer
26from hyper_parallel.models.replacement import module_replacement
29def _yarn_frequencies(parameters: dict, dim: int, base: float, factor: float) -> torch.Tensor:
30 """Build the static interpolation/extrapolation blend from its declared rotation range."""
31 original = parameters.get("original_max_position_embeddings")
32 if isinstance(original, bool) or not isinstance(original, int) or original < 1:
33 raise ValueError("YaRN requires positive original_max_position_embeddings")
34 fast, slow = parameters.get("beta_fast") or 32, parameters.get("beta_slow") or 1
35 if fast <= 0 or slow <= 0 or base <= 1:
36 raise ValueError("YaRN requires positive beta values and rope base greater than one")
37 low = dim * log(original / (fast * 2 * pi)) / (2 * log(base))
38 high = dim * log(original / (slow * 2 * pi)) / (2 * log(base))
39 if parameters.get("truncate", True):
40 low, high = floor(low), ceil(high)
41 low, high = max(low, 0), min(high, dim - 1)
42 if low == high:
43 high += 0.001
44 ramp = ((torch.arange(dim // 2, dtype=torch.float32, device="cpu") - low) / (high - low)).clamp(0, 1)
45 extrapolation = 1 - ramp
46 periods = base ** (torch.arange(0, dim, 2, dtype=torch.float32, device="cpu") / dim)
47 return (1.0 / (factor * periods)) * (1 - extrapolation) + (1.0 / periods) * extrapolation
50class RotaryEmbeddingModule(nn.Module):
51 """Return split-half cos/sin; standard, linear and dynamic NTK have distinct validated semantics.
53 Dynamic NTK takes an explicit logical sequence extent. It does not depend on
54 a mutable cache left by a preceding request or checkpoint recomputation.
55 Multi-axis sections select axis frequencies before the split-half duplication.
56 """
58 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
59 output_format: str | None = None, mrope_interleaved: bool | None = None) -> None:
60 """Build from logical config or adopt a supported static source frequency buffer."""
61 super().__init__()
62 if (config is None) == (module is None):
63 raise ValueError("provide exactly one of config or module")
64 self.config = config if module is None else getattr(module, "config", None)
65 source = config if module is None else module
66 self.output_format = (getattr(source, "output_format", "cos_sin")
67 if output_format is None else output_format)
68 if self.output_format not in ("cos_sin", "complex"):
69 raise ValueError("Rotary output_format must be cos_sin or complex")
70 if mrope_interleaved is not None and not isinstance(mrope_interleaved, bool):
71 raise TypeError("mrope_interleaved must be bool or None")
72 if module is not None:
73 self._initialize_source(module, mrope_interleaved=mrope_interleaved)
74 else:
75 self.dim = config.dim
76 self.base = config.base
77 self.factor = config.factor
78 self.rope_type = config.rope_type
79 self.max_position_embeddings = config.max_position_embeddings
80 self.attention_factor = config.attention_factor
81 self.mrope_section = tuple(config.mrope_section)
82 self.mrope_interleaved = (getattr(config, "mrope_interleaved", False)
83 if mrope_interleaved is None else mrope_interleaved)
84 self._validate()
85 target = torch.empty(0).device
86 frequency = self.base ** (-torch.arange(0, self.dim, 2, dtype=torch.float32, device="cpu") / self.dim)
87 if self.rope_type == "linear":
88 frequency = frequency / self.factor
89 elif self.rope_type == "yarn":
90 parameters = getattr(config, "rope_parameters", None)
91 if not parameters:
92 raise ValueError("YaRN direct construction requires explicit rope_parameters")
93 frequency = _yarn_frequencies(parameters, self.dim, self.base, self.factor)
94 register_rebuildable_buffer(self, "inv_freq", value=frequency, persistent=False)
95 self.inv_freq = self.inv_freq.to(target)
96 self._validate()
98 def _initialize_source(self, module: nn.Module, *, mrope_interleaved: bool | None) -> None:
99 """Adopt static frequency buffers and retain their materialization rebuild recipes."""
100 source_config = getattr(module, "config", None)
101 params = getattr(source_config, "rope_parameters", None) or getattr(source_config, "rope_scaling", {}) or {}
102 self.rope_type = getattr(module, "rope_type", params.get("rope_type", "default"))
103 if self.rope_type not in ("default", "linear", "yarn"):
104 raise ValueError("source conversion supports static default/linear/YaRN RoPE; "
105 "dynamic cache needs explicit config")
106 frequency = getattr(module, "inv_freq", None)
107 if not isinstance(frequency, torch.Tensor) or frequency.ndim != 1:
108 raise ValueError("source requires a one-dimensional inv_freq buffer")
109 if any(True for _ in module.parameters()):
110 raise ValueError("parameterized rotary sources require a separate state contract")
111 self.dim = 2 * frequency.numel()
112 self.base = float(params.get("rope_theta", getattr(source_config, "rope_theta", 10000.0)))
113 self.factor = float(params.get("factor", 1.0))
114 self.max_position_embeddings = int(getattr(source_config, "max_position_embeddings", 2048))
115 self.attention_factor = float(getattr(module, "attention_scaling", 1.0))
116 self._set_source_position_layout(module, params, mrope_interleaved)
117 rebuilt = self._rebuild_source_frequency(module, source_config, params, frequency)
118 register_rebuildable_buffer(self, "inv_freq", value=rebuilt, persistent=False)
119 self.inv_freq = frequency
120 original = getattr(module, "original_inv_freq", None)
121 if isinstance(original, torch.Tensor):
122 if original.shape != frequency.shape:
123 raise ValueError("original rotary frequency shape must match inv_freq")
124 value = rebuilt.clone() if original.is_meta else original.detach().cpu()
125 register_rebuildable_buffer(self, "original_inv_freq", value=value, persistent=False)
126 self.original_inv_freq = original
127 self.train(module.training)
129 def _set_source_position_layout(self, module: nn.Module, params: dict,
130 mrope_interleaved: bool | None) -> None:
131 """Require an explicit axis-selection contract before adopting multimodal positions."""
132 self.mrope_section = tuple(getattr(module, "mrope_section", params.get("mrope_section", ())))
133 source_interleaved = getattr(module, "mrope_interleaved", params.get("mrope_interleaved"))
134 if mrope_interleaved is None:
135 mrope_interleaved = source_interleaved
136 if self.mrope_section and mrope_interleaved is None:
137 raise ValueError("multi-axis source requires an explicit mrope_interleaved contract")
138 if mrope_interleaved is not None and not isinstance(mrope_interleaved, bool):
139 raise TypeError("mrope_interleaved must be bool or None")
140 self.mrope_interleaved = False if mrope_interleaved is None else mrope_interleaved
142 def _rebuild_source_frequency(self, module: nn.Module, source_config: Any, params: dict,
143 frequency: torch.Tensor) -> torch.Tensor:
144 """Reconstruct only meta frequencies with the audited source arithmetic order."""
145 if frequency.is_meta:
146 if isinstance(module, RotaryEmbeddingModule):
147 rebuilt = self.base ** (-torch.arange(0, self.dim, 2, device="cpu").float() / self.dim)
148 elif callable(getattr(module, "compute_default_rope_parameters", None)):
149 with torch.device("cpu"):
150 rebuilt, _ = module.compute_default_rope_parameters(source_config, device="cpu")
151 if rebuilt.is_meta or rebuilt.shape != frequency.shape:
152 raise ValueError("source static rotary builder must produce the declared CPU frequency shape")
153 rebuilt = rebuilt.detach().cpu()
154 else:
155 raise ValueError("meta rotary source must declare a supported frequency construction contract")
156 if self.rope_type == "linear":
157 rebuilt = rebuilt / self.factor
158 elif self.rope_type == "yarn":
159 rebuilt = _yarn_frequencies(params, self.dim, self.base, self.factor)
160 else:
161 rebuilt = frequency.detach().cpu()
162 return rebuilt
165 @staticmethod
167 def compute_default_rope_parameters(config: Any, **kwargs: Any) -> tuple[torch.Tensor, float]:
168 """Expose the static HF initialization protocol using component-owned math."""
169 del kwargs
170 params = getattr(config, "rope_parameters", None) or getattr(config, "rope_scaling", None) or {}
171 dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
172 dim = int(dim * params.get("partial_rotary_factor", 1.0))
173 base = params.get("rope_theta", getattr(config, "rope_theta", 10000.0))
174 frequency = 1.0 / (base ** (torch.arange(0, dim, 2, device="cpu").float() / dim))
175 return frequency, 1.0
177 def _validate(self) -> None:
178 """Validate supported frequency and position layouts before execution."""
179 if isinstance(self.dim, bool) or not isinstance(self.dim, int) or self.dim < 2 or self.dim % 2:
180 raise ValueError("rotary dim must be a positive even integer")
181 if self.rope_type not in ("default", "linear", "dynamic", "yarn"):
182 raise ValueError("supported rope_type values are default, linear, dynamic and yarn")
183 for name in ("base", "factor", "attention_factor"):
184 value = getattr(self, name)
185 if isinstance(value, bool) or not isinstance(value, (float, int)) or not isfinite(value) or value <= 0:
186 raise ValueError(f"{name} must be finite and positive")
187 if (isinstance(self.max_position_embeddings, bool)
188 or not isinstance(self.max_position_embeddings, int) or self.max_position_embeddings < 1):
189 raise ValueError("max_position_embeddings must be positive")
190 if self.output_format not in ("cos_sin", "complex"):
191 raise ValueError("Rotary output_format must be cos_sin or complex")
192 self._validate_position_layout()
194 def _validate_position_layout(self) -> None:
195 """Validate dynamic NTK extent constraints and multi-axis section coverage."""
196 if self.rope_type == "dynamic" and (self.dim <= 2 or self.factor < 1):
197 raise ValueError("dynamic NTK requires dim > 2 and factor >= 1")
198 if not isinstance(self.mrope_interleaved, bool):
199 raise ValueError("mrope_interleaved must be boolean")
200 if self.mrope_interleaved and len(self.mrope_section) != 3:
201 raise ValueError("interleaved multimodal RoPE requires three axis sections")
202 if self.mrope_section and (
203 any(isinstance(x, bool) or not isinstance(x, int) or x < 1 for x in self.mrope_section)
204 or sum(self.mrope_section) != self.dim // 2):
205 raise ValueError("mrope_section must partition the half-dimension into positive axis sections")
207 def _apply(self, fn: Any, recurse: bool = True) -> RotaryEmbeddingModule:
208 # Frequencies must not be rounded by model-wide BF16 conversion.
209 original = self.inv_freq
210 super()._apply(fn, recurse=recurse)
211 converted = self.inv_freq
212 if converted.dtype != torch.float32:
213 self.inv_freq = (converted.float() if original.is_meta
214 else original.to(device=converted.device, dtype=torch.float32))
215 return self
217 @torch.no_grad()
219 def forward(self, x: torch.Tensor, position_ids: torch.Tensor,
220 *, sequence_length: int | None = None) -> tuple[torch.Tensor, torch.Tensor]:
221 """Return cos/sin in x.dtype for [B,S] or explicitly sectioned [axes,B,S] positions.
223 Args:
224 x: Activation supplying output device and dtype.
225 position_ids: Actual logical positions, including caller-owned packed offsets.
226 sequence_length: Required global context extent for dynamic NTK; no host read of device positions.
228 Returns:
229 Cosine and sine tensors shaped [B,S,dim].
230 """
231 if position_ids.device != x.device or self.inv_freq.device != x.device:
232 raise ValueError("rotary buffers, positions and activations must share a device")
233 frequency = self.inv_freq.float()
234 if self.rope_type == "dynamic":
235 if isinstance(sequence_length, bool) or not isinstance(sequence_length, int) or sequence_length < 1:
236 raise ValueError("dynamic NTK requires explicit positive sequence_length")
237 extent = max(sequence_length, self.max_position_embeddings)
238 adjusted = self.base * (
239 self.factor * extent / self.max_position_embeddings - (self.factor - 1)
240 ) ** (self.dim / (self.dim - 2))
241 frequency = adjusted ** (-torch.arange(0, self.dim, 2, device=x.device).float() / self.dim)
242 # Explicit elementwise FP32 multiplication is unaffected by GEMM autocast.
243 if self.mrope_interleaved and position_ids.ndim == 2:
244 position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
245 angles = position_ids.float().unsqueeze(-1) * frequency
246 if position_ids.ndim == 3 and self.mrope_section:
247 angles = self._merge_position_axes(angles)
248 elif position_ids.ndim != 2 or self.mrope_section:
249 raise ValueError("positions must be [B,S], or sectioned [axes,B,S] with mrope_section")
250 if self.output_format == "complex":
251 return torch.polar(torch.ones_like(angles), angles) * self.attention_factor
252 embedding = torch.cat((angles, angles), dim=-1)
253 return ((embedding.cos() * self.attention_factor).to(x.dtype),
254 (embedding.sin() * self.attention_factor).to(x.dtype))
257 def _merge_position_axes(self, angles: torch.Tensor) -> torch.Tensor:
258 """Select source-declared axis sections before duplicating rotary channels."""
259 if angles.shape[0] != len(self.mrope_section):
260 raise ValueError("position axes must match mrope_section")
261 if self.mrope_interleaved:
262 merged = angles[0].clone()
263 for axis in (1, 2):
264 indices = slice(axis, self.mrope_section[axis] * 3, 3)
265 merged[..., indices] = angles[axis, ..., indices]
266 return merged
267 sections = angles.split(self.mrope_section, dim=-1)
268 return torch.cat([section[axis] for axis, section in enumerate(sections)], dim=-1)
271@module_replacement
272def RotaryEmbedding( # pylint: disable=invalid-name
273 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
274 context: Any = None, mesh: Any = None, output_format: str | None = None,
275 mrope_interleaved: bool | None = None,
276) -> nn.Module:
277 """Construct rotary math with explicit output and multi-axis layout contracts.
279 Args:
280 config: Logical settings for direct construction, exclusive with module.
281 module: Source frequencies and state to adopt.
282 module_fqn: Replacement scope supplied by the framework.
283 context: Family construction context.
284 mesh: Existing job mesh.
285 output_format: Complex factors or cos/sin; None retains declared source metadata.
286 mrope_interleaved: Interleaved multi-axis channels; sectioned sources must declare their layout.
287 """
288 return build_family(RotaryEmbedding, config=config, module=module, module_fqn=module_fqn,
289 context=context, mesh=mesh, output_format=output_format,
290 mrope_interleaved=mrope_interleaved)
293register_module_family(ModuleFamily(
294 name="rotary_embedding", baseline=RotaryEmbedding,
295 variants={"local": "hyper_parallel.components.modules.common.rotary_embedding.RotaryEmbeddingModule"},
296 default_variant="local",
297))