Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / rope.py: 73%
63 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"""Half and interleaved rotary position embedding contracts."""
17from collections.abc import Callable
18from typing import Protocol
20import torch
22from .._dependency import require_package, require_symbol
23from ..registry import OpRegistry
24from ..spec import OpSpec
27class RopeFn(Protocol):
28 """Rotate a tensor with broadcast-ready cosine and sine tensors."""
30 def __call__(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
31 """Rotate the prefix of x covered by the frequencies and retain the tail."""
34class InterleavedRopeFn(Protocol):
35 """Rotate adjacent pairs using the Transformers interleaved RoPE layout."""
37 def __call__(
38 self, x: torch.Tensor, key: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
39 *, unsqueeze_dim: int = 1,
40 ) -> tuple[torch.Tensor, torch.Tensor]:
41 """Return query and key with their rotated pairs laid out as two halves."""
44ROPE = OpSpec[RopeFn](config_key="rope", variant="half")
45ROPE_INTERLEAVED = OpSpec[InterleavedRopeFn](config_key="rope", variant="interleaved")
48def _rotate_prefix(
49 x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
50 rotation: Callable[[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor],
51) -> torch.Tensor:
52 """Rotate the frequency-covered prefix and preserve the remaining head dimensions."""
53 rotary_dim = cos.shape[-1]
54 if rotary_dim != sin.shape[-1] or rotary_dim > x.shape[-1] or rotary_dim % 2:
55 raise ValueError("RoPE requires matching, even frequency dimensions within the input head dimension")
56 if rotary_dim == x.shape[-1]:
57 return rotation(x, cos, sin)
58 prefix, tail = x.split((rotary_dim, x.shape[-1] - rotary_dim), dim=-1)
59 return torch.cat((rotation(prefix, cos, sin), tail), dim=-1)
62def _half(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
63 first, second = x.chunk(2, dim=-1)
64 return x * cos + torch.cat((-second, first), dim=-1) * sin
67def _native(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
68 return _rotate_prefix(x, cos, sin, _half) if cos.shape[-1] else x
71def _rotate_adjacent(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
72 even, odd = x.unflatten(-1, (-1, 2)).unbind(-1)
73 return torch.cat((even * cos - odd * sin, odd * cos + even * sin), dim=-1)
76def _native_interleaved(
77 x: torch.Tensor, key: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, *, unsqueeze_dim: int = 1,
78) -> tuple[torch.Tensor, torch.Tensor]:
79 """Rotate adjacent Q/K pairs and return the canonical split-half layout."""
80 if unsqueeze_dim not in (1, 2):
81 raise ValueError("Interleaved RoPE supports unsqueeze_dim 1 or 2")
82 if cos.ndim == 2:
83 cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
84 rotary_dim = cos.shape[-1]
85 if rotary_dim != sin.shape[-1] or rotary_dim % 2 or rotary_dim > min(x.shape[-1], key.shape[-1]):
86 raise ValueError("RoPE requires matching, even frequency dimensions within the input head dimension")
87 if not rotary_dim:
88 return x, key
89 cos = cos[..., : rotary_dim // 2].unsqueeze(unsqueeze_dim)
90 sin = sin[..., : rotary_dim // 2].unsqueeze(unsqueeze_dim)
91 return tuple(
92 torch.cat((_rotate_adjacent(tensor[..., :rotary_dim], cos, sin), tensor[..., rotary_dim:]), dim=-1)
93 for tensor in (x, key)
94 )
97def _load_npu() -> RopeFn:
98 """Load the NPU half-layout rotary embedding adapter."""
99 extension = require_package("torch_npu")
100 require_symbol(extension, "npu_rotary_mul")
102 def half(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
103 """Rotate a contiguous prefix with the NPU half-layout kernel."""
104 return extension.npu_rotary_mul(x.contiguous(), cos, sin, rotary_mode="half")
106 def run(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
107 """Apply the selected rotation while preserving the unrotated tail."""
108 return _rotate_prefix(x, cos, sin, half) if cos.shape[-1] else x
110 return run
113def _load_npu_interleaved() -> InterleavedRopeFn:
114 """Load the optional NPU adjacent-pair rotary embedding adapter."""
115 require_symbol(require_package("torch_npu"), "npu_rotary_mul")
116 # The existing pair-layout adapter imports the optional NPU extension.
117 from hyper_parallel.components.functional.rotary_embedding import ( # pylint: disable=import-outside-toplevel
118 apply_rotary_pos_emb_interleave,
119 )
121 def run(
122 x: torch.Tensor, key: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, *, unsqueeze_dim: int = 1,
123 ) -> tuple[torch.Tensor, torch.Tensor]:
124 """Apply the selected rotation while preserving the unrotated tail."""
125 if not cos.shape[-1]:
126 return x, key
127 return apply_rotary_pos_emb_interleave(x, key, cos, sin, unsqueeze_dim=unsqueeze_dim)
129 return run
132def register_rope(registry: OpRegistry) -> None:
133 """Register half, interleaved and partial rotation on compatible devices."""
134 registry.register_family("rope", specs=(ROPE, ROPE_INTERLEAVED))
135 registry.register_impl(ROPE, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native)
136 registry.register_impl(
137 ROPE_INTERLEAVED, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_interleaved,
138 )
139 registry.register_impl(ROPE, name="torch_npu", devices=("npu",), load=_load_npu)
140 registry.register_impl(ROPE_INTERLEAVED, name="torch_npu", devices=("npu",), load=_load_npu_interleaved)