TextVR_ckpt4000 / processing_quicksviewer2.py
EdgePro001's picture
Upload folder using huggingface_hub
7e0b12a verified
Raw History Blame Contribute Delete
24 kB
# =============================================================================
# ==== Quicksviewer2 Processor (GLM-4.1V Baseline) ====
# =============================================================================
# coding=utf-8
# Copyright 2025 The ZhipuAI Inc. team and HuggingFace Inc. team. All rights reserved.
#
# 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 typing import List, Optional, Tuple, Union
import numpy as np
from typing import Any
from transformers.feature_extraction_utils import BatchFeature
from transformers.image_utils import ImageInput
from transformers.processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
from transformers.video_utils import VideoInput
from transformers import AutoProcessor, AutoConfig
from .configuration_quicksviewer2 import Quicksviewer2Config
# =============================================================================
# ==== 数据结构 ====
# =============================================================================
class Quicksviewer2ProcessorKwargs(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": False,
"return_token_type_ids": False,
"return_mm_token_type_ids": False,
},
"videos_kwargs": {"return_metadata": True},
}
# =============================================================================
# ==== Processor 主体 ====
# =============================================================================
class Quicksviewer2Processor(ProcessorMixin):
r"""
Constructs a Quicksviewer2 processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor.
[`~Quicksviewer2Processor.__call__`] and [`~Quicksviewer2Processor.decode`] for more information.
Args:
image_processor ([`Quicksviewer2Processor`], *optional*):
The image processor is a required input.
tokenizer ([`PreTrainedTokenizerFast`], *optional*):
The tokenizer is a required input.
video_processor ([`Glm4vVideoProcessor`], *optional*):
The video processor is a required input.
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
in a chat into a tokenizable string.
"""
attributes = ["image_processor", "tokenizer", "video_processor"]
image_processor_class = "AutoImageProcessor"
video_processor_class = "AutoVideoProcessor"
tokenizer_class = ("PreTrainedTokenizer", "PreTrainedTokenizerFast")
def __init__(
self,
image_processor=None,
tokenizer=None,
video_processor=None,
chat_template=None,
config=None,
auto_videos_bound: bool = True,
**kwargs,
):
# ==== 配置绑定 ====
self.config = config
self.auto_videos_bound = bool(auto_videos_bound)
self.image_token = "<|image|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
self.video_token = "<|video|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
self.image_token_id = (
tokenizer.image_token_id
if getattr(tokenizer, "image_token_id", None)
else tokenizer.convert_tokens_to_ids(self.image_token)
)
self.video_token_id = (
tokenizer.video_token_id
if getattr(tokenizer, "video_token_id", None)
else tokenizer.convert_tokens_to_ids(self.video_token)
)
super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template, **kwargs)
# ==== Sync FPS to video_processor ====
if self.video_processor is not None and self.config is not None:
video_fps = getattr(self.config, "video_fps", -1)
if video_fps > 0:
self.video_processor.fps = video_fps
def _is_cubing_enabled(self) -> bool:
return bool(getattr(self.config, "use_cubing", False))
def __call__(
self,
images: Optional[ImageInput] = None,
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
videos: Optional[VideoInput] = None,
**kwargs: Unpack[Quicksviewer2ProcessorKwargs],
) -> BatchFeature:
"""
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
the text.
Args:
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
tensor. Both channels-first and channels-last formats are supported.
text (`str`, `List[str]`, `List[List[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors of a particular framework. Acceptable values are:
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return NumPy `np.ndarray` objects.
Returns:
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
`None`).
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
- **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
- **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
- **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
"""
output_kwargs = self._merge_kwargs(
Quicksviewer2ProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
if images is not None:
image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
image_grid_thw = image_inputs["image_grid_thw"]
else:
image_inputs = {}
image_grid_thw = None
if videos is not None:
videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
# Align with reference: do not propagate metadata into BatchFeature (non-tensorizable)
videos_inputs.pop("video_metadata", None)
video_grid_thw = videos_inputs["video_grid_thw"]
else:
videos_inputs = {}
video_grid_thw = None
if not isinstance(text, list):
text = [text]
text = text.copy() # below lines change text in-place
if image_grid_thw is not None:
merge_length = self.image_processor.merge_size**2
index = 0
image_placeholders = []
for candidate in (self.image_token, "<image>"):
if candidate and candidate not in image_placeholders:
image_placeholders.append(candidate)
for i in range(len(text)):
for placeholder in image_placeholders:
while placeholder in text[i] and index < len(image_grid_thw):
num_image_tokens = image_grid_thw[index].prod() // merge_length
text[i] = text[i].replace(placeholder, "<|placeholder|>" * num_image_tokens, 1)
index += 1
text[i] = text[i].replace("<|placeholder|>", self.image_token)
cubing_video_token_counts: Optional[List[int]] = None
cubing_videos_bound: Optional[List[Tuple[int, int]]] = None
native_video_token_counts: Optional[List[int]] = None
# ==== 根据模式计算 token 数量和 videos_bound ====
if video_grid_thw is not None:
if self._is_cubing_enabled():
# Cubing 模式
cubing_video_token_counts, cubing_videos_bound = self._calculate_cubing_video_tokens(video_grid_thw)
if cubing_videos_bound and self.auto_videos_bound:
videos_inputs["videos_bound"] = cubing_videos_bound
else:
# Native 模式
native_video_token_counts = self._calculate_native_video_tokens(video_grid_thw)
# Optionally construct videos_bound for auto-inference
if self.auto_videos_bound:
cubing_videos_bound = self._construct_videos_bound(video_grid_thw)
videos_inputs["videos_bound"] = cubing_videos_bound
# ==== 替换视频 placeholder(统一处理两种模式)====
if video_grid_thw is not None:
# 根据模式选择 token 数量列表
token_counts = cubing_video_token_counts if self._is_cubing_enabled() else native_video_token_counts
if token_counts:
video_token_string = self.video_token or "<|video|>"
expected_video_token_id = getattr(self.config, "video_token_id", None) if self.config is not None else None
if expected_video_token_id is not None:
try:
converted_token = self.tokenizer.convert_ids_to_tokens(expected_video_token_id)
if isinstance(converted_token, list):
converted_token = converted_token[0]
if converted_token is not None and converted_token != getattr(self.tokenizer, "unk_token", None):
video_token_string = converted_token
except Exception:
video_token_string = self.video_token or "<|video|>"
video_placeholders = []
for candidate in (self.video_token, "<|video|>", "<video>"):
if candidate and candidate not in video_placeholders:
video_placeholders.append(candidate)
video_index = 0
for i in range(len(text)):
for placeholder in video_placeholders:
while placeholder in text[i] and video_index < len(token_counts):
total_tokens = max(int(token_counts[video_index]), 0)
replacement = video_token_string * total_tokens if total_tokens > 0 else ""
text[i] = text[i].replace(placeholder, replacement, 1)
video_index += 1
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
if return_mm_token_type_ids:
array_ids = np.array(text_inputs["input_ids"])
mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
mm_token_type_ids[array_ids == self.image_token_id] = 1
text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
config = kwargs.pop("config", None)
if config is None:
config_kwargs = {}
for key in ["cache_dir", "force_download", "local_files_only", "revision", "token", "trust_remote_code"]:
if key in kwargs:
config_kwargs[key] = kwargs[key]
try:
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **config_kwargs)
except Exception:
config = None
processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
if config is not None:
processor.config = config
return processor
def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
video_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (num_frames, height, width) per each video.
Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""
vision_data = {}
if image_sizes is not None:
images_kwargs = Quicksviewer2ProcessorKwargs._defaults.get("images_kwargs", {})
images_kwargs.update(kwargs)
merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
num_image_patches = [
self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
for image_size in image_sizes
]
num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
if video_sizes is not None:
if self._is_cubing_enabled():
num_video_tokens = [
self._estimate_cubing_tokens_from_frames(int(video_size[0])) for video_size in video_sizes
]
vision_data["num_video_tokens"] = num_video_tokens
else:
videos_kwargs = Quicksviewer2ProcessorKwargs._defaults.get("videos_kwargs", {})
videos_kwargs.update(kwargs)
num_video_patches = [
self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)
for video_size in video_sizes
]
num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
vision_data["num_video_tokens"] = num_video_tokens
return MultiModalData(**vision_data)
def post_process_image_text_to_text(
self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
):
"""
Post-process the output of the model to decode the text.
Args:
generated_outputs (`torch.Tensor` or `np.ndarray`):
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
or `(sequence_length,)`.
skip_special_tokens (`bool`, *optional*, defaults to `True`):
Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
**kwargs:
Additional arguments to be passed to the tokenizer's `batch_decode method`.
Returns:
`list[str]`: The decoded text.
"""
return self.tokenizer.batch_decode(
generated_outputs,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
def _calculate_cubing_video_tokens(
self, video_grid_thw
) -> Tuple[List[int], List[Tuple[int, int]]]:
if video_grid_thw is None:
return [], []
counts: List[int] = []
bounds: List[Tuple[int, int]] = []
cursor = 0
for entry in video_grid_thw:
frames = int(entry[0])
num_cubes = self._estimate_cubing_cube_count(frames)
tokens = num_cubes * int(getattr(self.config, "resampler_num_queries", 64))
if bool(getattr(self.config, "cubing_use_thumbnail", True)):
tokens += int(getattr(self.config, "thumbnail_num_queries", 64))
counts.append(tokens)
bounds.append((cursor, cursor + frames))
cursor += frames
return counts, bounds
def _estimate_cubing_tokens_from_frames(self, frames: int) -> int:
if frames <= 0:
return 0
num_cubes = self._estimate_cubing_cube_count(frames)
tokens = num_cubes * int(getattr(self.config, "resampler_num_queries", 64))
if bool(getattr(self.config, "cubing_use_thumbnail", True)):
tokens += int(getattr(self.config, "thumbnail_num_queries", 64))
return tokens
def _estimate_cubing_cube_count(self, frames: int) -> int:
"""
估算 Cubing 输出的 cube 数量,需与 Cubing 模块逻辑**完全一致**。
Exp 中使用 config.effective_cubing_fpq 计算:
effective_fpq = cubing_fpq // temporal_patch_size
desired_cubes = max(int(round(frames / effective_fpq)) - 1, 1)
然后在 forward 时会强制第一帧为 keyframe,所以实际 cube 数 = desired_cubes + 1。
"""
if frames <= 0:
return 0
# 优先使用预计算的 effective_cubing_fpq
effective_fpq = getattr(self.config, "effective_cubing_fpq", None)
if effective_fpq is None:
# 回退:手动计算(与 Cubing 模块 L218-220 一致)
if self.config is None:
temporal_patch_size = 2 # GLM4V 默认值
else:
temporal_patch_size = max(int(getattr(self.config.vision_config, "temporal_patch_size", 2)), 1)
frames_per_query = max(int(getattr(self.config, "cubing_fpq", 14)), 1)
effective_fpq = max(frames_per_query / float(temporal_patch_size), 1.0)
# 计算 desired_cubes(Gumbel 采样的目标数量,不包括首帧)
desired_cubes = max(int(round(frames / effective_fpq)) - 1, 1)
# +1 是因为首帧强制为 keyframe
return desired_cubes + 1
def _calculate_native_video_tokens(self, video_grid_thw) -> List[int]:
"""
Calculate placeholder tokens for Native GLM4V mode.
Args:
video_grid_thw: [num_videos, 3] - (temporal, height, width) for each video
Returns:
List of token counts for each video
"""
if video_grid_thw is None:
return []
# Get spatial_merge_size from config
if self.config is None:
spatial_merge_size = 2 # Default GLM4V value
else:
spatial_merge_size = int(getattr(self.config.vision_config, "spatial_merge_size", 2))
counts: List[int] = []
for entry in video_grid_thw:
t, h, w = int(entry[0]), int(entry[1]), int(entry[2])
# Original GLM4V formula: T * H * W / (spatial_merge_size^2)
tokens_per_video = (t * h * w) // (spatial_merge_size ** 2)
counts.append(tokens_per_video)
return counts
# ==== Timestamp 相关工具 ====
@staticmethod
def _format_timestamp(seconds: float) -> str:
"""格式化时间戳为固定宽度字符串,例如 0.0 -> 0000.0。"""
return f"{seconds:06.1f}"
def _split_frames_to_cubes(self, total_frames: int, num_cubes: int) -> List[Tuple[int, int]]:
"""将帧均匀分割到各个 cube。"""
if num_cubes <= 0 or total_frames <= 0:
return []
num_cubes = min(num_cubes, total_frames)
cube_bounds: List[Tuple[int, int]] = []
frames_per_cube = total_frames / num_cubes
for i in range(num_cubes):
start = int(round(i * frames_per_cube))
end = int(round((i + 1) * frames_per_cube))
if i == num_cubes - 1:
end = total_frames
cube_bounds.append((start, end))
return cube_bounds
def _build_cubing_timestamps(
self,
video_grid_thw,
fps_list: Optional[List[float]],
) -> List[List[str]]:
"""基于 grid/fps 预估每个视频的时间戳字符串列表。"""
timestamps_all: List[List[str]] = []
for idx, entry in enumerate(video_grid_thw or []):
frames = int(entry[0])
num_cubes = self._estimate_cubing_cube_count(frames)
bounds = self._split_frames_to_cubes(frames, num_cubes)
fps = None
if fps_list and idx < len(fps_list):
fps = fps_list[idx]
if fps is None or fps <= 0:
timestamps_all.append([])
continue
timestamps = []
for start, _ in bounds:
seconds = start / float(fps)
timestamps.append(self._format_timestamp(seconds))
timestamps_all.append(timestamps)
return timestamps_all
def _construct_videos_bound(self, video_grid_thw) -> List[Tuple[int, int]]:
"""
Construct videos_bound from video_grid_thw.
This is used when videos_bound is not provided but auto-inference is desired.
Assumes each entry in video_grid_thw represents a separate video.
Args:
video_grid_thw: [num_videos, 3] - (temporal, height, width) for each video
Returns:
List of (start_frame, end_frame) tuples
Example:
>>> video_grid_thw = torch.tensor([[120, 24, 24], [80, 24, 24]])
>>> videos_bound = self._construct_videos_bound(video_grid_thw)
>>> print(videos_bound)
[(0, 120), (120, 200)]
"""
if video_grid_thw is None:
return []
bounds: List[Tuple[int, int]] = []
cursor = 0
for entry in video_grid_thw:
num_frames = int(entry[0])
bounds.append((cursor, cursor + num_frames))
cursor += num_frames
return bounds
__all__ = ["Quicksviewer2Processor", "Quicksviewer2ProcessorKwargs"]
AutoProcessor.register(Quicksviewer2Config, Quicksviewer2Processor, exist_ok=True)