EnyaWoooo commited on
Commit
4a975ce
·
verified ·
1 Parent(s): fd3d8f8

Update models/rope_kernels.py

Browse files
Files changed (1) hide show
  1. models/rope_kernels.py +197 -67
models/rope_kernels.py CHANGED
@@ -1,7 +1,16 @@
1
  """
2
- rope_kernel.py — ViT 的 RoPE 内核(接口不变),按 Qwen2-VL 的多模态 3D RoPE 思路实现,
3
- 支持四种模式:'mrope' | 'vanilla' | 'tad' | 'videorope'(含时间缩放与空间合并交错)。
4
 
 
 
 
 
 
 
 
 
 
 
5
  - SimpleRotaryEmbedding
6
  - _split_hwt_dims
7
  - _build_thw_indices
@@ -9,107 +18,189 @@ rope_kernel.py — ViT 的 RoPE 内核(接口不变),按 Qwen2-VL 的多
9
  - compute_cos_sin(Dx, Dy, Dz, head_dim, theta, mode, t_scale, device)
10
  - prepare_vision_rope(encoder, images, patch_size, head_dim, theta, mode, t_scale, device)
11
 
12
- 与上文 Qwen2-VL 行为对齐要点:
13
- 1) mrope:标准 3D 网格索引 (t,h,w) 分段生成 cos/sin 并拼接;
14
- 2) vanilla:将 1D 展平索引复制到三轴;
15
- 3) tad:time-only(t 复制到 h,w)与 vanilla 的索引**相加**,再生成 cos/sin;
16
- 4) videorope:t 轴索引按 t_scale 放大;h,w 以中心为 0 后相对 t 平移("body-diagonal"),并在通道维对 h 与 w 的频率**交错合并**,再把 t 段放到最后(对应上文的 apply_m_modify_* 行为)。
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
 
 
 
19
  import torch
20
  import torch.nn as nn
21
- from typing import Tuple
22
 
23
- # ---- 基础 ----
24
  class SimpleRotaryEmbedding(nn.Module):
25
  def __init__(self, dim: int, theta: float = 10000.0, dtype=torch.float32):
26
  super().__init__()
27
- inv = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype) / dim))
28
- self.register_buffer("inv_freq", inv, persistent=False)
 
 
 
 
 
 
 
29
 
30
- def sinusoid(self, positions: torch.Tensor):
31
- """返回 cos, sin;自动适配 positions 的 device。"""
 
 
32
  local_inv = self.inv_freq.to(positions.device)
33
- freqs = torch.outer(positions.to(local_inv.dtype), local_inv) # (P, dim/2)
34
- emb = torch.cat([freqs, freqs], dim=-1) # (P, dim)
35
  return emb.cos(), emb.sin()
36
 
 
37
  def set_shared_axial_freqs(encoder: nn.Module, freqs_nd: torch.Tensor) -> None:
 
 
 
38
  for layer in encoder.layers:
39
  layer.self_attn.set_freqs(freqs_nd)
40
 
41
 
42
  def _split_hwt_dims(head_dim: int) -> Tuple[int, int, int]:
43
- """按 h:w:t = 3:3:2 分配,确保偶数并和为 head_dim。"""
44
- assert head_dim % 2 == 0, "head_dim 必须为偶数用于 RoPE"
 
 
 
 
 
 
 
 
 
45
  ratio = torch.tensor([3.0, 3.0, 2.0])
46
  raw = (ratio / ratio.sum() * head_dim).round().int()
47
- # 变成偶数
 
48
  raw = raw - (raw % 2)
49
  raw = torch.clamp(raw, min=2)
 
50
  diff = int(head_dim - int(raw.sum()))
51
- raw[-1] += diff # 把余数给 t 段
 
52
  if (raw[-1] % 2) == 1:
53
  raw[-1] += 1
54
  raw[0] -= 1
 
55
  return int(raw[0]), int(raw[1]), int(raw[2]) # (h, w, t)
56
 
57
 
58
- def _build_thw_indices(Dx, Dy, Dz, device):
59
- # t-major: t -> h -> w
 
 
 
 
 
 
60
  t = torch.arange(Dz, device=device).view(Dz, 1, 1).expand(Dz, Dy, Dx)
61
  h = torch.arange(Dy, device=device).view(1, Dy, 1).expand(Dz, Dy, Dx)
62
  w = torch.arange(Dx, device=device).view(1, 1, Dx).expand(Dz, Dy, Dx)
63
- return torch.stack([t.flatten(), h.flatten(), w.flatten()], dim=0) # (3, N) = [t,h,w]
64
 
 
 
 
 
 
 
65
 
66
- def _pack_cos_sin(cos: torch.Tensor, sin: torch.Tensor):
67
- # (N, d) -> (N, 2d)
 
 
 
 
 
68
  return torch.cat([cos, sin], dim=-1)
69
 
70
 
71
  def _interleave_lastdim(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
72
- """按最后一维交错合并 a,b(形状: (N, Da)/(N, Db))。"""
73
- N, Da = a.shape
74
- _, Db = b.shape
75
- m = min(Da, Db)
 
 
 
 
 
 
 
 
 
 
76
  if m > 0:
77
- stacked = torch.stack([a[:, :m], b[:, :m]], dim=-1).reshape(N, -1)
78
  else:
79
- stacked = a.new_empty(N, 0)
 
80
  tails = []
81
- if Da > m:
82
  tails.append(a[:, m:])
83
- if Db > m:
84
  tails.append(b[:, m:])
 
85
  return torch.cat([stacked] + tails, dim=-1) if tails else stacked
86
 
87
 
88
- # ---- 各模式的 cos/sin 生成 ----
89
  @torch.no_grad()
90
  def compute_cos_sin(
91
- Dx: int, Dy: int, Dz: int, head_dim: int, theta: float,
92
- mode: str, t_scale: float, device
93
- ):
 
 
 
 
 
 
94
  """
