"""Interleaved rotary positions and learned, normalized query/key scales.""" from __future__ import annotations import math import torch from torch import nn class RotaryEmbedding(nn.Module): def __init__(self, head_dim: int) -> None: super().__init__() self.head_dim = head_dim # Explicit CPU construction keeps this nonpersistent buffer materialized # during meta-device checkpoint loading. It moves with the model. inv_freq = 1.0 / ( 10_000.0 ** (torch.arange(0, head_dim, 2, device="cpu", dtype=torch.float32) / head_dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False) def cache(self, positions, *, dtype, device): resolved_positions = positions.to(device=device).reshape(-1) pos_idx = resolved_positions.to(dtype=torch.long) freqs = torch.outer(pos_idx.to(dtype=torch.float32), self.inv_freq.to(device=device)) return ( torch.repeat_interleave(freqs.cos(), 2, dim=-1).to(dtype=dtype).unsqueeze(1), torch.repeat_interleave(freqs.sin(), 2, dim=-1).to(dtype=dtype).unsqueeze(1), ) def forward(self, values: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: cosine, sine = self.cache(positions, dtype=values.dtype, device=values.device) return (values * cosine) + (rotate_half(values) * sine) def apply_pair(self, query, key, positions): cosine, sine = self.cache(positions, dtype=query.dtype, device=query.device) return (query * cosine) + (rotate_half(query) * sine), (key * cosine) + ( rotate_half(key) * sine ) def rotate_half(values: torch.Tensor) -> torch.Tensor: first, second = values[..., ::2], values[..., 1::2] return torch.stack((-second, first), dim=-1).flatten(start_dim=-2) def normalize_key(values: torch.Tensor, eps: float) -> torch.Tensor: source = values.float() denominator = source.norm(p=2, dim=-1, keepdim=True).clamp_min(float(eps)) return (source / denominator).to(values.dtype) def normalize_query( values: torch.Tensor, log_scale: torch.Tensor, head_dim: int, eps: float ) -> torch.Tensor: unit = normalize_key(values, eps) scale = ( log_scale.float() .exp() .to(device=values.device, dtype=values.dtype) .view(1, int(values.size(-2)), 1) ) multiplier = math.sqrt(float(head_dim)) return unit * scale * multiplier