SigVLP / models /rope_kernels.py
EnyaWoooo's picture
Update models/rope_kernels.py
4a975ce verified
Raw History Blame Contribute Delete
9.11 kB
"""
rope_kernel.py
RoPE kernel for ViT, implemented following the Qwen2-VL-style multimodal 3D RoPE idea
while keeping the original public interfaces unchanged.
Supported modes:
- 'mrope'
- 'vanilla'
- 'tad'
- 'videorope'
Included APIs:
- SimpleRotaryEmbedding
- _split_hwt_dims
- _build_thw_indices
- _pack_cos_sin
- compute_cos_sin(Dx, Dy, Dz, head_dim, theta, mode, t_scale, device)
- prepare_vision_rope(encoder, images, patch_size, head_dim, theta, mode, t_scale, device)
Behavior alignment notes with the Qwen2-VL-style logic:
1. mrope:
Standard 3D grid indexing (t, h, w), generating RoPE cos/sin independently
for each axis and then concatenating them.
2. vanilla:
Use a 1D flattened index and replicate it across all three axes.
3. tad:
Add the time-only index and the vanilla flattened index together, then use
the resulting shared index for all three axes.
4. videorope:
- Scale the temporal index by t_scale
- Center h and w around zero and shift them relative to time
("body-diagonal" style)
- Interleave h and w frequencies along the channel dimension
- Append the temporal segment at the end
"""
from typing import Tuple
import torch
import torch.nn as nn
class SimpleRotaryEmbedding(nn.Module):
def __init__(self, dim: int, theta: float = 10000.0, dtype=torch.float32):
super().__init__()
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype) / dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
def sinusoid(self, positions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Return cosine and sine embeddings for the given positions.
Args:
positions: Tensor of shape (P,)
Returns:
cos: (P, dim)
sin: (P, dim)
"""
local_inv = self.inv_freq.to(positions.device)
freqs = torch.outer(positions.to(local_inv.dtype), local_inv) # (P, dim/2)
emb = torch.cat([freqs, freqs], dim=-1) # (P, dim)
return emb.cos(), emb.sin()
def set_shared_axial_freqs(encoder: nn.Module, freqs_nd: torch.Tensor) -> None:
"""
Assign the same packed RoPE frequencies to all attention layers in the encoder.
"""
for layer in encoder.layers:
layer.self_attn.set_freqs(freqs_nd)
def _split_hwt_dims(head_dim: int) -> Tuple[int, int, int]:
"""
Split head_dim into h:w:t = 3:3:2 while ensuring:
- each segment is even
- each segment is at least 2
- the sum equals head_dim
Returns:
(dh, dw, dt)
"""
assert head_dim % 2 == 0, "head_dim must be even for RoPE"
ratio = torch.tensor([3.0, 3.0, 2.0])
raw = (ratio / ratio.sum() * head_dim).round().int()
# Force each segment to be even
raw = raw - (raw % 2)
raw = torch.clamp(raw, min=2)
diff = int(head_dim - int(raw.sum()))
raw[-1] += diff # Assign the remainder to the temporal segment
if (raw[-1] % 2) == 1:
raw[-1] += 1
raw[0] -= 1
return int(raw[0]), int(raw[1]), int(raw[2]) # (h, w, t)
def _build_thw_indices(Dx: int, Dy: int, Dz: int, device) -> torch.Tensor:
"""
Build flattened 3D indices in t-major order: t -> h -> w.
Returns:
Tensor of shape (3, N), where N = Dx * Dy * Dz
and the rows correspond to [t, h, w].
"""
t = torch.arange(Dz, device=device).view(Dz, 1, 1).expand(Dz, Dy, Dx)
h = torch.arange(Dy, device=device).view(1, Dy, 1).expand(Dz, Dy, Dx)
w = torch.arange(Dx, device=device).view(1, 1, Dx).expand(Dz, Dy, Dx)
return torch.stack([t.flatten(), h.flatten(), w.flatten()], dim=0)
def _pack_cos_sin(cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""
Pack cosine and sine tensors along the last dimension.
Args:
cos: (N, d)
sin: (N, d)
Returns:
packed: (N, 2d)
"""
return torch.cat([cos, sin], dim=-1)
def _interleave_lastdim(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""
Interleave two tensors along the last dimension.
Args:
a: (N, Da)
b: (N, Db)
Returns:
merged: (N, Da + Db), where the common prefix is interleaved
"""
n, da = a.shape
_, db = b.shape
m = min(da, db)
if m > 0:
stacked = torch.stack([a[:, :m], b[:, :m]], dim=-1).reshape(n, -1)
else:
stacked = a.new_empty(n, 0)
tails = []
if da > m:
tails.append(a[:, m:])
if db > m:
tails.append(b[:, m:])
return torch.cat([stacked] + tails, dim=-1) if tails else stacked
@torch.no_grad()
def compute_cos_sin(
Dx: int,
Dy: int,
Dz: int,
head_dim: int,
theta: float,
mode: str,
t_scale: float,
device,
) -> torch.Tensor:
"""
Compute packed cosine/sine RoPE features.
Args:
Dx, Dy, Dz: Number of patches along width, height, and depth/time
head_dim: Attention head dimension
theta: RoPE base
mode: One of 'vanilla', 'tad', 'mrope', 'videorope'
t_scale: Temporal scaling factor for videorope
device: Target device
Returns:
packed: (N, 2 * head_dim), where N = Dx * Dy * Dz
"""
assert head_dim % 2 == 0, "head_dim must be even"
# Split the head dimension using the h:w:t = 3:3:2 ratio
dh, dw, dt = _split_hwt_dims(head_dim)
# Build 3D indices: [t, h, w]
pos3 = _build_thw_indices(Dx, Dy, Dz, device=device)
n = pos3.shape[1]
# Create RoPE embedders for each axis segment
emb_t = SimpleRotaryEmbedding(dt, theta).to(device)
emb_h = SimpleRotaryEmbedding(dh, theta).to(device)
emb_w = SimpleRotaryEmbedding(dw, theta).to(device)
if mode == "mrope":
pt = pos3[0].float()
ph = pos3[1].float()
pw = pos3[2].float()
ct, st = emb_t.sinusoid(pt)
ch, sh = emb_h.sinusoid(ph)
cw, sw = emb_w.sinusoid(pw)
cos_full = torch.cat([ct, ch, cw], dim=-1)
sin_full = torch.cat([st, sh, sw], dim=-1)
elif mode == "vanilla":
flat = torch.arange(n, device=device, dtype=torch.float32)
pt = ph = pw = flat
ct, st = emb_t.sinusoid(pt)
ch, sh = emb_h.sinusoid(ph)
cw, sw = emb_w.sinusoid(pw)
cos_full = torch.cat([ct, ch, cw], dim=-1)
sin_full = torch.cat([st, sh, sw], dim=-1)
elif mode == "tad":
# Add the time-only index and the vanilla flattened index
base_t = pos3[0].float()
base_v = torch.arange(n, device=device, dtype=torch.float32)
idx = base_t + base_v
pt = ph = pw = idx
ct, st = emb_t.sinusoid(pt)
ch, sh = emb_h.sinusoid(ph)
cw, sw = emb_w.sinusoid(pw)
cos_full = torch.cat([ct, ch, cw], dim=-1)
sin_full = torch.cat([st, sh, sw], dim=-1)
elif mode == "videorope":
# 1) Scale temporal positions
pt = pos3[0].float() * float(t_scale)
# 2) Center h and w around zero
h_center = pos3[1].float() - (Dy - 1) / 2.0
w_center = pos3[2].float() - (Dx - 1) / 2.0
# 3) Shift spatial positions relative to time
ph = h_center + pt
pw = w_center + pt
ct, st = emb_t.sinusoid(pt)
ch, sh = emb_h.sinusoid(ph)
cw, sw = emb_w.sinusoid(pw)
# Interleave h and w channels, then place t at the end
hw_cos = _interleave_lastdim(ch, cw)
hw_sin = _interleave_lastdim(sh, sw)
cos_full = torch.cat([hw_cos, ct], dim=-1)
sin_full = torch.cat([hw_sin, st], dim=-1)
else:
raise ValueError(f"Unsupported rope mode: {mode}")
return _pack_cos_sin(cos_full, sin_full)
@torch.no_grad()
def prepare_vision_rope(
encoder,
images: torch.Tensor,
patch_size,
head_dim: int,
theta: float,
mode: str,
t_scale: float,
device,
) -> None:
"""
One-shot entry point for preparing RoPE frequencies for the vision encoder.
This function is intended to be called once per batch.
Args:
encoder: Vision encoder whose layers expose self_attn.set_freqs(...)
images:
- 5D tensor: (B, C, D, H, W)
- 4D tensor: (B, C, H, W)
patch_size:
- int, or
- tuple/list of (p_d, p_h, p_w)
head_dim: Attention head dimension
theta: RoPE base
mode: One of 'vanilla', 'tad', 'mrope', 'videorope'
t_scale: Temporal scaling factor for videorope
device: Target device
"""
if isinstance(patch_size, int):
p_d = p_h = p_w = patch_size
else:
p_d, p_h, p_w = patch_size
if images.dim() == 5:
_, _, d, h, w = images.shape
Dz = max(1, d // p_d)
Dy = max(1, h // p_h)
Dx = max(1, w // p_w)
else:
_, _, h, w = images.shape
Dz = 1
Dy = max(1, h // p_h)
Dx = max(1, w // p_w)
packed = compute_cos_sin(
Dx=Dx,
Dy=Dy,
Dz=Dz,
head_dim=head_dim,
theta=theta,
mode=mode,
t_scale=t_scale,
device=device,
)
set_shared_axial_freqs(encoder, packed)