File size: 14,400 Bytes
7e0b12a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2025
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

from typing import Optional

import torch
import torch.nn as nn


# =============================================================================
# ==== 1D RoPE 工具 ====
# =============================================================================
class RotaryEmbedding(nn.Module):
    """1D Rotary Position Embedding."""

    def __init__(self, dim: int, max_position_embeddings: int = 10000, base: float = 10000.0) -> None:
        super().__init__()
        self.dim = dim
        self.max_position_embeddings = max_position_embeddings
        self.base = base

        inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))
        self.register_buffer("inv_freq", inv_freq, persistent=False)

    def forward(
        self,
        seq_len: int,
        device: Optional[torch.device] = None,
        dtype: Optional[torch.dtype] = None,
    ) -> torch.Tensor:
        """生成给定长度的 RoPE 频率表。"""
        if device is None:
            device = self.inv_freq.device
        if dtype is None:
            dtype = torch.float32

        positions = torch.arange(seq_len, device=device, dtype=torch.float32)
        freqs = torch.outer(positions, self.inv_freq.to(device))  # [seq_len, dim//2]
        freqs = torch.cat([freqs, freqs], dim=-1)  # [seq_len, dim]
        return freqs.to(dtype)


def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """对输入张量应用 RoPE 旋转。"""
    cos = cos.to(x.dtype)
    sin = sin.to(x.dtype)

    x_even = x[..., 0::2]
    x_odd = x[..., 1::2]

    cos_half = cos[..., 0::2]
    sin_half = sin[..., 0::2]

    rotated_even = x_even * cos_half - x_odd * sin_half
    rotated_odd = x_even * sin_half + x_odd * cos_half

    rotated = torch.stack([rotated_even, rotated_odd], dim=-1).flatten(-2)
    return rotated


