# ============================================================================= # ==== 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, ""): 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|>", "