j3pa-tiny / rope.py
paunas's picture
Upload model
8b003e4 verified
Raw History Blame Contribute Delete
1.79 kB
# (c) Copyright 2026 Zenseact AB
"""Rotary Positional Embeddings (RoPE) of the encoder's attention layers.
Generic N-dimensional extension of the RoFormer paper https://arxiv.org/abs/2104.09864. We only build the angles and
lookup tables for interleaving here and do not provide any forward pass. The provided Triton kernels take care of that.
"""
import math
import torch
from torch import nn
class RoPE(nn.Module):
"""Per-head RoPE: the channel pairs of every head rotate with angles of the x, y and z positions in turn."""
def __init__(self, dim: int, pos_dim: int, max_freq: float, num_heads: int):
"""Initialize.
Args:
dim: Channels of all heads together. The channels of each head are rotated in pairs.
pos_dim: Dimensionality of the positions.
max_freq: Maximum frequency for producing angles.
num_heads: Number of attention heads.
"""
assert dim % 2 == 0
super().__init__()
self._pos_dim = pos_dim
self._dim = dim
dh = dim // num_heads
angles_per_axis = int(math.ceil(dh / (2 * pos_dim)) * num_heads)
angles = max_freq ** (-2 * torch.arange(angles_per_axis) / (dim / pos_dim))
head_idx = torch.arange(dim) // dh
pair_idx = (torch.arange(dim) % dh) // 2
angle_idx = (pair_idx // pos_dim) * num_heads + head_idx
pos_idx = (pair_idx + head_idx) % pos_dim
# Persistent, so they are loaded from the checkpoints: computed on other hardware they coulc differ from what the model was trained on.
# Probably doesn't matter, but why risk it...
self.register_buffer("_angles", angles)
self.register_buffer("_angle_idx", angle_idx)
self.register_buffer("_pos_idx", pos_idx)