def interpolate_rope_freqs(freqs: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
    """对浮点位置进行 RoPE 频率插值。"""
    positions_float = positions.to(torch.float32)

    pos_floor = positions_float.floor().long().clamp(0, freqs.shape[0] - 1)
    pos_ceil = positions_float.ceil().long().clamp(0, freqs.shape[0] - 1)
    weight = (positions_float - pos_floor.float()).unsqueeze(-1)

    freqs_floor = freqs[pos_floor]
    freqs_ceil = freqs[pos_ceil]
    freqs_interp = freqs_floor * (1 - weight) + freqs_ceil * weight
    return freqs_interp.to(freqs.dtype)


# =============================================================================
# ==== Resampler 实现 ====
# =============================================================================
class Quicksviewer2Resampler(nn.Module):
    """使用 1D RoPE 的视频 Resampler,实现对 Cubing 输出进行压缩。"""

    def __init__(self, config) -> None:
        super().__init__()
        self.config = config

        # ==== 配置 ====
        self.vision_dim = int(getattr(config.vision_config, "hidden_size", 1536))
        self.lm_dim = int(getattr(config.text_config, "hidden_size", 4096))
        self.num_queries = int(getattr(config, "resampler_num_queries", 64))
        self.num_heads = int(getattr(config, "resampler_num_heads", 32))
        self.reference_fps = float(getattr(config, "reference_fps", 10.0))
        # Align default with exp: fall back to 1.0 if not provided
        self.effective_video_fps = float(getattr(config, "effective_video_fps", 1.0))

        # ==== 维度分配 ====
        self.dim_ratio = (2, 3, 3)
        base_dim = self.lm_dim // sum(self.dim_ratio)
        self.dim_t = base_dim * self.dim_ratio[0]
        self.dim_h = base_dim * self.dim_ratio[1]
        self.dim_w = base_dim * self.dim_ratio[2]
        self.dim_w += self.lm_dim - (self.dim_t + self.dim_h + self.dim_w)  # 补足余数

        # ==== RoPE 生成器 ====
        self.rope_t = RotaryEmbedding(self.dim_t)
        self.rope_h = RotaryEmbedding(self.dim_h)
        self.rope_w = RotaryEmbedding(self.dim_w)

        # ==== 核心模块 ====
        self.query = nn.Parameter(torch.zeros(self.num_queries, self.lm_dim))
        self.kv_proj = nn.Linear(self.vision_dim, self.lm_dim, bias=False)
        self.attn = nn.MultiheadAttention(self.lm_dim, self.num_heads, batch_first=False, dropout=0.0)
        self.ln_q = nn.LayerNorm(self.lm_dim, eps=1e-6)
        self.ln_kv = nn.LayerNorm(self.lm_dim, eps=1e-6)
        self.ln_post = nn.LayerNorm(self.lm_dim, eps=1e-6)
        self.proj = nn.Parameter((self.lm_dim ** -0.5) * torch.randn(self.lm_dim, self.lm_dim))

        self.apply(self._init_weights)
        self._post_init_parameters()
        self._debug_checked_params = False

    def _has_nonfinite_params(self) -> bool:
        """Return True if any parameter contains NaN/Inf."""
        for p in self.parameters():
            if p is None:
                continue
            if not torch.isfinite(p).all():
                return True
        return False

    def _reset_parameters(self) -> None:
        """Re-initialize parameters to a sane state."""
        self.apply(self._init_weights)
        self._post_init_parameters()

    def _init_weights(self, m) -> None:
        if hasattr(m, "weight") and getattr(m.weight, "device", None) is not None and m.weight.device.type == "meta":
            return
        if isinstance(m, nn.Linear):
            nn.init.trunc_normal_(m.weight, std=0.02)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0.0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.weight, 1.0)
            nn.init.constant_(m.bias, 0.0)
        elif isinstance(m, nn.MultiheadAttention):
            if hasattr(m, "in_proj_weight") and m.in_proj_weight is not None and m.in_proj_weight.device.type != "meta":
                nn.init.xavier_uniform_(m.in_proj_weight)
            if hasattr(m, "in_proj_bias") and m.in_proj_bias is not None and m.in_proj_bias.device.type != "meta":
                nn.init.constant_(m.in_proj_bias, 0.0)

    def _post_init_parameters(self) -> None:
        if getattr(self.query, "device", None) is not None and self.query.device.type == "meta":
            return
        if torch.isnan(self.query).any() or self.query.std() < 1e-6:
            nn.init.trunc_normal_(self.query, std=0.02)
        if torch.isnan(self.proj).any() or self.proj.std() < 1e-6:
            nn.init.trunc_normal_(self.proj, std=0.02)

    def forward(
        self,
        cube_features: torch.Tensor,
        tgt_size_range: list,
        fps: Optional[float] = None,
    ) -> torch.Tensor:
        """将 Cubing 输出的立方体特征压缩为固定数量的查询 token。"""
        if cube_features.dim() == 2:
            cube_features = cube_features.unsqueeze(0)

        B, L, _ = cube_features.shape
        # 默认关闭调试输出,可通过 config.debug_cubing_logs 显式打开
        debug_nan = bool(getattr(self.config, "debug_cubing_logs", False))

        device = cube_features.device
        dtype = cube_features.dtype
        if debug_nan and cube_features.numel() > 0:
            nan_in = torch.isnan(cube_features).sum().item()
            inf_in = torch.isinf(cube_features).sum().item()
            if nan_in > 0 or inf_in > 0:
                print(
                    f"[Quicksviewer2][DEBUG NaNCheck][resampler_input] shape={tuple(cube_features.shape)} "
                    f"dtype={cube_features.dtype} nan={nan_in} inf={inf_in}"
                )

        if debug_nan and self._has_nonfinite_params():
            print("[Quicksviewer2][DEBUG NaNCheck] Non-finite params detected in resampler, re-initializing.")
            self._reset_parameters()

        if debug_nan and not self._debug_checked_params:
            self._debug_checked_params = True
            with torch.no_grad():
                def _stat(t: torch.Tensor, name: str) -> None:
                    nan_cnt = torch.isnan(t).sum().item()
                    inf_cnt = torch.isinf(t).sum().item()
                    max_val = torch.max(torch.abs(t)).item() if t.numel() else 0.0
                    print(
                        f"[Quicksviewer2][DEBUG NaNCheck][{name}] shape={tuple(t.shape)} "
                        f"nan={nan_cnt} inf={inf_cnt} max={max_val}"
                    )

                _stat(self.query, "resampler_query")
                _stat(self.proj, "resampler_proj")
                _stat(self.kv_proj.weight, "resampler_kv_proj.weight")
                if self.kv_proj.bias is not None:
                    _stat(self.kv_proj.bias, "resampler_kv_proj.bias")
                for idx, ln in enumerate([self.ln_q, self.ln_kv, self.ln_post]):
                    _stat(ln.weight, f"resampler_ln{idx}.weight")
                    _stat(ln.bias, f"resampler_ln{idx}.bias")
                if hasattr(self.attn, "in_proj_weight") and self.attn.in_proj_weight is not None:
                    _stat(self.attn.in_proj_weight, "resampler_attn.in_proj_weight")
                if hasattr(self.attn, "out_proj") and self.attn.out_proj is not None:
                    _stat(self.attn.out_proj.weight, "resampler_attn.out_proj.weight")

        # ==== 范围规范化 ====
        if len(tgt_size_range) == 1 and isinstance(tgt_size_range[0], (list, tuple)):
            tgt_size_range = tgt_size_range[0]
        if len(tgt_size_range) == 2:
            tgt_size_range = [[0, 1], tgt_size_range[0], tgt_size_range[1]]
        # 将纯 int 维度扩展成 [0, int](对齐参考实现)
        tgt_size_range = [[0, d] if isinstance(d, int) else d for d in tgt_size_range]
        if len(tgt_size_range) != 3:
            raise ValueError(f"tgt_size_range 期望包含 3 个维度,收到 {tgt_size_range}")

        t_range, h_range, w_range = tgt_size_range
        t_start, t_end = t_range
        h_start, h_end = h_range
        w_start, w_end = w_range

        # ==== 位置网格 (含 FPS 缩放) ====
        t_positions = torch.arange(t_start, t_end, device=device, dtype=torch.float32)
        effective_fps = self.effective_video_fps if fps is None else float(fps)
        if effective_fps > 0 and effective_fps != self.reference_fps:
            t_positions = t_positions * (self.reference_fps / effective_fps)

        h_positions = torch.arange(h_start, h_end, device=device, dtype=torch.float32)
        w_positions = torch.arange(w_start, w_end, device=device, dtype=torch.float32)

        grid_t, grid_h, grid_w = torch.meshgrid(t_positions, h_positions, w_positions, indexing="ij")
        flat_t, flat_h, flat_w = grid_t.flatten(), grid_h.flatten(), grid_w.flatten()

        expected_len = (t_end - t_start) * (h_end - h_start) * (w_end - w_start)
        if expected_len != L:
            raise ValueError(f"RoPE 位置数 {expected_len} 与输入长度 {L} 不匹配")

        # ==== RoPE 频率 ====
        max_t = max(int(flat_t.max().item()) + 1, 1)
        max_h = max(int(flat_h.max().item()) + 1, 1)
        max_w = max(int(flat_w.max().item()) + 1, 1)

        freqs_t = self.rope_t(max_t, device=device, dtype=dtype)
        freqs_h = self.rope_h(max_h, device=device, dtype=dtype)
        freqs_w = self.rope_w(max_w, device=device, dtype=dtype)

        def _gather(freqs: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
            if (positions % 1.0 != 0).any():
                return interpolate_rope_freqs(freqs, positions)
            return freqs[positions.long()]

        freq_t = _gather(freqs_t, flat_t)
        freq_h = _gather(freqs_h, flat_h)
        freq_w = _gather(freqs_w, flat_w)
        freqs = torch.cat([freq_t, freq_h, freq_w], dim=-1)
        cos, sin = freqs.cos(), freqs.sin()

        # ==== KV + RoPE ====
        kv = self.kv_proj(cube_features)  # [B, L, lm_dim]
        kv = self.ln_kv(kv).permute(1, 0, 2)  # [L, B, lm_dim]
        if debug_nan and kv.numel() > 0:
            nan_kv = torch.isnan(kv).sum().item()
            inf_kv = torch.isinf(kv).sum().item()
            if nan_kv > 0 or inf_kv > 0:
                print(
                    f"[Quicksviewer2][DEBUG NaNCheck][resampler_kv] shape={tuple(kv.shape)} "
                    f"dtype={kv.dtype} nan={nan_kv} inf={inf_kv}"
                )

        cos_expanded = cos.unsqueeze(1)  # [L, 1, lm_dim]
        sin_expanded = sin.unsqueeze(1)
        kv_rot = apply_rotary_pos_emb(kv, cos_expanded, sin_expanded)
        if debug_nan and kv_rot.numel() > 0:
            nan_kv_rot = torch.isnan(kv_rot).sum().item()
            inf_kv_rot = torch.isinf(kv_rot).sum().item()
            if nan_kv_rot > 0 or inf_kv_rot > 0:
                print(
                    f"[Quicksviewer2][DEBUG NaNCheck][resampler_kv_rot] shape={tuple(kv_rot.shape)} "
                    f"dtype={kv_rot.dtype} nan={nan_kv_rot} inf={inf_kv_rot}"
                )

        # ==== 查询 ====
        q = self.ln_q(self.query).unsqueeze(1).repeat(1, B, 1)  # [num_queries, B, lm_dim]
        q_cos = torch.ones_like(q)
        q_sin = torch.zeros_like(q)
        q_rot = apply_rotary_pos_emb(q, q_cos, q_sin)

        # ==== 交叉注意力 ====
        out = self.attn(q_rot, kv_rot, kv, key_padding_mask=None)[0]  # [num_queries, B, lm_dim]

        # ==== 输出 ====
        out = out.permute(1, 0, 2)  # [B, num_queries, lm_dim]
        out = self.ln_post(out)
        out = out @ self.proj
        if debug_nan and out.numel() > 0:
            nan_out = torch.isnan(out).sum().item()
            inf_out = torch.isinf(out).sum().item()
            if nan_out > 0 or inf_out > 0:
                print(
                    f"[Quicksviewer2][DEBUG NaNCheck][resampler_out] shape={tuple(out.shape)} "
                    f"dtype={out.dtype} nan={nan_out} inf={inf_out}"
                )
        return out.squeeze(0)


__all__ = ["Quicksviewer2Resampler"]