95
- 返回 packed: (N, 2*head_dim),N=Dx*Dy*Dz
96
- mode: 'vanilla' | 'tad' | 'mrope' | 'videorope'
 
 
 
 
 
 
 
 
 
 
97
  """
98
- assert head_dim % 2 == 0
99
 
100
- # 先按 h:w:t=3:3:2 拆段
101
  dh, dw, dt = _split_hwt_dims(head_dim)
102
 
103
- # 索引 (3,N)
104
- pos3 = _build_thw_indices(Dx, Dy, Dz, device=device) # [t,h,w]
105
- N = pos3.shape[1]
106
 
107
- # 三段的 RoPE 嵌入器
108
  emb_t = SimpleRotaryEmbedding(dt, theta).to(device)
109
  emb_h = SimpleRotaryEmbedding(dh, theta).to(device)
110
  emb_w = SimpleRotaryEmbedding(dw, theta).to(device)
111
 
112
- # 构造三轴的“位置索引”
113
  if mode == "mrope":
114
  pt = pos3[0].float()
115
  ph = pos3[1].float()
@@ -123,7 +214,7 @@ def compute_cos_sin(
123
  sin_full = torch.cat([st, sh, sw], dim=-1)
124
 
125
  elif mode == "vanilla":
126
- flat = torch.arange(N, device=device, dtype=torch.float)
127
  pt = ph = pw = flat
128
 
129
  ct, st = emb_t.sinusoid(pt)
@@ -134,10 +225,11 @@ def compute_cos_sin(
134
  sin_full = torch.cat([st, sh, sw], dim=-1)
135
 
136
  elif mode == "tad":
137
- # time-only 与 vanilla 的索引相加(与上文 Qwen2-VL 的 position_ids 相加一致)
138
  base_t = pos3[0].float()
139
- base_v = torch.arange(N, device=device, dtype=torch.float)
140
- idx = base_t + base_v # t + flat,三轴相同
 
141
  pt = ph = pw = idx
142
 
143
  ct, st = emb_t.sinusoid(pt)
@@ -148,11 +240,14 @@ def compute_cos_sin(
148
  sin_full = torch.cat([st, sh, sw], dim=-1)
149
 
150
  elif mode == "videorope":
151
- # 1) t 放大;2) h,w 中心化并相对 t 平移;3) 频率层面合并交错(h↔w),并把 t 段放到最后
152
  pt = pos3[0].float() * float(t_scale)
153
- # 中心化:以网格中心为 0
 
154
  h_center = pos3[1].float() - (Dy - 1) / 2.0
155
  w_center = pos3[2].float() - (Dx - 1) / 2.0
 
 
156
  ph = h_center + pt
157
  pw = w_center + pt
158
 
@@ -160,7 +255,7 @@ def compute_cos_sin(
160
  ch, sh = emb_h.sinusoid(ph)
161
  cw, sw = emb_w.sinusoid(pw)
162
 
163
- # 交错合并 h 与 w,��后把 t 放到最后(对应 apply_m_modify_* 的通道次序)
164
  hw_cos = _interleave_lastdim(ch, cw)
165
  hw_sin = _interleave_lastdim(sh, sw)
166
 
@@ -168,31 +263,66 @@ def compute_cos_sin(
168
  sin_full = torch.cat([hw_sin, st], dim=-1)
169
 
170
  else:
171
- raise ValueError(f"unsupported rope mode: {mode}")
172
 
173
- return _pack_cos_sin(cos_full, sin_full) # (N, 2*head_dim)
174
 
175
 
176
- # ---- 对接 encoder 的一次性入口(每个 batch 调用)----
177
  @torch.no_grad()
178
  def prepare_vision_rope(
179
  encoder,
180
  images: torch.Tensor,
181
- patch_size, head_dim: int,
182
- theta: float, mode: str, t_scale: float,
183
- device
184
- ):
185
- # 计算 (Dz,Dy,Dx)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  if isinstance(patch_size, int):
187
  p_d = p_h = p_w = patch_size
188
  else:
189
  p_d, p_h, p_w = patch_size
 
190
  if images.dim() == 5:
191
- _, _, D, H, W = images.shape
192
- Dz = max(1, D // p_d); Dy = max(1, H // p_h); Dx = max(1, W // p_w)
 
 
193
  else:
194
- _, _, H, W = images.shape
195
- Dz = 1; Dy = max(1, H // p_h); Dx = max(1, W // p_w)
196
-
197
- packed = compute_cos_sin(Dx, Dy, Dz, head_dim, theta, mode, t_scale, device)
198
- set_shared_axial_freqs(encoder, packed) # 复用 setter,把 (N, 2*head_dim) 写进 encoder
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ rope_kernel.py
 
3
 
4
+ RoPE kernel for ViT, implemented following the Qwen2-VL-style multimodal 3D RoPE idea
5
+ while keeping the original public interfaces unchanged.
6
+
7
+ Supported modes:
8
+ - 'mrope'
9
+ - 'vanilla'
10
+ - 'tad'
11
+ - 'videorope'
12
+
13
+ Included APIs:
14
  - SimpleRotaryEmbedding
15
  - _split_hwt_dims
16
  - _build_thw_indices
 
18
  - compute_cos_sin(Dx, Dy, Dz, head_dim, theta, mode, t_scale, device)
19
  - prepare_vision_rope(encoder, images, patch_size, head_dim, theta, mode, t_scale, device)
20
 
21
+ Behavior alignment notes with the Qwen2-VL-style logic:
22
+ 1. mrope:
23
+ Standard 3D grid indexing (t, h, w), generating RoPE cos/sin independently
24
+ for each axis and then concatenating them.
25
+
26
+ 2. vanilla:
27
+ Use a 1D flattened index and replicate it across all three axes.
28
+
29
+ 3. tad:
30
+ Add the time-only index and the vanilla flattened index together, then use
31
+ the resulting shared index for all three axes.
32
+
33
+ 4. videorope:
34
+ - Scale the temporal index by t_scale
35
+ - Center h and w around zero and shift them relative to time
36
+ ("body-diagonal" style)
37
+ - Interleave h and w frequencies along the channel dimension
38
+ - Append the temporal segment at the end
39
  """
