PyTorch
Nebulon33's picture
Upload 84 files
bd992b7 verified
Raw History Blame Contribute Delete
2.34 kB
import torch
import torch.nn as nn
"""
A standard RoPE implementation
"""
class RoPE(nn.Module):
def __init__(
self,
d_k: int,
n_ctx: int = 2048,
base: float = 10000.0
):
"""
d_k (int): The amount of values in a single q or k tensor.
n_ctx (int): Maximum amount of context to configure RoPE for.
"""
super().__init__()
# The values of theta for each embed
# Shape of (d_k // 2,)
inv_freq = 1.0 / (base ** (torch.arange(0, d_k, 2).float() / d_k))
# Token num range to multiply by
# Shape of (n_ctx,)
t = torch.arange(n_ctx).float()
# For each token, multiply the theta value by the index
# Consecutive tokens get a consistent rotation difference
# Shape of (n_ctx, d_k // 2)
freqs = torch.outer(t, inv_freq)
# Slightly more cache efficient to use pairs over the halves instead of consecutive
# Shape of (n_ctx, d_k)
emb = torch.cat([freqs, freqs], dim=-1)
self.register_buffer('cos_cached', emb.cos())
self.register_buffer('sin_cached', emb.sin())
def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
"""
Split last dim of tensor into halves x1, x2, then rejoins them in order [-x2, x1]
This is because a point rotated by theta is equal to x1cos - x2sin, x2cos + x1sin
(notice how the sin multiples are -x2, x1)
"""
x1 = x[..., :x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2:]
return torch.cat([-x2, x1], dim=-1)
def forward(self, q: torch.Tensor, k: torch.Tensor, offset: int = 0) -> tuple[torch.Tensor, torch.Tensor]:
"""
q (torch.Tensor): The q values after being multiplied by the input (B, num_heads, T, d_k).
k (torch.Tensor): The k values after being multiplied by the input (B, num_heads, T, d_k).
offset (int): The amount of values to offset the RoPE scaling by (useful for KV Caching).
"""
T = q.shape[2]
cos = self.cos_cached[offset:offset + T].unsqueeze(0).unsqueeze(0)
sin = self.sin_cached[offset:offset + T].unsqueeze(0).unsqueeze(0)
q = (q * cos) + (self.rotate_half(q) * sin)
k = (k * cos) + (self.rotate_half(k) * sin)
return q, k