File size: 1,787 Bytes
8b003e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# (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)