Download cubing_quicksviewer2.py from EdgePro001/TextVR_ckpt4000: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/EdgePro001/TextVR_ckpt4000/resolve/main/cubing_quicksviewer2.py
- Command line
-
hf download hf://EdgePro001/TextVR_ckpt4000/cubing_quicksviewer2.py
-
curl -L -o cubing_quicksviewer2.py https://huggingface.co/EdgePro001/TextVR_ckpt4000/resolve/main/cubing_quicksviewer2.py
14.9 kB
| # cubing_quicksivewer2.py | |
| from __future__ import annotations | |
| from typing import Any, List, Optional, Sequence, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # ============================================================================= | |
| # ==== Gumbel 采样工具 ==== | |
| # ============================================================================= | |
| def _sample_gumbel( | |
| shape: Tuple[int, ...], device: torch.device, dtype: torch.dtype, eps: float = 1e-20 | |
| ) -> torch.Tensor: | |
| """生成 Gumbel 噪声(使用与输入一致的 dtype/device)。""" | |
| uniform = torch.rand(shape, device=device, dtype=dtype) | |
| noise = -torch.log(-torch.log(uniform + eps) + eps) | |
| return noise | |
| def _straight_through_topk( | |
| logits: torch.Tensor, | |
| temperature: float, | |
| topk: int, | |
| lr_gumbel: float, | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """对 gate logits 进行 Straight-Through Gumbel-Softmax 采样。""" | |
| if logits.ndim != 3: | |
| raise ValueError(f"Expected logits as [B, N, 2], got {logits.shape}") | |
| if logits.shape[-1] != 2: | |
| raise ValueError(f"Gate logits last dim should be 2, but got {logits.shape[-1]}") | |
| safe_temperature = max(float(temperature), 1e-5) | |
| safe_lr = max(float(lr_gumbel), 0.0) | |
| bsz, seq_len, _ = logits.shape | |
| topk = max(1, min(int(topk), seq_len)) | |
| noise = _sample_gumbel(logits.shape, logits.device, logits.dtype) * safe_lr | |
| noisy_logits = logits + noise | |
| probs = torch.softmax(noisy_logits / safe_temperature, dim=-1) | |
| key_probs = probs[..., 1] # [B, N] | |
| _, indices = torch.topk(key_probs, k=topk, dim=-1) | |
| hard_mask = torch.zeros_like(key_probs) | |
| hard_mask.scatter_(1, indices, 1.0) | |
| hard_mask = (hard_mask - key_probs).detach() + key_probs | |
| return key_probs.to(logits.dtype), hard_mask.to(logits.dtype) | |
| def _find_segments(z_hard: torch.Tensor) -> List[Tuple[int, int]]: | |
| """依据 keyframe mask 推导每个 cube 的 [start, end) 边界。""" | |
| length = z_hard.shape[0] | |
| if length == 0: | |
| return [] | |
| segments: List[Tuple[int, int]] = [] | |
| start = 0 | |
| for idx in range(length): | |
| is_last = idx == length - 1 | |
| next_is_key = not is_last and z_hard[idx + 1] > 0 | |
| if is_last or next_is_key: | |
| segments.append((start, idx + 1)) | |
| start = idx + 1 | |
| if segments and segments[-1][1] < length: | |
| segments.append((segments[-1][1], length)) | |
| return segments | |
| # ============================================================================= | |
| # ==== Cubing 实现 ==== | |
| # ============================================================================= | |
| class Quicksviewer2CubingModule(nn.Module): | |
| """ | |
| Momentum + Gumbel Cubing 模块:在不改变推理路径的前提下, | |
| 统计关键帧边界并生成可选的缩略图特征写入 metadata。 | |
| """ | |
| def __init__(self, config) -> None: | |
| super().__init__() | |
| self.config = config | |
| vision_config = getattr(config, "vision_config", config) | |
| text_config = getattr(config, "text_config", config) | |
| # Cubing 在 pre-merge 特征上运行,维度 = vision hidden_size | |
| self.vision_dim = int(getattr(vision_config, "hidden_size", getattr(vision_config, "out_hidden_size"))) | |
| self.language_dim = int(getattr(text_config, "hidden_size", self.vision_dim)) | |
| self.spatial_merge = int(getattr(vision_config, "spatial_merge_size", 1)) | |
| self.alpha = float(getattr(config, "cubing_alpha", 0.8)) | |
| # Default fallback matches reference cubing fpq=14 | |
| self.frames_per_query = max(1, int(getattr(config, "cubing_fpq", 14))) | |
| self.temperature = float(getattr(config, "cubing_temperature", 0.5)) | |
| self.lr_gumbel_start = float(getattr(config, "cubing_lr_gumbel_start", 1.0)) | |
| self.lr_gumbel_end = float(getattr(config, "cubing_lr_gumbel_end", 0.001)) | |
| self.use_thumbnail = bool(getattr(config, "cubing_use_thumbnail", True)) | |
| self.thumbnail_num_queries = max( | |
| 1, | |
| int( | |
| getattr( | |
| config, | |
| "thumbnail_num_queries", | |
| getattr(config, "thumbnail_num_queries", 64), | |
| ) | |
| ), | |
| ) | |
| # ==== Momentum & Gate 网络 ==== | |
| self.agg_frame_fn = nn.Sequential( | |
| nn.Linear(self.vision_dim, self.vision_dim), | |
| ) | |
| self.gate_network = nn.Sequential( | |
| nn.LayerNorm(self.vision_dim), | |
| nn.Linear(self.vision_dim, self.vision_dim), | |
| nn.GELU(), | |
| nn.Linear(self.vision_dim, 2), | |
| ) | |
| if self.use_thumbnail: | |
| self.thumbnail_fn = nn.Linear(self.vision_dim, self.language_dim) | |
| else: | |
| self.thumbnail_fn = None | |
| # 默认关闭 NaN 调试输出,可通过 config.debug_cubing_logs 显式打开 | |
| self._debug_nan = bool(getattr(config, "debug_cubing_logs", False)) | |
| self._debug_params_checked = False | |
| def _has_nonfinite_params(self) -> bool: | |
| 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 learnable parameters to defaults.""" | |
| def _reset(m): | |
| if hasattr(m, "reset_parameters"): | |
| m.reset_parameters() | |
| self.apply(_reset) | |
| # ========================================================================= | |
| # ==== 公共接口 ==== | |
| # ========================================================================= | |
| def forward( | |
| self, | |
| video_embeds: Sequence[torch.Tensor], | |
| metadata: Any, | |
| videos_bound: Optional[Sequence[Tuple[int, int]]] = None, | |
| ) -> Tuple[Sequence[torch.Tensor], Any]: | |
| if not video_embeds: | |
| metadata.cube_bounds = [] | |
| metadata.z_hard = [] | |
| metadata.gate_logits = [] | |
| metadata.thumbnail = [] if self.use_thumbnail else None | |
| return video_embeds, metadata | |
| if self._debug_nan and (self._has_nonfinite_params() or not self._debug_params_checked): | |
| self._debug_params_checked = True | |
| has_bad = self._has_nonfinite_params() | |
| if has_bad: | |
| print("[Quicksviewer2][DEBUG NaNCheck] Non-finite params detected in cubing, re-initializing.") | |
| self._reset_parameters() | |
| grid_thw = getattr(metadata, "original_grid_thw", None) | |
| if grid_thw is None: | |
| raise ValueError("metadata.original_grid_thw 缺失,无法执行 Cubing。") | |
| if grid_thw.shape[0] != len(video_embeds): | |
| raise ValueError( | |
| f"metadata 与视频特征数量不一致:metadata={grid_thw.shape[0]} videos={len(video_embeds)}" | |
| ) | |
| cube_bounds_all: List[List[Tuple[int, int]]] = [] | |
| gate_logits_all: List[torch.Tensor] = [] | |
| z_hard_all: List[torch.Tensor] = [] | |
| z_soft_all: List[torch.Tensor] = [] | |
| thumbnail_all: List[Optional[torch.Tensor]] = [] | |
| processed_chunks: List[torch.Tensor] = [] | |
| for chunk, thw in zip(video_embeds, grid_thw): | |
| result = self._process_single_video(chunk, thw.to(chunk.device), metadata) | |
| cube_bounds_all.append(result["cube_bounds"]) | |
| gate_logits_all.append(result["gate_logits"]) | |
| z_hard_all.append(result["z_hard"]) | |
| z_soft_all.append(result.get("z_soft", torch.empty(0, device=chunk.device, dtype=chunk.dtype))) | |
| thumbnail_all.append(result["thumbnail"]) | |
| processed_chunks.append(chunk) | |
| metadata.cube_bounds = cube_bounds_all | |
| metadata.gate_logits = gate_logits_all | |
| metadata.z_hard = z_hard_all | |
| metadata.z_soft = z_soft_all | |
| metadata.thumbnail = thumbnail_all if self.use_thumbnail else None | |
| return tuple(processed_chunks), metadata | |
| # ========================================================================= | |
| # ==== 单视频处理 ==== | |
| # ========================================================================= | |
| def _process_single_video( | |
| self, | |
| video_tokens: torch.Tensor, | |
| thw_row: torch.Tensor, | |
| metadata: Any, | |
| ) -> dict: | |
| device = video_tokens.device | |
| dtype = video_tokens.dtype | |
| temporal = int(video_tokens.shape[0]) | |
| tokens_per_frame = int(video_tokens.shape[1]) if video_tokens.ndim >= 2 else 0 | |
| self._check_finite("input_video_tokens", video_tokens) | |
| if temporal == 0 or tokens_per_frame == 0: | |
| empty = torch.empty(0, 2, device=device, dtype=dtype) | |
| return { | |
| "cube_bounds": [], | |
| "gate_logits": empty, | |
| "z_hard": torch.empty(0, device=device, dtype=dtype), | |
| "thumbnail": None, | |
| } | |
| reshaped = video_tokens | |
| if temporal == 1: | |
| z_hard_single = torch.ones(1, device=device, dtype=dtype) | |
| z_soft_single = z_hard_single.clone() | |
| return { | |
| "cube_bounds": [(0, 1)], | |
| "gate_logits": torch.empty(0, 2, device=device, dtype=dtype), | |
| "z_hard": z_hard_single, | |
| "z_soft": z_soft_single, | |
| "thumbnail": self._build_thumbnail(reshaped, z_hard_single), | |
| "tokens_per_frame": tokens_per_frame, | |
| } | |
| # Diff-first momentum on patch-level features, then aggregate per frame | |
| vid_feats = self._calculate_momentum(reshaped) # [T-1, HW, D] | |
| vid_feats = self.agg_frame_fn(vid_feats).mean(dim=1) # [T-1, D] | |
| self._check_finite("momentum_feats", vid_feats) | |
| gate_logits = self.gate_network(vid_feats) | |
| self._check_finite("gate_logits", gate_logits) | |
| temporal_patch = max(int(getattr(metadata, "temporal_patch_size", 2)), 1) | |
| # 优先使用预计算的 effective_cubing_fpq | |
| effective_fpq = getattr(self.config, "effective_cubing_fpq", None) | |
| if effective_fpq is None: | |
| effective_fpq = max(self.frames_per_query / float(temporal_patch), 1.0) | |
| desired_cubes = max(int(round(temporal / effective_fpq)) - 1, 1) | |
| lr_gumbel = getattr(self.config, "_current_lr_gumbel", None) | |
| if lr_gumbel is None: | |
| # Align with exp: default to start value unless外部显式调度 | |
| lr_gumbel = self.lr_gumbel_start | |
| probs, hard = _straight_through_topk( | |
| gate_logits.unsqueeze(0), | |
| temperature=self.temperature, | |
| topk=desired_cubes, | |
| lr_gumbel=lr_gumbel, | |
| ) | |
| probs = probs.squeeze(0) | |
| hard = hard.squeeze(0) | |
| z_hard = torch.cat( | |
| [ | |
| torch.ones(1, device=device, dtype=hard.dtype), | |
| hard, | |
| ], | |
| dim=0, | |
| ) | |
| z_soft = torch.cat( | |
| [ | |
| torch.ones(1, device=device, dtype=probs.dtype), | |
| probs, | |
| ], | |
| dim=0, | |
| ) | |
| cube_bounds = _find_segments(z_hard) | |
| # thumbnail uses frame-level features (aggregated per frame) | |
| thumbnail = self._build_thumbnail(reshaped, z_hard) | |
| self._check_finite("thumbnail", thumbnail) | |
| return { | |
| "cube_bounds": cube_bounds, | |
| "gate_logits": gate_logits, | |
| "z_hard": z_hard.to(dtype), | |
| "z_soft": z_soft.to(dtype), | |
| "thumbnail": thumbnail, | |
| "tokens_per_frame": tokens_per_frame, | |
| } | |
| # ========================================================================= | |
| # ==== 辅助函数 ==== | |
| # ========================================================================= | |
| def _check_finite(self, name: str, tensor: Optional[torch.Tensor]) -> None: | |
| if not self._debug_nan or tensor is None: | |
| return | |
| if tensor.numel() == 0: | |
| return | |
| nan_count = torch.isnan(tensor).sum().item() | |
| inf_count = torch.isinf(tensor).sum().item() | |
| if nan_count > 0 or inf_count > 0: | |
| print( | |
| f"[Quicksviewer2][DEBUG NaNCheck][{name}] shape={tuple(tensor.shape)} " | |
| f"dtype={tensor.dtype} device={tensor.device} nan={nan_count} inf={inf_count}" | |
| ) | |
| def _calculate_momentum(self, frame_features: torch.Tensor) -> torch.Tensor: | |
| """计算 momentum 序列,输出张量长度为 T-1。""" | |
| deltas = frame_features[1:] - frame_features[:-1] | |
| momentum_list = [deltas[0]] | |
| alpha = float(self.alpha) | |
| for delta in deltas[1:]: | |
| momentum_list.append(alpha * delta + (1 - alpha) * momentum_list[-1]) | |
| return torch.stack(momentum_list, dim=0) | |
| def _build_thumbnail(self, frame_features: torch.Tensor, z_hard: torch.Tensor) -> Optional[torch.Tensor]: | |
| """ | |
| 构建缩略图特征,输出 [thumbnail_num_queries, language_dim]。 | |
| 对齐 Exp modeling_glm4v_withCube.py L275-315: | |
| 1. 使用 z_hard 加权原始 video_features | |
| 2. 使用 adaptive_avg_pool1d 压缩到 thumbnail_num_queries 个 token | |
| 3. 投影到 language_dim | |
| Args: | |
| frame_features: [N, num_patches, vision_dim] | |
| z_hard: [N] keyframe mask | |
| Returns: | |
| thumbnail: [thumbnail_num_queries, language_dim] 或 None | |
| """ | |
| if not self.use_thumbnail or self.thumbnail_fn is None: | |
| return None | |
| weights = z_hard.to(frame_features.dtype) | |
| total = weights.sum() | |
| if total <= 0: | |
| return None | |
| # 加权聚合: [N, num_patches, vision_dim] | |
| weights_expanded = weights.unsqueeze(-1).unsqueeze(-1) # [N, 1, 1] | |
| weighted_feats = frame_features * weights_expanded # [N, num_patches, vision_dim] | |
| # Sum over frames and normalize | |
| thumbnail_feat = weighted_feats.sum(dim=0, keepdim=True) # [1, num_patches, vision_dim] | |
| thumbnail_feat = thumbnail_feat / total | |
| # Transpose for AdaptiveAvgPool1d: [1, num_patches, vision_dim] → [1, vision_dim, num_patches] | |
| thumbnail_feat = thumbnail_feat.permute(0, 2, 1) | |
| # Compress num_patches to thumbnail_num_queries tokens | |
| # [1, vision_dim, num_patches] → [1, vision_dim, thumbnail_num_queries] | |
| thumbnail_feat = F.adaptive_avg_pool1d(thumbnail_feat, self.thumbnail_num_queries) | |
| # Transpose back: [1, vision_dim, thumbnail_num_queries] → [1, thumbnail_num_queries, vision_dim] | |
| thumbnail_feat = thumbnail_feat.permute(0, 2, 1) | |
| # Remove batch dimension: [thumbnail_num_queries, vision_dim] | |
| thumbnail_feat = thumbnail_feat.squeeze(0) | |
| # Project to language_dim: [thumbnail_num_queries, language_dim] | |
| thumbnail = self.thumbnail_fn(thumbnail_feat) | |
| return thumbnail | |
| __all__ = ["Quicksviewer2CubingModule"] | |