40
 
41
+ from typing import Tuple
42
+
43
  import torch
44
  import torch.nn as nn
 
45
 
46
+
47
  class SimpleRotaryEmbedding(nn.Module):
48
  def __init__(self, dim: int, theta: float = 10000.0, dtype=torch.float32):
49
  super().__init__()
50
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype) / dim))
51
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
52
+
53
+ def sinusoid(self, positions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
54
+ """
55
+ Return cosine and sine embeddings for the given positions.
56
+
57
+ Args:
58
+ positions: Tensor of shape (P,)
59
 
60
+ Returns:
61
+ cos: (P, dim)
62
+ sin: (P, dim)
63
+ """
64
  local_inv = self.inv_freq.to(positions.device)
65
+ freqs = torch.outer(positions.to(local_inv.dtype), local_inv) # (P, dim/2)
66
+ emb = torch.cat([freqs, freqs], dim=-1) # (P, dim)
67
  return emb.cos(), emb.sin()
68
 
69
+
70
  def set_shared_axial_freqs(encoder: nn.Module, freqs_nd: torch.Tensor) -> None:
71
+ """
72
+ Assign the same packed RoPE frequencies to all attention layers in the encoder.
73
+ """
74
  for layer in encoder.layers:
75
  layer.self_attn.set_freqs(freqs_nd)
76
 
77
 
78
  def _split_hwt_dims(head_dim: int) -> Tuple[int, int, int]:
79
+ """
80
+ Split head_dim into h:w:t = 3:3:2 while ensuring:
81
+ - each segment is even
82
+ - each segment is at least 2
83
+ - the sum equals head_dim
84
+
85
+ Returns:
86
+ (dh, dw, dt)
87
+ """
88
+ assert head_dim % 2 == 0, "head_dim must be even for RoPE"
89
+
90
  ratio = torch.tensor([3.0, 3.0, 2.0])
91
  raw = (ratio / ratio.sum() * head_dim).round().int()
92
+
93
+ # Force each segment to be even
94
  raw = raw - (raw % 2)
95
  raw = torch.clamp(raw, min=2)
96
+
97
  diff = int(head_dim - int(raw.sum()))
98
+ raw[-1] += diff # Assign the remainder to the temporal segment
99
+
100
  if (raw[-1] % 2) == 1:
101
  raw[-1] += 1
102
  raw[0] -= 1
103
+
104
  return int(raw[0]), int(raw[1]), int(raw[2]) # (h, w, t)
105
 
106
 
107
+ def _build_thw_indices(Dx: int, Dy: int, Dz: int, device) -> torch.Tensor:
108
+ """
109
+ Build flattened 3D indices in t-major order: t -> h -> w.
110
+
111
+ Returns:
112
+ Tensor of shape (3, N), where N = Dx * Dy * Dz
113
+ and the rows correspond to [t, h, w].
114
+ """
115
  t = torch.arange(Dz, device=device).view(Dz, 1, 1).expand(Dz, Dy, Dx)
116
  h = torch.arange(Dy, device=device).view(1, Dy, 1).expand(Dz, Dy, Dx)
117
  w = torch.arange(Dx, device=device).view(1, 1, Dx).expand(Dz, Dy, Dx)
 
118
 
119
+ return torch.stack([t.flatten(), h.flatten(), w.flatten()], dim=0)
120
+
121
+
122
+ def _pack_cos_sin(cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
123
+ """
124
+ Pack cosine and sine tensors along the last dimension.
125
 
126
+ Args:
127
+ cos: (N, d)
128
+ sin: (N, d)
129
+
130
+ Returns:
131
+ packed: (N, 2d)
132
+ """
133
  return torch.cat([cos, sin], dim=-1)
134
 
135
 
136
  def _interleave_lastdim(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
137
+ """
138
+ Interleave two tensors along the last dimension.
139
+
140
+ Args:
141
+ a: (N, Da)
142
+ b: (N, Db)
143
+
144
+ Returns:
145
+ merged: (N, Da + Db), where the common prefix is interleaved
146
+ """
147
+ n, da = a.shape
148
+ _, db = b.shape
149
+ m = min(da, db)
150
+
151
  if m > 0:
152
+ stacked = torch.stack([a[:, :m], b[:, :m]], dim=-1).reshape(n, -1)
153
  else:
154
+ stacked = a.new_empty(n, 0)
155
+
156
  tails = []
157
+ if da > m:
158
  tails.append(a[:, m:])
159
+ if db > m:
160
  tails.append(b[:, m:])
161
+
162
  return torch.cat([stacked] + tails, dim=-1) if tails else stacked
163
 
164
 
 
165
  @torch.no_grad()
166
  def compute_cos_sin(
167
+ Dx: int,
168
+ Dy: int,
169
+ Dz: int,
170
+ head_dim: int,
171
+ theta: float,
172
+ mode: str,
173
+ t_scale: float,
174
+ device,
175
+ ) -> torch.Tensor:
176
  """
177
+ Compute packed cosine/sine RoPE features.
178
+
179
+ Args:
180
+ Dx, Dy, Dz: Number of patches along width, height, and depth/time
181
+ head_dim: Attention head dimension
182
+ theta: RoPE base
183
+ mode: One of 'vanilla', 'tad', 'mrope', 'videorope'
184
+ t_scale: Temporal scaling factor for videorope
185
+ device: Target device
186
+
187
+ Returns:
188
+ packed: (N, 2 * head_dim), where N = Dx * Dy * Dz
189
  """
190
+ assert head_dim % 2 == 0, "head_dim must be even"
191
 
192
+ # Split the head dimension using the h:w:t = 3:3:2 ratio
193
  dh, dw, dt = _split_hwt_dims(head_dim)
194
 
195
+ # Build 3D indices: [t, h, w]
196
+ pos3 = _build_thw_indices(Dx, Dy, Dz, device=device)
197
+ n = pos3.shape[1]
198
 
199
+ # Create RoPE embedders for each axis segment
200
  emb_t = SimpleRotaryEmbedding(dt, theta).to(device)
201
  emb_h = SimpleRotaryEmbedding(dh, theta).to(device)
202
  emb_w = SimpleRotaryEmbedding(dw, theta).to(device)
203
 
 
204
  if mode == "mrope":
205
  pt = pos3[0].float()
206
  ph = pos3[1].float()
 
214
  sin_full = torch.cat([st, sh, sw], dim=-1)
215
 
216
  elif mode == "vanilla":
217
+ flat = torch.arange(n, device=device, dtype=torch.float32)
218
  pt = ph = pw = flat
219
 
220
  ct, st = emb_t.sinusoid(pt)
 
225
  sin_full = torch.cat([st, sh, sw], dim=-1)
226
 
227
  elif mode == "tad":
228
+ # Add the time-only index and the vanilla flattened index
229
  base_t = pos3[0].float()
230
+ base_v = torch.arange(n, device=device, dtype=torch.float32)
231
+ idx = base_t + base_v
232
+
233
  pt = ph = pw = idx
234
 
235
  ct, st = emb_t.sinusoid(pt)
 
240
  sin_full = torch.cat([st, sh, sw], dim=-1)
241
 
242
  elif mode == "videorope":
243
+ # 1) Scale temporal positions
244
  pt = pos3[0].float() * float(t_scale)
245
+
246
+ # 2) Center h and w around zero
247
  h_center = pos3[1].float() - (Dy - 1) / 2.0
248
  w_center = pos3[2].float() - (Dx - 1) / 2.0
249
+
250
+ # 3) Shift spatial positions relative to time
251
  ph = h_center + pt
252
  pw = w_center + pt
253
 
 
255
  ch, sh = emb_h.sinusoid(ph)
256
  cw, sw = emb_w.sinusoid(pw)
257
 
258
+ # Interleave h and w channels, then place t at the end
259
  hw_cos = _interleave_lastdim(ch, cw)
260
  hw_sin = _interleave_lastdim(sh, sw)
261
 
 
263
  sin_full = torch.cat([hw_sin, st], dim=-1)
264
 
265
  else:
266
+ raise ValueError(f"Unsupported rope mode: {mode}")
267
 
268
+ return _pack_cos_sin(cos_full, sin_full)
269
 
270
 
 
271
  @torch.no_grad()
272
  def prepare_vision_rope(
273
  encoder,
274
  images: torch.Tensor,
275
+ patch_size,
276
+ head_dim: int,
277
+ theta: float,
278
+ mode: str,
279
+ t_scale: float,
280
+ device,
281
+ ) -> None:
282
+ """
283
+ One-shot entry point for preparing RoPE frequencies for the vision encoder.
284
+
285
+ This function is intended to be called once per batch.
286
+
287
+ Args:
288
+ encoder: Vision encoder whose layers expose self_attn.set_freqs(...)
289
+ images:
290
+ - 5D tensor: (B, C, D, H, W)
291
+ - 4D tensor: (B, C, H, W)
292
+ patch_size:
293
+ - int, or
294
+ - tuple/list of (p_d, p_h, p_w)
295
+ head_dim: Attention head dimension
296
+ theta: RoPE base
297
+ mode: One of 'vanilla', 'tad', 'mrope', 'videorope'
298
+ t_scale: Temporal scaling factor for videorope
299
+ device: Target device
300
+ """
301
  if isinstance(patch_size, int):
302
  p_d = p_h = p_w = patch_size
303
  else:
304
  p_d, p_h, p_w = patch_size
305
+
306
  if images.dim() == 5:
307
+ _, _, d, h, w = images.shape
308
+ Dz = max(1, d // p_d)
309
+ Dy = max(1, h // p_h)
310
+ Dx = max(1, w // p_w)
311
  else:
312
+ _, _, h, w = images.shape
313
+ Dz = 1
314
+ Dy = max(1, h // p_h)
315
+ Dx = max(1, w // p_w)
316
+
317
+ packed = compute_cos_sin(
318
+ Dx=Dx,
319
+ Dy=Dy,
320
+ Dz=Dz,
321
+ head_dim=head_dim,
322
+ theta=theta,
323
+ mode=mode,
324
+ t_scale=t_scale,
325
+ device=device,
326
+ )
327
+
328
+ set_shared_axial_freqs(encoder, packed)