TextVR_ckpt4000 / resampler_quicksviewer2.py
EdgePro001's picture
Upload folder using huggingface_hub
7e0b12a verified
Raw History Blame Contribute Delete
14.4 kB
# 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"]