TextVR_ckpt4000 / modeling_quicksviewer2.py
EdgePro001's picture
Upload folder using huggingface_hub
7e0b12a verified
Raw History Blame Contribute Delete
94.3 kB
# modeling_quicksviewer2.py from __future__ import annotations import itertools import os import csv from dataclasses import dataclass from typing import List, Optional, Sequence, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.glm4v import modeling_glm4v as _glm4v from transformers.cache_utils import Cache from transformers.utils import logging from .configuration_quicksviewer2 import ( Quicksviewer2Config, Quicksviewer2TextConfig, Quicksviewer2VisionConfig, ) from .cubing_quicksviewer2 import Quicksviewer2CubingModule from .resampler_quicksviewer2 import Quicksviewer2Resampler logger = logging.get_logger(__name__) # 全局调试开关:导出 QUICKSVIEWER2_DEBUG=1 才会打印调试信息 DEBUG_ENABLED = os.getenv("QUICKSVIEWER2_DEBUG", "0") == "1" def debug_print(*args, **kwargs) -> None: """Lightweight debug print that prefixes rank when分布式可用。""" if not DEBUG_ENABLED: return prefix = "" try: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): prefix = f"[Rank {dist.get_rank()}] " except Exception: prefix = "" if prefix: if args: args = (prefix + str(args[0]), *args[1:]) else: args = (prefix,) print(*args, **kwargs) # ============================================================================= # ==== 元数据工具 ==== # ============================================================================= @dataclass class Quicksviewer2VideoMetadata: original_grid_thw: torch.LongTensor temporal_patch_size: int mode: str = "native" pre_merge: bool = False use_thumbnail: bool = True thumbnail_num_queries: int = 64 actual_num_tokens: Optional[int] = None tgt_size_range: Optional[List[List[Tuple[int, int]]]] = None cube_bounds: Optional[List[List[Tuple[int, int]]]] = None z_hard: Optional[List[torch.Tensor]] = None z_soft: Optional[List[torch.Tensor]] = None gate_logits: Optional[List[torch.Tensor]] = None thumbnail: Optional[List[Optional[torch.Tensor]]] = None cube_tgt_size_ranges: Optional[List[List[List[List[int]]]]] = None video_token_counts: Optional[List[int]] = None cube_timestamps: Optional[List[List[str]]] = None # 逐视频的时间戳字符串 cube_timestamp_tokens: Optional[List[List[List[int]]]] = None # 逐视频逐 cube 的时间戳 token ids # MRoPE 相关字段 mrope_positions: Optional[torch.Tensor] = None # 形状: (3, num_tokens) mrope_adjusted: bool = False # 是否已为 Cubing 调整了 MRoPE original_token_count: Optional[int] = None # 原始 token 数量(用于调试) def to_flattened_native(self, device: Optional[torch.device] = None) -> torch.LongTensor: """展平为逐帧 Grid,保持 GLM-4.1V 的 native 处理路径。""" if self.original_grid_thw.numel() == 0: base = self.original_grid_thw.new_zeros((0, 3)) return base.to(device=device) if device is not None else base flattened_chunks: List[torch.LongTensor] = [] for thw in self.original_grid_thw: t, h, w = (int(thw[0].item()), int(thw[1].item()), int(thw[2].item())) repeated = thw.new_tensor([1, h, w]).unsqueeze(0).repeat(t, 1) flattened_chunks.append(repeated) flattened = torch.cat(flattened_chunks, dim=0) return flattened.to(device=device) if device is not None else flattened def to_temporal_grid(self, device: Optional[torch.device] = None) -> torch.LongTensor: """构造 Cubing 需要的 temporal grid(每个条目长度为 temporal_patch_size)。""" flattened_chunks: List[torch.LongTensor] = [] for thw in self.original_grid_thw: t = int(thw[0].item()) h = int(thw[1].item()) w = int(thw[2].item()) temporal_patch = max(int(self.temporal_patch_size), 1) num_temporal_tokens = max(t // temporal_patch, 1) repeated = thw.new_tensor([temporal_patch, h, w]).unsqueeze(0).repeat(num_temporal_tokens, 1) flattened_chunks.append(repeated) base = torch.cat(flattened_chunks, dim=0) if flattened_chunks else self.original_grid_thw.new_zeros((0, 3)) return base.to(device=device) if device is not None else base # ==== 共享组件别名 ==== def rotate_half_llm(x: torch.Tensor) -> torch.Tensor: """Rotate half the hidden dims of the input.""" x1 = x[..., 0::2] x2 = x[..., 1::2] return torch.stack((-x2, x1), dim=-1).flatten(-2) def apply_multimodal_rotary_pos_emb( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, mrope_section: Sequence[int], unsqueeze_dim=1 ) -> tuple[torch.Tensor, torch.Tensor]: """Apply 3D MRoPE to Q/K.""" mrope_section = [int(x) for x in mrope_section] split_sizes = [s * 2 for s in mrope_section] cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(split_sizes, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim) sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(split_sizes, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim) cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1) sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1) rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:] q_embed = (q_rot * cos) + (rotate_half_llm(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half_llm(k_rot) * sin) q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed class Quicksviewer2TextAttention(_glm4v.Glm4vTextAttention): """MRoPE-aware text attention used by Quicksviewer2.""" def __init__(self, config: Quicksviewer2TextConfig, layer_idx: Optional[int] = None): super().__init__(config, layer_idx) self.rope_scaling = getattr(config, "rope_scaling", None) self.rope_parameters = getattr(config, "rope_parameters", None) or {} def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[_glm4v.Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings mrope_section = None if self.rope_scaling is not None: mrope_section = self.rope_scaling.get("mrope_section") if mrope_section is None: mrope_section = self.rope_parameters.get("mrope_section", [0, 0, 0]) query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, mrope_section ) if past_key_values is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface = _glm4v.eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = _glm4v.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights class Quicksviewer2TextDecoderLayer(_glm4v.GradientCheckpointingLayer): def __init__(self, config: Quicksviewer2TextConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Quicksviewer2TextAttention(config, layer_idx) self.mlp = _glm4v.Glm4vTextMLP(config) self.input_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_self_attn_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_mlp_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) @_glm4v.auto_docstring def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[_glm4v.Cache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, _ = self.self_attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = self.post_self_attn_layernorm(hidden_states) residual = residual.to(hidden_states.device) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = self.post_mlp_layernorm(hidden_states) residual = residual.to(hidden_states.device) hidden_states = residual + hidden_states return hidden_states class Quicksviewer2TextModel(_glm4v.Glm4vTextModel): """Text backbone that swaps in MRoPE-aware attention layers.""" config: Quicksviewer2TextConfig config_class = Quicksviewer2TextConfig input_modalities = "text" def __init__(self, config: Quicksviewer2TextConfig): _glm4v.Glm4vPreTrainedModel.__init__(self, config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Quicksviewer2TextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = _glm4v.Glm4vTextRotaryEmbedding(config=config) self.gradient_checkpointing = False self.post_init() # ==== 优化版 Vision Patch Embed(channels_last_3d) ==== class Quicksviewer2VisionPatchEmbed(nn.Module): def __init__(self, config: Quicksviewer2VisionConfig) -> None: super().__init__() self.patch_size = config.patch_size self.temporal_patch_size = config.temporal_patch_size self.in_channels = config.in_channels self.embed_dim = config.hidden_size kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size] proj = nn.Conv3d( self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, ) self._channels_last_available = False if torch.cuda.is_available(): try: proj = proj.to(memory_format=torch.channels_last_3d) self._channels_last_available = True except Exception: # 保持回退路径 pass self.proj = proj def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: target_dtype = self.proj.weight.dtype hidden_states = hidden_states.view( -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size ) if self._channels_last_available and hidden_states.is_cuda: hidden_states = hidden_states.to(dtype=target_dtype, memory_format=torch.channels_last_3d) else: hidden_states = hidden_states.to(dtype=target_dtype) hidden_states = self.proj(hidden_states).view(-1, self.embed_dim) return hidden_states Quicksviewer2TextRotaryEmbedding = _glm4v.Glm4vTextRotaryEmbedding Quicksviewer2TextMLP = _glm4v.Glm4vTextMLP Quicksviewer2TextDecoderLayer = Quicksviewer2TextDecoderLayer Quicksviewer2TextAttention = Quicksviewer2TextAttention Quicksviewer2TextModel = Quicksviewer2TextModel Quicksviewer2RMSNorm = _glm4v.Glm4vRMSNorm Quicksviewer2VisionPatchEmbed = Quicksviewer2VisionPatchEmbed Quicksviewer2VisionRotaryEmbedding = _glm4v.Glm4vVisionRotaryEmbedding Quicksviewer2VisionPatchMerger = _glm4v.Glm4vVisionPatchMerger Quicksviewer2VisionEmbeddings = _glm4v.Glm4vVisionEmbeddings Quicksviewer2VisionAttention = _glm4v.Glm4vVisionAttention Quicksviewer2VisionBlock = _glm4v.Glm4vVisionBlock Quicksviewer2ModelOutputWithPast = _glm4v.Glm4vModelOutputWithPast Quicksviewer2CausalLMOutputWithPast = _glm4v.Glm4vCausalLMOutputWithPast # ==== 预训练模型包装 ==== class Quicksviewer2PreTrainedModel(_glm4v.Glm4vPreTrainedModel): config_class = Quicksviewer2Config class Quicksviewer2VisionModel(_glm4v.Glm4vVisionModel): config_class = Quicksviewer2VisionConfig class Quicksviewer2Model(_glm4v.Glm4vModel): config_class = Quicksviewer2Config def __init__(self, config: Quicksviewer2Config): super().__init__(config) self._latest_video_metadata: Optional[Quicksviewer2VideoMetadata] = None self._cubing_module: Optional[Quicksviewer2CubingModule] = None self._resampler: Optional[Quicksviewer2Resampler] = None # 替换视觉 patch_embed 为 channels_last_3d 优化版 try: old_patch = getattr(self.visual, "patch_embed", None) if old_patch is not None: new_patch = Quicksviewer2VisionPatchEmbed(config.vision_config) new_patch.load_state_dict(old_patch.state_dict(), strict=False) self.visual.patch_embed = new_patch except Exception: # 失败则保留原实现 pass # ==== 替换文本主干以启用 MRoPE ==== self.language_model = Quicksviewer2TextModel._from_config(config.text_config) if getattr(config, "use_cubing", False): self.initialize_cubing_modules_if_needed() def _debug_logs_enabled(self) -> bool: # 允许通过配置开关启用详细调试日志,默认关闭: # config.debug_cubing_logs = True return DEBUG_ENABLED and bool(getattr(self.config, "debug_cubing_logs", False)) # ==== 覆盖父类方法,修复 GLM4V 的 video token ID bug ==== def get_placeholder_mask( self, input_ids: Optional[torch.LongTensor], inputs_embeds: torch.FloatTensor, image_features: Optional[torch.FloatTensor] = None, video_features: Optional[torch.FloatTensor] = None, ): """ Quicksviewer2 覆盖版本:修复父类 GLM4V 中 video_token_id 错误使用 image_token_id 的 bug。 父类 GLM4V L1210 有 bug (注释说 "GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask"): special_video_mask = input_ids == self.config.image_token_id # ❌ 错误 这可能是因为原始 GLM4V 中 image 和 video 使用同一个 token ID (通过 wrapper tokens 区分)。 但在 Quicksviewer2 配置中: - image_token_id = 151343 - video_token_id = 151344 ← 不同的 ID! 因此需要修正为: special_video_mask = input_ids == self.config.video_token_id # ✅ 正确 """ if input_ids is None: base_image_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) base_image_mask = base_image_mask.all(-1) base_video_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device) ) base_video_mask = base_video_mask.all(-1) else: base_image_mask = input_ids == self.config.image_token_id base_video_mask = input_ids == self.config.video_token_id n_image_tokens = int(base_image_mask.sum().item()) if image_features is not None and base_image_mask.sum().item() != image_features.shape[0]: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}" ) # 对视频占位符做严格匹配,与参考实现一致:占位符数必须等于特征数 n_video_tokens = int(base_video_mask.sum().item()) if video_features is not None: expected_video_tokens = int(video_features.shape[0]) if n_video_tokens != expected_video_tokens: raise ValueError( f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}" ) special_image_mask = base_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) special_video_mask = base_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel(): raise ValueError( f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}" ) return special_image_mask, special_video_mask def _debug_log(self, message: str) -> None: if self._debug_logs_enabled(): debug_print(f"[Quicksviewer2][DEBUG] {message}") def _log_cubing_metadata_summary(self, metadata: Optional[Quicksviewer2VideoMetadata]) -> None: if not self._debug_logs_enabled() or metadata is None: return counts = metadata.video_token_counts or [] bounds = metadata.cube_bounds or [] summary = [] for idx, grid in enumerate(metadata.original_grid_thw): frames = int(grid[0].item()) token_count = counts[idx] if idx < len(counts) else 0 cube_ranges = bounds[idx] if idx < len(bounds) else [] cube_count = len(cube_ranges) preview = ", ".join(f"{int(s)}-{int(e)}" for s, e in cube_ranges[:5]) if cube_count > 5: preview += ", ..." summary.append( f"video{idx}: frames={frames}, cubes={cube_count}, tokens={token_count}" + (f", bounds=[{preview}]" if preview else "") ) if summary: self._debug_log("Cubing summary -> " + "; ".join(summary)) else: self._debug_log("Cubing enabled but no video metadata available.") def _log_cubing_aux_loss(self) -> None: if not self._debug_logs_enabled(): return with torch.no_grad(): aux = self.get_cubing_aux_loss() if isinstance(aux, torch.Tensor): aux_value = aux.detach().float().cpu().item() else: aux_value = float(aux) debug_print(f"[Quicksviewer2][DEBUG] Cubing aux loss={aux_value:.6f}") # ========================================================================= # ==== 视频特征抽取 (含 metadata) ==== # ========================================================================= def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None, videos_bound: Optional[Sequence[Tuple[int, int]]] = None, return_metadata: bool = False, tokenizer=None, fps: Optional[float] = None, ): """ 对齐 Exp modeling_glm4v_withCube.py L2515-2562 的视频特征提取流程。 Args: pixel_values_videos: 视频像素值 video_grid_thw: 视频网格维度 [num_videos, 3] videos_bound: 帧边界列表 [(start, end), ...] return_metadata: 是否返回 metadata tokenizer: 用于编码时间戳的 tokenizer(cubing 模式必需) fps: 视频帧率 Returns: chunks: 视频特征元组 metadata: (可选) Quicksviewer2VideoMetadata 对象 """ import torch.distributed as dist if dist.is_initialized(): rank = dist.get_rank() print( f"[Rank {rank}] get_video_features: video_shape={tuple(pixel_values_videos.shape)}, " f"grid_thw={video_grid_thw.tolist() if isinstance(video_grid_thw, torch.Tensor) else video_grid_thw}", flush=True, ) if self._debug_logs_enabled(): debug_print( "[Quicksviewer2][DEBUG get_video_features] pixel_values_videos.shape=%s, video_grid_thw.shape=%s, use_cubing=%s" % ( tuple(pixel_values_videos.shape), tuple(video_grid_thw.shape) if video_grid_thw is not None else None, bool(getattr(self.config, "use_cubing", False)), ) ) if video_grid_thw is None: raise ValueError("video_grid_thw 必须提供以计算视频特征。") use_cubing = bool(getattr(self.config, "use_cubing", False)) metadata = self._build_video_metadata( video_grid_thw=video_grid_thw, mode="cubing" if use_cubing else "native", ) if use_cubing: # ==== Cubing 模式:对齐 Exp _get_video_features_with_cubing 流程 ==== self.initialize_cubing_modules_if_needed() # Step 1: 获取 pre-merge 特征(对齐 Exp L2627-2631: visual(return_before_merge=True)) premerge_chunks = self._get_video_features_with_cubing_premerge(pixel_values_videos, metadata) metadata.pre_merge = True if self._debug_logs_enabled(): fin = torch.isfinite(premerge_chunks[0]).all().item() if premerge_chunks else True nan_count = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0 debug_print(f"[Quicksviewer2][DEBUG NaNCheck][premerge_chunks] finite={fin} nan_total={nan_count}") # Step 2: 调用 cubing 模块获取 cube_bounds 等元数据 # 对齐 Exp L2670-2676: cubing_module(video_frames, fpq=..., temperature=..., lr_gumbel=...) if self._debug_logs_enabled(): pre_nan = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0 debug_print(f"[Quicksviewer2][DEBUG NaNCheck][cubing_input] nan_total={pre_nan}") _, metadata = self._cubing_module( premerge_chunks, metadata, videos_bound=videos_bound, ) # 缓存 gate_logits 供 aux loss 使用(对齐参考实现 _last_gate_logits) valid_logits = [ logits for logits in (metadata.gate_logits or []) if logits is not None and logits.numel() > 0 ] if valid_logits: self._last_gate_logits = torch.cat(valid_logits, dim=0) metadata.cube_tgt_size_ranges = self._build_cube_tgt_size_ranges(metadata) temporal_patch_size = int(getattr(self.config.vision_config, "temporal_patch_size", 2)) effective_fps = None if fps is not None and fps > 0: effective_fps = float(fps) / max(int(temporal_patch_size), 1) else: base_fps = float(getattr(self.config, "video_fps", -1.0)) if base_fps > 0: effective_fps = base_fps / max(int(temporal_patch_size), 1) elif self._resampler is not None: effective_fps = float(getattr(self._resampler, "effective_video_fps", -1.0)) # Step 3: 计算时间戳(对齐 Exp L2682-2698) # 注意:Exp 在 resampler 之前计算时间戳,我们也按此顺序 if metadata.cube_bounds: if tokenizer is None: raise ValueError("tokenizer must be provided in cubing mode to compute cube timestamps.") all_timestamps: List[List[str]] = [] all_timestamp_tokens: List[List[List[int]]] = [] for bounds in metadata.cube_bounds: ts = ( self._compute_cube_timestamps( cube_bounds=[(int(s), int(e)) for s, e in bounds], video_start_token=0, temporal_patch_size=temporal_patch_size, fps=effective_fps, ) if effective_fps and effective_fps > 0 else [] ) all_timestamps.append(ts) # 立即 tokenize 时间戳(对齐 Exp L2692-2698) per_cube_tokens: List[List[int]] = [] if tokenizer is not None and ts: for ts_text in ts: try: token_ids = tokenizer.encode(ts_text, add_special_tokens=False) except Exception: token_ids = [] per_cube_tokens.append(token_ids) elif ts: per_cube_tokens = [[] for _ in ts] all_timestamp_tokens.append(per_cube_tokens) metadata.cube_timestamps = all_timestamps metadata.cube_timestamp_tokens = all_timestamp_tokens # Step 4: 应用 resampler(对齐 Exp L2700-2727) if self._resampler is not None: if self._debug_logs_enabled(): nan_before = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0 debug_print(f"[Quicksviewer2][DEBUG NaNCheck][resampler_input] nan_total={nan_before}") resampler_fps = effective_fps if effective_fps and effective_fps > 0 else None chunks = self._apply_cubing_resampler(premerge_chunks, metadata, fps=resampler_fps) if self._debug_logs_enabled(): nan_after = sum(int(torch.isnan(c).sum().item()) for c in chunks) if chunks else 0 debug_print(f"[Quicksviewer2][DEBUG NaNCheck][resampler_output] nan_total={nan_after}") else: chunks = premerge_chunks self._log_cubing_metadata_summary(metadata) self._log_cubing_aux_loss() else: # ==== Native 模式:对齐 Exp _get_video_features_native ==== chunks = self._get_video_features_native(pixel_values_videos, metadata) self._debug_log("use_cubing=False; running native video path.") self._latest_video_metadata = metadata if return_metadata: return chunks, metadata return chunks def get_rope_index( self, input_ids: Optional[torch.LongTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ 计算 3D rope index,Cubing 模式使用专门的位置编码逻辑 """ metadata = self._latest_video_metadata use_cubing = bool(getattr(self.config, "use_cubing", False)) if ( use_cubing and metadata is not None and getattr(metadata, "mode", "native") == "cubing" and metadata.cube_bounds ): return self._get_rope_index_for_cubing( input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, ) return super().get_rope_index( input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, ) def _get_rope_index_for_cubing( self, input_ids: Optional[torch.LongTensor], image_grid_thw: Optional[torch.LongTensor], video_grid_thw: Optional[torch.LongTensor], attention_mask: Optional[torch.Tensor], ) -> tuple[torch.Tensor, torch.Tensor]: """ Cubing 模式的 RoPE 位置编码(支持时间戳和 Thumbnail) 完全对齐 modeling_glm4v_withCube.py L1095-1321 位置分配策略: - text: 连续递增 - video_start: 单个位置 - thumbnail: 连续递增(如果启用) - timestamp: 连续递增 - cube: linspace 分布,位置范围按帧数比例分配 - video_end: 单个位置 """ if input_ids is None: return super().get_rope_index( input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, ) metadata = self._latest_video_metadata if metadata is None or not metadata.cube_bounds: return super().get_rope_index( input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, ) batch_size = input_ids.shape[0] seq_len = input_ids.shape[1] device = input_ids.device video_token_id = getattr(self.config, "video_token_id", self.config.image_token_id) video_start_token_id = self.config.video_start_token_id video_end_token_id = self.config.video_end_token_id # 初始化 position_ids [3, batch_size, seq_len] # 3 对应 MRoPE 的 T/H/W 三个维度 position_ids = torch.ones( 3, batch_size, seq_len, dtype=torch.float32, device=device ) mrope_position_deltas = [] # === 主循环:逐 batch item 处理 === for i in range(batch_size): st_idx = 0 # 位置游标(T 维度的当前位置) cube_idx = 0 # 当前正在处理的 cube 索引 cube_video_token_idx = 0 # 当前 cube 内已处理的 video token 数 in_video_section = False # 是否在 video_start 和 video_end 之间 cube_start_pos = None # 当前 cube 的起始位置 # Thumbnail 相关状态 expecting_thumbnail = False thumbnail_token_count = 0 thumbnail_num_queries = int(getattr(metadata, "thumbnail_num_queries", 64)) # 为当前 batch item 计算每个 cube 的位置分配数量 cube_position_counts = None if metadata.cube_bounds and i < len(metadata.cube_bounds): cube_position_counts = self._allocate_cube_position_counts(metadata, batch_idx=i) resampler_num_queries = int(getattr(self.config, "resampler_num_queries", 64)) # === 逐 token 遍历 === for j in range(seq_len): # Padding 位置:跳过,保持默认值 1 if attention_mask is not None and attention_mask[i, j] == 0: position_ids[:, i, j] = 1 continue token = input_ids[i, j].item() # === 处理 <|video_start|> === if token == video_start_token_id: in_video_section = True position_ids[0, i, j] = st_idx position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 st_idx += 1 # 重置所有 cube 相关计数器 cube_idx = 0 cube_video_token_idx = 0 cube_start_pos = None # 初始化 thumbnail 状态 expecting_thumbnail = ( metadata is not None and getattr(metadata, "use_thumbnail", False) ) thumbnail_token_count = 0 continue # === 处理 Thumbnail tokens === elif (expecting_thumbnail and in_video_section and token == video_token_id and thumbnail_token_count < thumbnail_num_queries): # Thumbnail token: 使用连续递增位置 position_ids[0, i, j] = st_idx position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 st_idx += 1 thumbnail_token_count += 1 # 检查 Thumbnail 是否完成 if thumbnail_token_count >= thumbnail_num_queries: expecting_thumbnail = False # 重置 cube 相关计数器,准备处理后续 cubes cube_video_token_idx = 0 cube_start_pos = None continue # === 处理 <|video_end|> === elif token == video_end_token_id: in_video_section = False position_ids[0, i, j] = st_idx position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 st_idx += 1 continue # === 处理 <|video|> tokens (Cube 内容) === elif token == video_token_id and in_video_section and not expecting_thumbnail: # 检查是否需要切换到下一个 cube(当前 cube 已处理完 64 个 token) if cube_video_token_idx >= resampler_num_queries: cube_idx += 1 cube_video_token_idx = 0 cube_start_pos = None # 检查当前 cube 是否在有效范围内 if cube_position_counts is not None and cube_idx < len(cube_position_counts): num_positions = cube_position_counts[cube_idx] # 该 cube 分配的位置数量 num_tokens = resampler_num_queries # 64 # 初始化新 cube 的起始位置 if cube_video_token_idx == 0: cube_start_pos = st_idx # 使用 linspace 计算当前 token 的位置 # 64 个 token 均匀分布在 num_positions 个位置中 if num_tokens > 1: relative_pos = cube_video_token_idx / (num_tokens - 1) else: relative_pos = 0 actual_pos = cube_start_pos + relative_pos * (num_positions - 1) position_ids[0, i, j] = actual_pos position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 cube_video_token_idx += 1 # 当前 cube 处理完毕,更新 st_idx 到该 cube 位置范围的末尾 if cube_video_token_idx >= num_tokens: st_idx = cube_start_pos + num_positions else: # cube 索引超出范围,降级为连续递增位置 position_ids[0, i, j] = st_idx position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 st_idx += 1 continue # === 处理其他 tokens(普通文本、时间戳等)=== else: # 视频段内的非 video_token 视为时间戳 # 视频段外的视为普通文本 # 两者处理方式相同:连续递增位置 position_ids[0, i, j] = st_idx position_ids[1, i, j] = 1.0 position_ids[2, i, j] = 1.0 st_idx += 1 # 计算当前样本的 rope delta max_pos = position_ids[:, i, :].max() delta = max_pos + 1 - seq_len mrope_position_deltas.append(delta) # 转换 deltas 为 tensor mrope_position_deltas = torch.tensor( mrope_position_deltas, device=device, dtype=torch.float32 ).unsqueeze(1) return position_ids, mrope_position_deltas def _allocate_cube_position_counts( self, metadata: Quicksviewer2VideoMetadata, batch_idx: int = 0, ) -> List[int]: """ 计算指定 batch item 的每个 cube 应该占用多少个位置(按帧数比例分配) 完全对齐 modeling_glm4v_withCube.py L1368-1399 原理: - 每个 cube 包含固定数量的 token(resampler_num_queries,通常是 64) - 但每个 cube 对应的原始视频帧数不同 - 位置编码空间按帧数比例分配,使得时间上更长的 cube 在位置空间中也占据更大范围 例如:3 个 cubes 分别有 5、4、3 帧 - 总帧数 = 12 - 总位置数 = 3 × 64 = 192 - cube0 分配 192 × 5/12 ≈ 80 个位置 - cube1 分配 192 × 4/12 ≈ 64 个位置 - cube2 分配 192 × 3/12 ≈ 48 个位置 Args: metadata: 视频元数据 batch_idx: 当前 batch 的索引 Returns: List[int]: 每个 cube 的位置分配数量,例如 [80, 64, 48] """ if not metadata.cube_bounds or batch_idx >= len(metadata.cube_bounds): return [] cube_bounds = metadata.cube_bounds[batch_idx] num_cubes = len(cube_bounds) if num_cubes == 0: return [] resampler_num_queries = int(getattr(self.config, "resampler_num_queries", 64)) cube_total_tokens = num_cubes * resampler_num_queries # 不包括 thumbnail # 计算每个 cube 的帧数 cube_frames = [] for start_frame, end_frame in cube_bounds: num_frames = int(end_frame) - int(start_frame) cube_frames.append(max(num_frames, 1)) total_frames = max(sum(cube_frames), 1) # 按帧数比例分配位置数量 position_counts = [] for num_frames in cube_frames: allocated = int(round(cube_total_tokens * num_frames / total_frames)) position_counts.append(max(allocated, 1)) # 调整确保总和 = cube_total_tokens diff = cube_total_tokens - sum(position_counts) if diff != 0 and position_counts: position_counts[-1] += diff if self._debug_logs_enabled(): debug_print(f"\n[Quicksviewer2][DEBUG AllocatePositionCounts] Batch {batch_idx}:") debug_print(f" Cube total tokens: {cube_total_tokens}") debug_print(f" Cube frames: {cube_frames}") debug_print(f" Total frames: {total_frames}") debug_print(f" Position counts: {position_counts}") return position_counts # ==== Timestamp 工具 ==== @staticmethod def _format_timestamp(seconds: float) -> str: """将秒数格式化为固定宽度字符串,例如 0.0 -> 0000.0。""" return f"{seconds:06.1f}" def _compute_cube_timestamps( self, cube_bounds: List[Tuple[int, int]], video_start_token: int, temporal_patch_size: int, fps: float, ) -> List[str]: """ 依据 cube 边界计算每个 cube 的起始时间戳(字符串)。 Args: cube_bounds: [(start, end)] 列表,基于 temporal token 索引。 video_start_token: 视频在全局帧中的起始索引(当前实现均视为 0)。 temporal_patch_size: 时间维度 patch 大小。 fps: 有效帧率(已考虑 temporal_patch_size 的采样)。 """ if fps is None or fps <= 0: if self._debug_logs_enabled(): debug_print( "[Quicksviewer2][DEBUG _compute_cube_timestamps] fps<=0, skip. cube_bounds=%s video_start=%d temporal_patch_size=%d" % (cube_bounds, video_start_token, temporal_patch_size) ) return [] timestamps: List[str] = [] original_fps = fps * max(int(temporal_patch_size), 1) if self._debug_logs_enabled(): debug_print( "[Quicksviewer2][DEBUG _compute_cube_timestamps] cube_bounds=%s video_start_token=%d temporal_patch_size=%d fps=%.4f original_fps=%.4f" % ( cube_bounds, video_start_token, temporal_patch_size, float(fps), float(original_fps), ) ) for start_token, _ in cube_bounds: abs_frame = video_start_token + start_token * temporal_patch_size seconds = abs_frame / float(original_fps) ts = self._format_timestamp(seconds) timestamps.append(ts) if self._debug_logs_enabled(): debug_print( " [Quicksviewer2][DEBUG _compute_cube_timestamps] start_token=%d abs_frame=%d seconds=%.1f formatted=%s" % (start_token, abs_frame, float(seconds), ts) ) return timestamps @property def latest_video_metadata(self) -> Optional[Quicksviewer2VideoMetadata]: """返回最近一次调用 `get_video_features` 时生成的 metadata。""" return self._latest_video_metadata def initialize_cubing_modules_if_needed(self) -> None: """ 根据配置初始化 Cubing/Resampler 模块。 对齐 Exp modeling_glm4v_withCube.py L1502-1505。 """ if not getattr(self.config, "use_cubing", False): return if self._cubing_module is None: self._cubing_module = Quicksviewer2CubingModule(self.config) # 对齐 Exp L1505: self._current_lr_gumbel = config.cubing_lr_gumbel_start lr_gumbel_start = float(getattr(self.config, "cubing_lr_gumbel_start", 1.0)) setattr(self.config, "_current_lr_gumbel", lr_gumbel_start) setattr(self._cubing_module.config, "_current_lr_gumbel", lr_gumbel_start) self._debug_log("Initialized Quicksviewer2 cubing module.") if self._resampler is None: self._resampler = Quicksviewer2Resampler(self.config) self._debug_log("Initialized Quicksviewer2 resampler module.") @property def cubing_module(self) -> Optional[Quicksviewer2CubingModule]: return self._cubing_module @property def resampler(self) -> Optional[Quicksviewer2Resampler]: return self._resampler def set_gumbel_noise(self, lr_gumbel: float) -> None: """Set current Gumbel noise level for cubing (aligns with exp training loop).""" setattr(self.config, "_current_lr_gumbel", float(lr_gumbel)) if self._cubing_module is not None: setattr(self._cubing_module.config, "_current_lr_gumbel", float(lr_gumbel)) def get_cubing_aux_loss(self, alpha: float = 1e-3) -> torch.Tensor: """L2 penalty on gate logits, mirroring原版 Quicksviewer2 实现。""" if not getattr(self.config, "use_cubing", False): device = self.visual.patch_embed.proj.weight.device return torch.tensor(0.0, device=device) device = self.visual.patch_embed.proj.weight.device if hasattr(self, "_last_gate_logits"): gate_logits = self._last_gate_logits if self._debug_logs_enabled(): debug_print( "[Quicksviewer2][DEBUG AUX LOSS] Computing aux loss on %d gate logits" % gate_logits.numel() ) aux_loss = alpha * torch.norm(gate_logits, p=2) delattr(self, "_last_gate_logits") return aux_loss if self._debug_logs_enabled(): debug_print("[Quicksviewer2][DEBUG AUX LOSS] No gate_logits available, returning 0") return torch.tensor(0.0, device=device) def _build_video_metadata( self, video_grid_thw: torch.LongTensor, mode: str, ) -> Quicksviewer2VideoMetadata: metadata = Quicksviewer2VideoMetadata( original_grid_thw=video_grid_thw.clone(), temporal_patch_size=int(getattr(self.config.vision_config, "temporal_patch_size", 2)), mode=mode, use_thumbnail=bool(getattr(self.config, "cubing_use_thumbnail", True)), thumbnail_num_queries=int(getattr(self.config, "thumbnail_num_queries", 64)), ) return metadata def _generate_cubing_mrope_positions( self, num_tokens: int, device: torch.device, dtype: torch.dtype ) -> torch.Tensor: """ 为 Cubing 压缩后的 token 生成 MRoPE 位置编码。 Args: num_tokens: 压缩后的 token 数量(通常是 64) device: 目标设备 dtype: 数据类型 Returns: MRoPE 位置编码张量,形状为 (3, num_tokens) 3 对应 GLM-4.1V MRoPE 的三个部分:Q, K, V """ # 检查是否启用了 MRoPE is_mrope_enabled = ( hasattr(self.config, 'text_config') and hasattr(self.config.text_config, 'rope_scaling') and 'mrope_section' in self.config.text_config.rope_scaling ) if not is_mrope_enabled: # 如果没有启用 MRoPE,返回简单的序列位置 positions = torch.arange(num_tokens, device=device, dtype=torch.long) # 扩展为 (3, num_tokens) 格式以保持接口一致性 return positions.unsqueeze(0).repeat(3, 1) # GLM-4.1V MRoPE 配置 mrope_section = self.config.text_config.rope_scaling.get('mrope_section', [0, 0, 0]) # 生成基础位置序列 [0, 1, 2, ..., num_tokens-1] base_positions = torch.arange(num_tokens, device=device, dtype=torch.long) # 为 MRoPE 的三个部分生成位置编码 # 根据 GLM-4.1V 的实现,三个部分分别对应不同的位置编码策略 mrope_positions = [] for i in range(3): # Q, K, V 三个部分 if mrope_section[i] == 0: # 如果该部分没有专门的配置,使用基础位置 positions_i = base_positions else: # 根据配置生成不同的位置编码 # 这里使用简单的策略,实际可能需要更复杂的逻辑 positions_i = base_positions * (i + 1) % num_tokens mrope_positions.append(positions_i) # 堆叠为 (3, num_tokens) 形状 mrope_tensor = torch.stack(mrope_positions, dim=0) return mrope_tensor.to(dtype=torch.long) def _get_video_features_native( self, pixel_values_videos: torch.FloatTensor, metadata: Quicksviewer2VideoMetadata, ) -> Tuple[torch.Tensor, ...]: pixel_values_videos = pixel_values_videos.type(self.visual.dtype) flattened_grid = metadata.to_flattened_native(device=pixel_values_videos.device).to( dtype=metadata.original_grid_thw.dtype ) video_embeds = self.visual(pixel_values_videos, grid_thw=flattened_grid) spatial_merge = getattr(self.visual, "spatial_merge_size", 1) split_sizes = ( metadata.original_grid_thw.prod(-1) // (spatial_merge**2) ).tolist() metadata.actual_num_tokens = sum(int(size) for size in split_sizes) return tuple(torch.split(video_embeds, split_sizes)) def _get_video_features_with_cubing_premerge( self, pixel_values_videos: torch.FloatTensor, metadata: Quicksviewer2VideoMetadata, ) -> Tuple[torch.Tensor, ...]: """Compute per-video frame features before spatial merge (aligns with exp: visual(..., return_before_merge=True)).""" pixel_values_videos = pixel_values_videos.type(self.visual.dtype) flattened_grid = metadata.to_flattened_native(device=pixel_values_videos.device).to( dtype=metadata.original_grid_thw.dtype ) # 始终使用手动 pre-merge 路径,避免依赖视觉模型签名 hidden_states = self._run_visual_premerge_manual(pixel_values_videos, flattened_grid) frames: List[torch.Tensor] = [] start_idx = 0 for thw in metadata.original_grid_thw: t = int(thw[0].item()) h = int(thw[1].item()) w = int(thw[2].item()) seq_len = t * h * w chunk = hidden_states[start_idx : start_idx + seq_len] chunk = chunk.reshape(t, h * w, -1) frames.append(chunk) start_idx += seq_len return tuple(frames) def _run_visual_premerge_manual( self, pixel_values_videos: torch.FloatTensor, flattened_grid: torch.LongTensor ) -> torch.Tensor: """手动执行视觉前向,拿到合并前特征(兼容不支持 return_before_merge 的视觉模型)。""" hidden_states = self.visual.patch_embed(pixel_values_videos) hidden_states = self.visual.post_conv_layernorm(hidden_states) rotary_pos_emb, image_type_ids = self.visual.rot_pos_emb(flattened_grid) emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) position_embeddings = (emb.cos(), emb.sin()) cu_seqlens = torch.repeat_interleave( flattened_grid[:, 1] * flattened_grid[:, 2], flattened_grid[:, 0] ).cumsum(dim=0, dtype=flattened_grid.dtype if torch.jit.is_tracing() else torch.int32) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) seqlens = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist() hidden_states = self.visual.embeddings( hidden_states, seqlens, flattened_grid, image_type_ids[:, 0], image_type_ids[:, 1] ) for idx, blk in enumerate(self.visual.blocks): hidden_states = blk( hidden_states, cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, ) hidden_states = self.visual.post_layernorm(hidden_states) return hidden_states def _apply_cubing_resampler( self, premerge_chunks: Tuple[torch.Tensor, ...], metadata: Quicksviewer2VideoMetadata, fps: float = None, ) -> Tuple[torch.Tensor, ...]: if not premerge_chunks or not metadata.cube_bounds: return tuple() resampled: List[torch.Tensor] = [] per_video_ranges: List[List[Tuple[int, int]]] = [] total_tokens = 0 lm_hidden = int(getattr(self.config.text_config, "hidden_size", premerge_chunks[0].shape[-1])) resampler_dtype = self._resampler.query.dtype if hasattr(self._resampler, "query") else premerge_chunks[0].dtype per_video_token_counts: List[int] = [] for video_idx, frames in enumerate(premerge_chunks): bounds = metadata.cube_bounds[video_idx] if metadata.cube_bounds else [] cube_ranges = ( metadata.cube_tgt_size_ranges[video_idx] if metadata.cube_tgt_size_ranges and video_idx < len(metadata.cube_tgt_size_ranges) else None ) h = int(metadata.original_grid_thw[video_idx][1].item()) w = int(metadata.original_grid_thw[video_idx][2].item()) per_video_tokens: List[torch.Tensor] = [] per_video_pairs: List[Tuple[int, int]] = [] for cube_idx, (start, end) in enumerate(bounds): start_i, end_i = int(start), int(end) if end_i <= start_i: continue frame_slice = frames[start_i:end_i] if frame_slice.numel() == 0: continue cube_flat = frame_slice.reshape(-1, frame_slice.shape[-1]) tgt_range = ( cube_ranges[cube_idx] if cube_ranges and cube_idx < len(cube_ranges) else [[start_i, end_i], [0, h], [0, w]] ) resampled_cube = self._resampler(cube_flat, tgt_range, fps=fps) if resampled_cube.dim() == 3: resampled_cube = resampled_cube.squeeze(0) resampled_cube = resampled_cube.to(device=frames.device) per_video_tokens.append(resampled_cube) per_video_pairs.append((start_i, end_i)) total_tokens += int(resampled_cube.shape[0]) if metadata.thumbnail and video_idx < len(metadata.thumbnail): thumb = metadata.thumbnail[video_idx] if thumb is not None: target_dtype = per_video_tokens[0].dtype if per_video_tokens else resampler_dtype # Thumbnail 现在是 [thumbnail_num_queries, language_dim],直接插入无需 unsqueeze per_video_tokens.insert( 0, thumb.to(device=frames.device, dtype=target_dtype) ) total_tokens += int(thumb.shape[0]) # 添加 thumbnail 的 token 数量 (64) if per_video_tokens: resampled_video = torch.cat(per_video_tokens, dim=0) else: resampled_video = torch.empty(0, lm_hidden, device=frames.device, dtype=resampler_dtype) resampled.append(resampled_video) per_video_ranges.append(per_video_pairs) per_video_token_counts.append(int(resampled_video.shape[0])) metadata.tgt_size_range = per_video_ranges metadata.video_token_counts = per_video_token_counts metadata.actual_num_tokens = total_tokens if total_tokens > 0: reference = resampled[0] metadata.mrope_positions = self._generate_cubing_mrope_positions( total_tokens, reference.device, reference.dtype ) metadata.mrope_adjusted = True else: metadata.mrope_positions = None metadata.mrope_adjusted = False metadata.original_token_count = int(metadata.original_grid_thw.prod(-1).sum().item()) return tuple(resampled) def _build_cube_tgt_size_ranges( self, metadata: Quicksviewer2VideoMetadata ) -> Optional[List[List[List[List[int]]]]]: cube_bounds = metadata.cube_bounds if not cube_bounds: return None ranges: List[List[List[List[int]]]] = [] for video_idx, bounds in enumerate(cube_bounds): per_video: List[List[List[int]]] = [] h = int(metadata.original_grid_thw[video_idx][1].item()) w = int(metadata.original_grid_thw[video_idx][2].item()) frames_total = int(metadata.original_grid_thw[video_idx][0].item()) covered = 0 for start, end in bounds: start_i = int(start) end_i = int(end) covered += max(end_i - start_i, 0) per_video.append([[start_i, end_i], [0, h], [0, w]]) if bounds and covered != frames_total: raise ValueError( f"Cubing cube_bounds mismatch: covered {covered} vs frames {frames_total}" ) ranges.append(per_video) return ranges class Quicksviewer2ForConditionalGeneration(_glm4v.Glm4vForConditionalGeneration): config_class = Quicksviewer2Config def __init__(self, config: Quicksviewer2Config): # ==== 复用 GLM4V 预训练基类初始化 ==== _glm4v.Glm4vPreTrainedModel.__init__(self, config) # ==== 换上新的主干模型并初始化 lm_head ==== self.model = Quicksviewer2Model(config) self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.post_init() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.Tensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, videos_bound: Optional[Sequence[Tuple[int, int]]] = None, rope_deltas: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, tokenizer=None, use_cache: Optional[bool] = None, # ← 添加 output_attentions: Optional[bool] = None, # ← 添加 output_hidden_states: Optional[bool] = None, # ← 添加 return_dict: Optional[bool] = None, **kwargs, ): """ Forward 方法,对齐 Exp modeling_glm4v_withCube.py L2829-3314。 核心流程: 1. 获取初始文本 Embeddings 2. 插入图像特征(如果存在) 3. 获取视频特征(含 Cubing) 4. 在 embedding 层面动态构建最终序列(Exp Step 4) 5. 重新计算 Position IDs(Exp Step 5) 6. 调用 language_model(Exp Step 6) """ use_cubing = bool(getattr(self.config, "use_cubing", False)) debug_print("Using Quicksviewer2") # ========== 非 Cubing 模式:走原有基类流程 ========== if not use_cubing: debug_print("[DEBUG] Using GLM4V native path!") return super().forward( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, rope_deltas=rope_deltas, cache_position=cache_position, logits_to_keep=logits_to_keep, videos_bound=videos_bound, **kwargs, ) is_decoding = ( past_key_values is not None and pixel_values_videos is None ) if is_decoding: # Decode 阶段:轻量级处理,不重新处理视频 return self._forward_decode_with_cubing( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # ========== Cubing 模式:对齐 Exp Forward 流程 ========== device = input_ids.device if input_ids is not None else inputs_embeds.device batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0] debug_max_samples = 1 debug_segments: List[Optional[List[dict]]] = [None for _ in range(batch_size)] # ===== Decode 调试:可用于对齐 train/infer 的输入序列 ===== if DEBUG_ENABLED and tokenizer is not None and input_ids is not None: decode_max_len = 512 for i in range(min(batch_size, debug_max_samples)): ids = input_ids[i].detach().cpu() decoded = tokenizer.decode(ids[:decode_max_len], skip_special_tokens=False) debug_print(f"\n[Quicksviewer2][DEBUG Decode Input] sample {i} len={len(ids)}") debug_print(decoded) if labels is not None: for i in range(min(batch_size, debug_max_samples)): lbl = labels[i].detach().cpu() lbl = lbl[lbl != -100] decoded_lbl = tokenizer.decode(lbl[:decode_max_len], skip_special_tokens=False) debug_print(f"\n[Quicksviewer2][DEBUG Decode Labels] sample {i} len={len(lbl)}") debug_print(decoded_lbl) # === Step 1: 获取初始文本 Embeddings (对齐 Exp L2865-2873) === if inputs_embeds is None: initial_inputs_embeds = self.get_input_embeddings()(input_ids) else: initial_inputs_embeds = inputs_embeds current_inputs_embeds = initial_inputs_embeds # 强制开启前向调试输出,用于检查 position_ids/attention_mask(受全局开关控制) debug_enabled = DEBUG_ENABLED # === Step 2: 插入图像特征 (对齐 Exp L2881-2902) === if pixel_values is not None: image_embeds = self.model.get_image_features(pixel_values, image_grid_thw) image_embeds = torch.cat(image_embeds, dim=0).to(current_inputs_embeds.device, current_inputs_embeds.dtype) image_mask, _ = self.model.get_placeholder_mask(input_ids, current_inputs_embeds, image_features=image_embeds) current_inputs_embeds = current_inputs_embeds.masked_scatter(image_mask, image_embeds) # === Step 3: 获取视频特征 (对齐 Exp L2905-2924) === video_embeds_tuple, video_metadata = self.model.get_video_features( pixel_values_videos, video_grid_thw, videos_bound=videos_bound, return_metadata=True, tokenizer=tokenizer, ) video_embeds_list = [v.to(current_inputs_embeds.device, current_inputs_embeds.dtype) for v in video_embeds_tuple] # === Step 4: 动态构建最终 Embeddings 和 Mask (对齐 Exp L2926-3088) === video_start_embed = self.get_input_embeddings()( torch.tensor(self.config.video_start_token_id, device=device) ).unsqueeze(0) video_end_embed = self.get_input_embeddings()( torch.tensor(self.config.video_end_token_id, device=device) ).unsqueeze(0) video_placeholder_id = self.config.video_token_id final_inputs_embeds_list = [] final_attention_mask_list = [] final_labels_list = [] if labels is not None else None for i in range(batch_size): video_positions = (input_ids[i] == video_placeholder_id).nonzero(as_tuple=True)[0] if len(video_positions) == 0 or i >= len(video_embeds_list): # 没有视频占位符,直接使用原始 embeddings final_inputs_embeds_list.append(current_inputs_embeds[i]) if attention_mask is not None: final_attention_mask_list.append(attention_mask[i]) else: seq_len = current_inputs_embeds[i].shape[0] final_attention_mask_list.append(torch.ones(seq_len, device=device, dtype=torch.long)) if labels is not None: final_labels_list.append(labels[i]) continue video_pos = video_positions[0].item() current_video_embeds = video_embeds_list[i] # 获取时间戳和 thumbnail 信息 cube_timestamps = video_metadata.cube_timestamps[i] if video_metadata.cube_timestamps else [] cube_timestamp_tokens = video_metadata.cube_timestamp_tokens[i] if video_metadata.cube_timestamp_tokens else [] num_cubes = len(cube_timestamps) has_thumbnail = bool( getattr(video_metadata, "use_thumbnail", False) or (video_metadata.thumbnail and i < len(video_metadata.thumbnail) and video_metadata.thumbnail[i] is not None) ) thumbnail_num_tokens = int(getattr(self.config, "thumbnail_num_queries", 64)) if has_thumbnail else 0 cube_offset = thumbnail_num_tokens num_cube_tokens = current_video_embeds.shape[0] - cube_offset tokens_per_cube = num_cube_tokens // num_cubes if num_cubes > 0 else 0 segs: List[dict] = [] cursor = 0 def _add_seg(name: str, seg_ids: torch.Tensor, seg_type: str) -> None: nonlocal cursor seg_len = int(seg_ids.shape[0]) segs.append( { "name": name, "type": seg_type, "start": cursor, "end": cursor + seg_len, "token_ids": seg_ids.detach().cpu(), } ) cursor += seg_len # === 构建 embeddings 序列 (对齐 Exp L2996-3017) === parts = [ current_inputs_embeds[i, :video_pos], video_start_embed, ] _add_seg("text_prefix", input_ids[i, :video_pos], "text") _add_seg("video_start", torch.tensor([self.config.video_start_token_id], device=device), "video_start") # 插入 Thumbnail if has_thumbnail and thumbnail_num_tokens > 0: thumbnail_embeds = current_video_embeds[:thumbnail_num_tokens] parts.append(thumbnail_embeds) _add_seg( "thumbnail", torch.full((thumbnail_num_tokens,), video_placeholder_id, device=device, dtype=torch.long), "thumbnail", ) # 插入 Cubes (timestamp + cube_tokens) for cube_idx in range(num_cubes): # 时间戳 embeddings if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]: ts_embeds = self.get_input_embeddings()( torch.tensor(cube_timestamp_tokens[cube_idx], device=device) ) parts.append(ts_embeds) _add_seg( f"cube{cube_idx}_timestamp", torch.tensor(cube_timestamp_tokens[cube_idx], device=device), "timestamp", ) # Cube embeddings cube_start = cube_offset + cube_idx * tokens_per_cube cube_end = cube_start + tokens_per_cube parts.append(current_video_embeds[cube_start:cube_end]) _add_seg( f"cube{cube_idx}", torch.full((tokens_per_cube,), video_placeholder_id, device=device, dtype=torch.long), "cube", ) parts.extend([ video_end_embed, current_inputs_embeds[i, video_pos + 1:], ]) _add_seg("video_end", torch.tensor([self.config.video_end_token_id], device=device), "video_end") _add_seg("text_suffix", input_ids[i, video_pos + 1:], "text") new_embeds = torch.cat(parts, dim=0) final_inputs_embeds_list.append(new_embeds) debug_segments[i] = segs # === 同步构建 attention_mask (对齐 Exp L3022-3059) === if attention_mask is not None: current_mask = attention_mask[i] mask_parts = [ current_mask[:video_pos], torch.ones(1, dtype=current_mask.dtype, device=device), # video_start ] if has_thumbnail and thumbnail_num_tokens > 0: mask_parts.append(torch.ones(thumbnail_num_tokens, dtype=current_mask.dtype, device=device)) for cube_idx in range(num_cubes): if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]: num_ts_tokens = len(cube_timestamp_tokens[cube_idx]) mask_parts.append(torch.ones(num_ts_tokens, dtype=current_mask.dtype, device=device)) mask_parts.append(torch.ones(tokens_per_cube, dtype=current_mask.dtype, device=device)) mask_parts.extend([ torch.ones(1, dtype=current_mask.dtype, device=device), # video_end current_mask[video_pos + 1:], ]) new_mask = torch.cat(mask_parts, dim=0) final_attention_mask_list.append(new_mask) else: new_len = new_embeds.shape[0] final_attention_mask_list.append(torch.ones(new_len, dtype=torch.long, device=device)) if labels is not None: ignore_index = -100 label_device = labels.device label_dtype = labels.dtype label_parts = [ labels[i, :video_pos], torch.full((1,), ignore_index, dtype=label_dtype, device=label_device), # video_start ] if has_thumbnail and thumbnail_num_tokens > 0: label_parts.append(torch.full((thumbnail_num_tokens,), ignore_index, dtype=label_dtype, device=label_device)) for cube_idx in range(num_cubes): if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]: num_ts_tokens = len(cube_timestamp_tokens[cube_idx]) label_parts.append(torch.full((num_ts_tokens,), ignore_index, dtype=label_dtype, device=label_device)) label_parts.append(torch.full((tokens_per_cube,), ignore_index, dtype=label_dtype, device=label_device)) label_parts.extend([ torch.full((1,), ignore_index, dtype=label_dtype, device=label_device), # video_end labels[i, video_pos + 1:], ]) new_labels = torch.cat(label_parts, dim=0) final_labels_list.append(new_labels) # === Padding (对齐 Exp L3061-3079) === max_len_new = max(embed.shape[0] for embed in final_inputs_embeds_list) final_inputs_embeds = torch.zeros( batch_size, max_len_new, current_inputs_embeds.shape[-1], dtype=current_inputs_embeds.dtype, device=device ) final_attention_mask = torch.zeros(batch_size, max_len_new, dtype=torch.long, device=device) if labels is not None: padded_labels = torch.full( (batch_size, max_len_new), -100, dtype=labels.dtype, device=labels.device, ) for i in range(batch_size): seq_len_i = final_inputs_embeds_list[i].shape[0] final_inputs_embeds[i, :seq_len_i] = final_inputs_embeds_list[i] final_attention_mask[i, :seq_len_i] = final_attention_mask_list[i] if labels is not None: label_seq = final_labels_list[i] copy_len = min(label_seq.shape[0], max_len_new) padded_labels[i, :copy_len] = label_seq[:copy_len] # 剩余部分保持 ignore_index if labels is not None: labels = padded_labels # === Step 5: 重新计算 Position IDs (对齐 Exp L3090-3198) === # 构建 temp_input_ids 用于 get_rope_index video_start_token_id = self.config.video_start_token_id video_end_token_id = self.config.video_end_token_id pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else 0 temp_input_ids = torch.full((batch_size, max_len_new), pad_token_id, dtype=torch.long, device=device) for i in range(batch_size): video_positions = (input_ids[i] == video_placeholder_id).nonzero(as_tuple=True)[0] if len(video_positions) == 0 or i >= len(video_embeds_list): original_len = input_ids[i].shape[0] temp_input_ids[i, :original_len] = input_ids[i] continue video_pos_orig = video_positions[0].item() cube_timestamp_tokens = video_metadata.cube_timestamp_tokens[i] if video_metadata.cube_timestamp_tokens else [] num_cubes = len(cube_timestamp_tokens) has_thumbnail = bool( getattr(video_metadata, "use_thumbnail", False) or (video_metadata.thumbnail and i < len(video_metadata.thumbnail) and video_metadata.thumbnail[i] is not None) ) thumbnail_num_tokens = int(getattr(self.config, "thumbnail_num_queries", 64)) if has_thumbnail else 0 cube_offset = thumbnail_num_tokens num_video_tokens = video_embeds_list[i].shape[0] num_cube_tokens = num_video_tokens - cube_offset tokens_per_cube = num_cube_tokens // num_cubes if num_cubes > 0 else 0 # 构建 temp_input_ids parts = [input_ids[i, :video_pos_orig]] parts.append(torch.tensor([video_start_token_id], device=device)) if has_thumbnail and thumbnail_num_tokens > 0: parts.append(torch.full((thumbnail_num_tokens,), video_placeholder_id, device=device)) for cube_idx in range(num_cubes): if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]: parts.append(torch.tensor(cube_timestamp_tokens[cube_idx], device=device)) parts.append(torch.full((tokens_per_cube,), video_placeholder_id, device=device)) parts.append(torch.tensor([video_end_token_id], device=device)) parts.append(input_ids[i, video_pos_orig + 1:]) temp_seq = torch.cat(parts) actual_len = min(temp_seq.shape[0], max_len_new) temp_input_ids[i, :actual_len] = temp_seq[:actual_len] # 调用 get_rope_index final_position_ids, final_rope_deltas = self.model.get_rope_index( input_ids=temp_input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=final_attention_mask, ) # === 调试:前 5 次 forward 将 embeddings 和 position_ids 全量写入 CSV(默认关闭) === dump_csv_enabled = os.getenv("QUICKSVIEWER2_DUMP_CSV", "0") == "1" if dump_csv_enabled: if not hasattr(self, "_debug_dump_count"): self._debug_dump_count = 0 if self._debug_dump_count < 5: dump_idx = self._debug_dump_count + 1 self._debug_dump_count += 1 dump_dir = os.getenv( "QUICKSVIEWER2_DUMP_DIR", os.path.join(os.getcwd(), "logs"), ) os.makedirs(dump_dir, exist_ok=True) emb_path = os.path.join(dump_dir, f"llm_embeddings_{dump_idx}.csv") pos_path = os.path.join(dump_dir, f"llm_position_ids_{dump_idx}.csv") emb_np = final_inputs_embeds.detach().cpu().to(torch.float32).numpy() bsz, seq_len, hidden = emb_np.shape with open(emb_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow(["batch", "position"] + [f"h{i}" for i in range(hidden)]) for b in range(bsz): for p in range(seq_len): writer.writerow([b, p] + emb_np[b, p].tolist()) pos_np = final_position_ids.detach().cpu().to(torch.float32).numpy() # shape: (3, bsz, seq_len) pos_np = pos_np.transpose(1, 2, 0) # (bsz, seq_len, 3) with open(pos_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow(["batch", "position", "t", "h", "w"]) for b in range(pos_np.shape[0]): for p in range(pos_np.shape[1]): t, h, w = pos_np[b, p].tolist() writer.writerow([b, p, t, h, w]) if debug_enabled: for i in range(min(batch_size, debug_max_samples)): segs = debug_segments[i] or [] seq_len_i = final_inputs_embeds_list[i].shape[0] pos_slice = final_position_ids[:, i, :seq_len_i].detach().cpu() debug_print(f"\n[Quicksviewer2][DEBUG Forward] Sample {i} seq_len={seq_len_i}") debug_print(" attention_mask_sum:", int(final_attention_mask[i, :seq_len_i].sum().item())) for seg in segs: s, e = int(seg["start"]), int(seg["end"]) seg_pos = pos_slice[:, s:e] t_min = int(seg_pos[0].min().item()) if seg_pos.numel() > 0 else 0 t_max = int(seg_pos[0].max().item()) if seg_pos.numel() > 0 else 0 h_unique = torch.unique(seg_pos[1]).tolist() if seg_pos.numel() > 0 else [] w_unique = torch.unique(seg_pos[2]).tolist() if seg_pos.numel() > 0 else [] token_ids = seg.get("token_ids") tok_preview = token_ids[:12].tolist() if token_ids is not None else [] debug_print( f" segment {seg['name']} ({seg['type']}, len={e - s}) " f"pos_t=[{t_min},{t_max}] span={t_max - t_min + 1} " f"h_unique={h_unique} w_unique={w_unique} " f"tokens_head={tok_preview}" ) # === Step 6: 调用 language_model (对齐 Exp L3231-3290) === outputs = self.model.language_model( input_ids=None, position_ids=final_position_ids, attention_mask=final_attention_mask, past_key_values=past_key_values, inputs_embeds=final_inputs_embeds, cache_position=cache_position, **kwargs, ) hidden_states = outputs[0] slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size) if self.training and getattr(self.config, "use_cubing", False): aux_loss = self.model.get_cubing_aux_loss() loss = loss + aux_loss # ===== Decode 输出:只展示有标签位置的预测,避免噪声 ===== if DEBUG_ENABLED and tokenizer is not None and logits is not None and labels is not None: with torch.no_grad(): # 对齐 cross-entropy,shift 一位 shift_logits = logits[..., :-1, :].detach().cpu() shift_labels = labels[..., 1:].detach().cpu() mask = shift_labels != -100 if mask.any(): pred_ids = shift_logits[0].argmax(dim=-1) pred_sel = pred_ids[mask[0]] label_sel = shift_labels[0][mask[0]] # 限制长度,避免过长打印 pred_sel = pred_sel[:64] label_sel = label_sel[:64] debug_print("\n[Quicksviewer2][DEBUG Decode Output] preds (masked, first 64):") debug_print(tokenizer.decode(pred_sel, skip_special_tokens=False)) debug_print("[Quicksviewer2][DEBUG Decode Output] labels (masked, first 64):") debug_print(tokenizer.decode(label_sel, skip_special_tokens=False)) return _glm4v.Glm4vCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=final_rope_deltas, ) def _forward_decode_with_cubing( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, _glm4v.Glm4vCausalLMOutputWithPast]: """ Decode 阶段的 forward:不重新处理视频,使用正确的位置编码。 这个方法在生成过程中被调用(第2步及以后),此时: - past_key_values 不为 None(有 KV cache) - pixel_values_videos 为 None(视频已在 prefill 处理) - input_ids 只包含刚生成的 1 个 token """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict # Step 1: 获取 embeddings if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) batch_size, seq_length = inputs_embeds.shape[:2] device = inputs_embeds.device # Step 2: 计算 position_ids(关键!) # 先计算 cache_length cache_length = past_key_values.get_seq_length() if past_key_values is not None else 0 if position_ids is None: # 新 token 的位置 = cache_length 开始,连续递增 new_positions = torch.arange( cache_length, cache_length + seq_length, dtype=torch.long, device=device ) # MRoPE 格式: (3, batch_size, seq_length) # T 维度:连续递增 # H, W 维度:固定为 1(答案部分不是 2D 图像) position_ids = new_positions.unsqueeze(0).repeat(3, 1, 1).float() position_ids = position_ids.expand(-1, batch_size, -1) # 扩展 batch 维度 position_ids[1:] = 1.0 # H 和 W 维度设置为 1 # 调试输出 # print(f"\n[Cubing Decode] cache_length={cache_length}, seq_length={seq_length}") debug_print(f"[Cubing Decode] position_ids[0,0,:] (T): {position_ids[0, 0, :].tolist()}") # print(f"[Cubing Decode] position_ids[1,0,:] (H): {position_ids[1, 0, :].tolist()}") # print(f"[Cubing Decode] position_ids[2,0,:] (W): {position_ids[2, 0, :].tolist()}") # Step 3: 处理 attention_mask if attention_mask is None: # Decode 阶段:新 token 可以看到所有历史 token # attention_mask shape: (batch_size, cache_length + seq_length) attention_mask = torch.ones( (batch_size, cache_length + seq_length), dtype=torch.long, device=device ) # Step 4: 调用 language_model outputs = self.model.language_model( input_ids=None, # 直接用 inputs_embeds position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] # Step 5: 计算 logits logits = self.lm_head(hidden_states) logits = logits.float() # Step 6: 计算 loss(如果提供了 labels) loss = None if labels is not None: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = torch.nn.CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.text_config.vocab_size) shift_labels = shift_labels.view(-1) shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) # Step 7: 返回结果 if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output max_pos = position_ids[:, :, :].max() rope_deltas = (max_pos + 1 - seq_length).unsqueeze(0).to(device) return _glm4v.Glm4vCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=rope_deltas ) def loss_function( self, logits: torch.Tensor, labels: torch.LongTensor, vocab_size: int, ignore_index: int = -100, ) -> torch.Tensor: """ 调试友好的 loss 计算:在启用 config.debug_loss 时,输出与 glm4v_cube_dbg/modeling_glm4v_withCube.py 中相同的详细统计信息。 """ # 强制将 labels 与 logits 放在同一设备,避免多 GPU 环境下的 device mismatch if labels.device != logits.device: labels = labels.to(logits.device) debug_loss = DEBUG_ENABLED # 全局开关控制详细 loss 调试 # 标准 GLM4V 风格的 loss 计算 shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() if not debug_loss: return F.cross_entropy( shift_logits.view(-1, vocab_size), shift_labels.view(-1), ignore_index=ignore_index, ) # ====== Debug 分支:打印详细信息,便于对齐/排查 ====== debug_print("\n[DEBUG LOSS_FUNCTION] === START ===") debug_print(" Input shapes:") debug_print(f" logits: {logits.shape}") debug_print(f" labels: {labels.shape}") debug_print(f" vocab_size: {vocab_size}") debug_print(" After shift:") debug_print(f" shift_logits: {shift_logits.shape}") debug_print(f" shift_labels: {shift_labels.shape}") valid_mask = shift_labels != ignore_index num_valid = int(valid_mask.sum().item()) total = int(shift_labels.numel()) debug_print(" Label statistics:") debug_print(f" Total positions: {total}") debug_print(f" Valid positions (not {ignore_index}): {num_valid}") debug_print(f" Ignored positions: {total - num_valid}") if total > 0: debug_print(f" Valid ratio: {num_valid / total * 100:.2f}%") debug_print(" Logits statistics:") debug_print(f" min: {shift_logits.min().item():.4f}") debug_print(f" max: {shift_logits.max().item():.4f}") debug_print(f" mean: {shift_logits.mean().item():.4f}") debug_print(f" has NaN: {shift_logits.isnan().any().item()}") debug_print(f" has Inf: {shift_logits.isinf().any().item()}") flat_logits = shift_logits.view(-1, vocab_size) flat_labels = shift_labels.view(-1) debug_print(" After flatten:") debug_print(f" shift_logits: {flat_logits.shape}") debug_print(f" shift_labels: {flat_labels.shape}") debug_print("\n [Manual loss calculation]") loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=ignore_index) per_token_loss = loss_fct(flat_logits, flat_labels) valid_loss_mask = flat_labels != ignore_index valid_losses = per_token_loss[valid_loss_mask] if valid_losses.numel() > 0: manual_loss = valid_losses.mean() debug_print(f" Per-token loss (first 10): {valid_losses[:10].tolist()}") debug_print(f" Manual loss (mean): {manual_loss.item():.6f}") else: debug_print(" ⚠️ WARNING: No valid labels!") manual_loss = torch.tensor(0.0, device=per_token_loss.device) debug_print("\n [F.cross_entropy]") loss = F.cross_entropy(flat_logits, flat_labels, ignore_index=ignore_index) debug_print(f" Returned loss: {loss.item():.6f}") if valid_losses.numel() > 0: diff = abs(loss.item() - manual_loss.item()) debug_print("\n [Comparison]") debug_print(f" Manual: {manual_loss.item():.6f}") debug_print(f" F.cross: {loss.item():.6f}") debug_print(f" Diff: {diff:.6f}") if diff > 0.01: debug_print(" ⚠️ WARNING: Large difference!") debug_print("\n [Valid positions analysis]") valid_indices = valid_loss_mask.nonzero(as_tuple=True)[0] debug_print(f" Number of valid positions: {len(valid_indices)}") debug_print(f" Valid position indices: {valid_indices.tolist()}") if len(valid_indices) > 0: valid_label_values = flat_labels[valid_indices] debug_print(f" Valid label values: {valid_label_values.tolist()}") debug_print("\n[DEBUG LABELS DETAIL]") if flat_labels.numel() > 0: sample_labels = flat_labels # 展开后的一维 labels sample_valid_mask = sample_labels != ignore_index sample_valid_positions = sample_valid_mask.nonzero(as_tuple=True)[0] debug_print(f" Valid label positions: {sample_valid_positions.tolist()}") if len(sample_valid_positions) > 0: debug_print(f" Valid label IDs: {sample_labels[sample_valid_positions].tolist()}") else: debug_print(" ⚠️ WARNING: No labels found at all!") debug_print("[DEBUG LOSS_FUNCTION] === END ===\n") return loss def prepare_inputs_for_generation(self, *args, videos_bound: Optional[Sequence[Tuple[int, int]]] = None, **kwargs): # `videos_bound` only matters during the initial prefill; discard for decoding kwargs.pop("videos_bound", None) return super().prepare_inputs_for_generation(*args, **kwargs) def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None, videos_bound: Optional[Sequence[Tuple[int, int]]] = None, return_metadata: bool = False, ): return self.model.get_video_features( pixel_values_videos, video_grid_thw, videos_bound=videos_bound, return_metadata=return_metadata, ) @property def latest_video_metadata(self) -> Optional[Quicksviewer2VideoMetadata]: return self.model.latest_video_metadata def initialize_cubing_modules_if_needed(self) -> None: self.model.initialize_cubing_modules_if_needed() @property def cubing_module(self) -> Optional[Quicksviewer2CubingModule]: return self.model.cubing_module @property def resampler(self) -> Optional[Quicksviewer2Resampler]: return self.model.resampler def get_cubing_aux_loss(self, alpha: float = 1e-3) -> torch.Tensor: return self.model.get_cubing_aux_loss(alpha) __all__ = [ "Quicksviewer2VideoMetadata", "Quicksviewer2CubingModule", "Quicksviewer2Resampler", "Quicksviewer2RMSNorm", "Quicksviewer2VisionPatchEmbed", "Quicksviewer2VisionRotaryEmbedding", "Quicksviewer2VisionPatchMerger", "Quicksviewer2VisionEmbeddings", "Quicksviewer2VisionAttention", "Quicksviewer2VisionBlock", "Quicksviewer2TextRotaryEmbedding", "Quicksviewer2TextAttention", "Quicksviewer2TextMLP", "Quicksviewer2TextDecoderLayer", "Quicksviewer2ModelOutputWithPast", "Quicksviewer2CausalLMOutputWithPast", "Quicksviewer2PreTrainedModel", "Quicksviewer2VisionModel", "Quicksviewer2TextModel", "Quicksviewer2Model", "Quicksviewer2ForConditionalGeneration", ]
# modeling_quicksviewer2.py
from __future__ import annotations
import itertools
import os
import csv
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.glm4v import modeling_glm4v as _glm4v
from transformers.cache_utils import Cache
from transformers.utils import logging
from .configuration_quicksviewer2 import (
Quicksviewer2Config,
Quicksviewer2TextConfig,
Quicksviewer2VisionConfig,
)
from .cubing_quicksviewer2 import Quicksviewer2CubingModule
from .resampler_quicksviewer2 import Quicksviewer2Resampler
logger = logging.get_logger(__name__)
# 全局调试开关:导出 QUICKSVIEWER2_DEBUG=1 才会打印调试信息
DEBUG_ENABLED = os.getenv("QUICKSVIEWER2_DEBUG", "0") == "1"
def debug_print(*args, **kwargs) -> None:
"""Lightweight debug print that prefixes rank when分布式可用。"""
if not DEBUG_ENABLED:
return
prefix = ""
try:
import torch.distributed as dist
if dist.is_available() and dist.is_initialized():
prefix = f"[Rank {dist.get_rank()}] "
except Exception:
prefix = ""
if prefix:
if args:
args = (prefix + str(args[0]), *args[1:])
else:
args = (prefix,)
print(*args, **kwargs)
# =============================================================================
# ==== 元数据工具 ====
# =============================================================================
@dataclass
class Quicksviewer2VideoMetadata:
original_grid_thw: torch.LongTensor
temporal_patch_size: int
mode: str = "native"
pre_merge: bool = False
use_thumbnail: bool = True
thumbnail_num_queries: int = 64
actual_num_tokens: Optional[int] = None
tgt_size_range: Optional[List[List[Tuple[int, int]]]] = None
cube_bounds: Optional[List[List[Tuple[int, int]]]] = None
z_hard: Optional[List[torch.Tensor]] = None
z_soft: Optional[List[torch.Tensor]] = None
gate_logits: Optional[List[torch.Tensor]] = None
thumbnail: Optional[List[Optional[torch.Tensor]]] = None
cube_tgt_size_ranges: Optional[List[List[List[List[int]]]]] = None
video_token_counts: Optional[List[int]] = None
cube_timestamps: Optional[List[List[str]]] = None # 逐视频的时间戳字符串
cube_timestamp_tokens: Optional[List[List[List[int]]]] = None # 逐视频逐 cube 的时间戳 token ids
# MRoPE 相关字段
mrope_positions: Optional[torch.Tensor] = None # 形状: (3, num_tokens)
mrope_adjusted: bool = False # 是否已为 Cubing 调整了 MRoPE
original_token_count: Optional[int] = None # 原始 token 数量(用于调试)
def to_flattened_native(self, device: Optional[torch.device] = None) -> torch.LongTensor:
"""展平为逐帧 Grid,保持 GLM-4.1V 的 native 处理路径。"""
if self.original_grid_thw.numel() == 0:
base = self.original_grid_thw.new_zeros((0, 3))
return base.to(device=device) if device is not None else base
flattened_chunks: List[torch.LongTensor] = []
for thw in self.original_grid_thw:
t, h, w = (int(thw[0].item()), int(thw[1].item()), int(thw[2].item()))
repeated = thw.new_tensor([1, h, w]).unsqueeze(0).repeat(t, 1)
flattened_chunks.append(repeated)
flattened = torch.cat(flattened_chunks, dim=0)
return flattened.to(device=device) if device is not None else flattened
def to_temporal_grid(self, device: Optional[torch.device] = None) -> torch.LongTensor:
"""构造 Cubing 需要的 temporal grid(每个条目长度为 temporal_patch_size)。"""
flattened_chunks: List[torch.LongTensor] = []
for thw in self.original_grid_thw:
t = int(thw[0].item())