Update models/rope_kernels.py
Browse files12345671 unmodified line91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141157 unmodified lines1231241251261271281294 unmodified lines1341351361371381391401411421434 unmodified lines1481491501511521531541551561571581 unmodified line1601611621631641651661 unmodified line168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""rope_kernel.py — ViT 的 RoPE 内核(接口不变),按 Qwen2-VL 的多模态 3D RoPE 思路实现,支持四种模式:'mrope' | 'vanilla' | 'tad' | 'videorope'(含时间缩放与空间合并交错)。- SimpleRotaryEmbedding- _split_hwt_dims- _build_thw_indices1 unmodified line- 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)与上文 Qwen2-VL 行为对齐要点:1) mrope:标准 3D 网格索引 (t,h,w) 分段生成 cos/sin 并拼接;2) vanilla:将 1D 展平索引复制到三轴;3) tad:time-only(t 复制到 h,w)与 vanilla 的索引**相加**,再生成 cos/sin;4) videorope:t 轴索引按 t_scale 放大;h,w 以中心为 0 后相对 t 平移("body-diagonal"),并在通道维对 h 与 w 的频率**交错合并**,再把 t 段放到最后(对应上文的 apply_m_modify_* 行为)。"""import torchimport torch.nn as nnfrom typing import Tuple# ---- 基础 ----class SimpleRotaryEmbedding(nn.Module):def __init__(self, dim: int, theta: float = 10000.0, dtype=torch.float32):super().__init__()inv = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype) / dim))self.register_buffer("inv_freq", inv, persistent=False)def sinusoid(self, positions: torch.Tensor):"""返回 cos, sin;自动适配 positions 的 device。"""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:for layer in encoder.layers:layer.self_attn.set_freqs(freqs_nd)def _split_hwt_dims(head_dim: int) -> Tuple[int, int, int]:"""按 h:w:t = 3:3:2 分配,确保偶数并和为 head_dim。"""assert head_dim % 2 == 0, "head_dim 必须为偶数用于 RoPE"ratio = torch.tensor([3.0, 3.0, 2.0])raw = (ratio / ratio.sum() * head_dim).round().int()# 变成偶数raw = raw - (raw % 2)raw = torch.clamp(raw, min=2)diff = int(head_dim - int(raw.sum()))raw[-1] += diff # 把余数给 t 段if (raw[-1] % 2) == 1:raw[-1] += 1raw[0] -= 1return int(raw[0]), int(raw[1]), int(raw[2]) # (h, w, t)def _build_thw_indices(Dx, Dy, Dz, device):# t-major: t -> h -> wt = 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) # (3, N) = [t,h,w]def _pack_cos_sin(cos: torch.Tensor, sin: torch.Tensor):# (N, d) -> (N, 2d)return torch.cat([cos, sin], dim=-1)def _interleave_lastdim(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:"""按最后一维交错合并 a,b(形状: (N, Da)/(N, Db))。"""N, Da = a.shape_, Db = b.shapem = 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# ---- 各模式的 cos/sin 生成 ----@torch.no_grad()def compute_cos_sin(Dx: int, Dy: int, Dz: int, head_dim: int, theta: float,mode: str, t_scale: float, device):"""返回 packed: (N, 2*head_dim),N=Dx*Dy*Dzmode: 'vanilla' | 'tad' | 'mrope' | 'videorope'"""assert head_dim % 2 == 0# 先按 h:w:t=3:3:2 拆段dh, dw, dt = _split_hwt_dims(head_dim)# 索引 (3,N)pos3 = _build_thw_indices(Dx, Dy, Dz, device=device) # [t,h,w]N = pos3.shape[1]# 三段的 RoPE 嵌入器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()7 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "vanilla":flat = torch.arange(N, device=device, dtype=torch.float)pt = ph = pw = flatct, st = emb_t.sinusoid(pt)4 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "tad":# time-only 与 vanilla 的索引相加(与上文 Qwen2-VL 的 position_ids 相加一致)base_t = pos3[0].float()base_v = torch.arange(N, device=device, dtype=torch.float)idx = base_t + base_v # t + flat,三轴相同pt = ph = pw = idxct, st = emb_t.sinusoid(pt)4 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "videorope":# 1) t 放大;2) h,w 中心化并相对 t 平移;3) 频率层面合并交错(h↔w),并把 t 段放到最后pt = pos3[0].float() * float(t_scale)# 中心化:以网格中心为 0h_center = pos3[1].float() - (Dy - 1) / 2.0w_center = pos3[2].float() - (Dx - 1) / 2.0ph = h_center + ptpw = w_center + pt1 unmodified linech, sh = emb_h.sinusoid(ph)cw, sw = emb_w.sinusoid(pw)# 交错合并 h 与 w,��后把 t 放到最后(对应 apply_m_modify_* 的通道次序)hw_cos = _interleave_lastdim(ch, cw)hw_sin = _interleave_lastdim(sh, sw)1 unmodified linesin_full = torch.cat([hw_sin, st], dim=-1)else:raise ValueError(f"unsupported rope mode: {mode}")return _pack_cos_sin(cos_full, sin_full) # (N, 2*head_dim)# ---- 对接 encoder 的一次性入口(每个 batch 调用)----@torch.no_grad()def prepare_vision_rope(encoder,images: torch.Tensor,patch_size, head_dim: int,theta: float, mode: str, t_scale: float,device):# 计算 (Dz,Dy,Dx)if isinstance(patch_size, int):p_d = p_h = p_w = patch_sizeelse:p_d, p_h, p_w = patch_sizeif images.dim() == 5:_, _, D, H, W = images.shapeDz = max(1, D // p_d); Dy = max(1, H // p_h); Dx = max(1, W // p_w)else:_, _, H, W = images.shapeDz = 1; Dy = max(1, H // p_h); Dx = max(1, W // p_w)packed = compute_cos_sin(Dx, Dy, Dz, head_dim, theta, mode, t_scale, device)set_shared_axial_freqs(encoder, packed) # 复用 setter,把 (N, 2*head_dim) 写进 encoder123456789101112131415161 unmodified line181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052067 unmodified lines2142152162172182192204 unmodified lines2252262272282292302312322332342354 unmodified lines2402412422432442452462472482492502512522531 unmodified line2552562572582592602611 unmodified line263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""rope_kernel.pyRoPE kernel for ViT, implemented following the Qwen2-VL-style multimodal 3D RoPE ideawhile keeping the original public interfaces unchanged.Supported modes:- 'mrope'- 'vanilla'- 'tad'- 'videorope'Included APIs:- SimpleRotaryEmbedding- _split_hwt_dims- _build_thw_indices1 unmodified line- 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 independentlyfor 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 usethe 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 Tupleimport torchimport torch.nn as nnclass 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_dimReturns:(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 evenraw = 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 segmentif (raw[-1] % 2) == 1:raw[-1] += 1raw[0] -= 1return 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 * Dzand 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.shapem = 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/timehead_dim: Attention head dimensiontheta: RoPE basemode: One of 'vanilla', 'tad', 'mrope', 'videorope't_scale: Temporal scaling factor for videoropedevice: Target deviceReturns: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 ratiodh, 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 segmentemb_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()7 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "vanilla":flat = torch.arange(n, device=device, dtype=torch.float32)pt = ph = pw = flatct, st = emb_t.sinusoid(pt)4 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "tad":# Add the time-only index and the vanilla flattened indexbase_t = pos3[0].float()base_v = torch.arange(n, device=device, dtype=torch.float32)idx = base_t + base_vpt = ph = pw = idxct, st = emb_t.sinusoid(pt)4 unmodified linessin_full = torch.cat([st, sh, sw], dim=-1)elif mode == "videorope":# 1) Scale temporal positionspt = pos3[0].float() * float(t_scale)# 2) Center h and w around zeroh_center = pos3[1].float() - (Dy - 1) / 2.0w_center = pos3[2].float() - (Dx - 1) / 2.0# 3) Shift spatial positions relative to timeph = h_center + ptpw = w_center + pt1 unmodified linech, sh = emb_h.sinusoid(ph)cw, sw = emb_w.sinusoid(pw)# Interleave h and w channels, then place t at the endhw_cos = _interleave_lastdim(ch, cw)hw_sin = _interleave_lastdim(sh, sw)1 unmodified linesin_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 dimensiontheta: RoPE basemode: One of 'vanilla', 'tad', 'mrope', 'videorope't_scale: Temporal scaling factor for videoropedevice: Target device"""if isinstance(patch_size, int):p_d = p_h = p_w = patch_sizeelse:p_d, p_h, p_w = patch_sizeif images.dim() == 5:_, _, d, h, w = images.shapeDz = max(1, d // p_d)Dy = max(1, h // p_h)Dx = max(1, w // p_w)else:_, _, h, w = images.shapeDz = 1Dy = 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)
models/rope_kernels.py+197-67