File size: 9,113 Bytes
f7374e7
4a975ce
f7374e7
4a975ce
 
 
 
 
 
 
 
 
 
f7374e7
 
 
 
 
 
 
4a975ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7374e7
 
4a975ce
 
f7374e7
 
 
4a975ce
f7374e7
 
 
4a975ce
 
 
 
 
 
 
 
 
f7374e7
4a975ce
 
 
 
f7374e7
4a975ce
 
f7374e7
 
4a975ce
f7374e7
4a975ce
 
 
f7374e7
 
 
 
 
4a975ce
 
 
 
 
 
 
 
 
 
 
f7374e7
 
4a975ce
 
f7374e7
 
4a975ce
f7374e7
4a975ce
 
f7374e7
 
 
4a975ce
f7374e7
 
 
4a975ce
 
 
 
 
 
 
 
f7374e7
 
 
 
4a975ce
 
 
 
 
 
f7374e7
4a975ce
 
 
 
 
 
 
f7374e7
 
 
 
4a975ce
 
 
 
 
 
 
 
 
 
 
 
 
 
f7374e7
4a975ce
f7374e7
4a975ce
 
f7374e7
4a975ce
f7374e7
4a975ce
f7374e7
4a975ce
f7374e7
 
 
 
 
4a975ce
 
 
 
 
 
 
 
 
f7374e7
4a975ce
 
 
 
 
 
 
 
 
 
 
 
f7374e7
4a975ce
f7374e7
4a975ce
f7374e7
 
4a975ce
 
 
f7374e7
4a975ce
f7374e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a975ce
f7374e7
 
 
 
 
 
 
 
 
 
4a975ce
f7374e7
4a975ce
 
 
f7374e7
 
 
 
 
 
 
 
 
 
4a975ce
f7374e7
4a975ce
 
f7374e7
 
4a975ce
 
f7374e7
 
 
 
 
 
 
4a975ce
f7374e7
 
 
 
 
 
 
4a975ce
f7374e7
4a975ce
f7374e7
 
 
 
 
 
4a975ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7374e7
 
 
 
4a975ce
f7374e7
4a975ce
 
 
 
f7374e7
4a975ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""
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)