Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.3#4# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX5# and OPT implementations in this library. It has been modified from its6# original forms to accommodate minor architectural differences compared7# to GPT-NeoX and OPT used by the Meta AI team that trained the model.8#9# Licensed under the Apache License, Version 2.0 (the "License");10# you may not use this file except in compliance with the License.11# You may obtain a copy of the License at12#13# http://www.apache.org/licenses/LICENSE-2.014#15# Unless required by applicable law or agreed to in writing, software16# distributed under the License is distributed on an "AS IS" BASIS,17# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18# See the License for the specific language governing permissions and19# limitations under the License.20"""21Processor class for Qwen2-VL.22"""23 24from typing import Optional, Union25 26import numpy as np27 28from ...feature_extraction_utils import BatchFeature29from ...image_utils import ImageInput30from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack31from ...tokenization_utils_base import PreTokenizedInput, TextInput32from ...utils import logging33from ...video_utils import VideoInput34 35 36logger = logging.get_logger(__name__)37 38 39class Qwen2VLImagesKwargs(ImagesKwargs):40 min_pixels: Optional[int]41 max_pixels: Optional[int]42 patch_size: Optional[int]43 temporal_patch_size: Optional[int]44 merge_size: Optional[int]45 46 47class Qwen2VLProcessorKwargs(ProcessingKwargs, total=False):48 images_kwargs: Qwen2VLImagesKwargs49 _defaults = {50 "text_kwargs": {51 "padding": False,52 "return_mm_token_type_ids": False,53 },54 }55 56 57class Qwen2VLProcessor(ProcessorMixin):58 r"""59 Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.60 [`Qwen2VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the61 [`~Qwen2VLProcessor.__call__`] and [`~Qwen2VLProcessor.decode`] for more information.62 Args:63 image_processor ([`Qwen2VLImageProcessor`], *optional*):64 The image processor is a required input.65 tokenizer ([`Qwen2TokenizerFast`], *optional*):66 The tokenizer is a required input.67 video_processor ([`Qwen2VLVideoProcessor`], *optional*):68 The video processor is a required input.69 chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages70 in a chat into a tokenizable string.71 """72 73 attributes = ["image_processor", "tokenizer", "video_processor"]74 image_processor_class = "AutoImageProcessor"75 video_processor_class = "AutoVideoProcessor"76 tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")77 78 def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):79 self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token80 self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token81 self.image_token_id = (82 tokenizer.image_token_id83 if getattr(tokenizer, "image_token_id", None)84 else tokenizer.convert_tokens_to_ids(self.image_token)85 )86 self.video_token_id = (87 tokenizer.video_token_id88 if getattr(tokenizer, "video_token_id", None)89 else tokenizer.convert_tokens_to_ids(self.video_token)90 )91 super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)92 93 def __call__(94 self,95 images: Optional[ImageInput] = None,96 text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,97 videos: Optional[VideoInput] = None,98 **kwargs: Unpack[Qwen2VLProcessorKwargs],99 ) -> BatchFeature:100 """101 Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`102 and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode103 the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwargs` arguments to104 Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.105 106 Args:107 images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):108 The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch109 tensor. Both channels-first and channels-last formats are supported.110 text (`str`, `list[str]`, `list[list[str]]`):111 The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings112 (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set113 `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).114 videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):115 The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch116 tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.117 return_tensors (`str` or [`~utils.TensorType`], *optional*):118 If set, will return tensors of a particular framework. Acceptable values are:119 - `'tf'`: Return TensorFlow `tf.constant` objects.120 - `'pt'`: Return PyTorch `torch.Tensor` objects.121 - `'np'`: Return NumPy `np.ndarray` objects.122 - `'jax'`: Return JAX `jnp.ndarray` objects.123 124 Returns:125 [`BatchFeature`]: A [`BatchFeature`] with the following fields:126 127 - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.128 - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when129 `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not130 `None`).131 - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.132 - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.133 - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.134 - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.135 """136 output_kwargs = self._merge_kwargs(137 Qwen2VLProcessorKwargs,138 tokenizer_init_kwargs=self.tokenizer.init_kwargs,139 **kwargs,140 )141 142 image_inputs = videos_inputs = {}143 if images is not None:144 image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])145 image_grid_thw = image_inputs["image_grid_thw"]146 147 if videos is not None:148 videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])149 video_grid_thw = videos_inputs["video_grid_thw"]150 151 if not isinstance(text, list):152 text = [text]153 154 text = text.copy() # below lines change text in-place155 156 if images is not None:157 merge_length = self.image_processor.merge_size**2158 index = 0159 for i in range(len(text)):160 while self.image_token in text[i]:161 num_image_tokens = image_grid_thw[index].prod() // merge_length162 text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)163 index += 1164 text[i] = text[i].replace("<|placeholder|>", self.image_token)165 166 if videos is not None:167 merge_length = self.video_processor.merge_size**2168 index = 0169 for i in range(len(text)):170 while self.video_token in text[i]:171 num_video_tokens = video_grid_thw[index].prod() // merge_length172 text[i] = text[i].replace(self.video_token, "<|placeholder|>" * num_video_tokens, 1)173 index += 1174 text[i] = text[i].replace("<|placeholder|>", self.video_token)175 176 return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)177 return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)178 text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)179 self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])180 181 if return_mm_token_type_ids:182 array_ids = np.array(text_inputs["input_ids"])183 mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])184 mm_token_type_ids[array_ids == self.image_token_id] = 1185 text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()186 187 return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)188 189 def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):190 """191 Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.192 Args:193 image_sizes (`list[list[int]]`, *optional*):194 The input sizes formatted as (height, width) per each image.195 video_sizes (`list[list[int]]`, *optional*):196 The input sizes formatted as (num_frames, height, width) per each video.197 Returns:198 `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided199 input modalities, along with other useful data.200 """201 202 vision_data = {}203 if image_sizes is not None:204 images_kwargs = Qwen2VLProcessorKwargs._defaults.get("images_kwargs", {})205 images_kwargs.update(kwargs)206 merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size207 208 num_image_patches = [209 self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)210 for image_size in image_sizes211 ]212 num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]213 vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})214 215 if video_sizes is not None:216 videos_kwargs = Qwen2VLProcessorKwargs._defaults.get("videos_kwargs", {})217 videos_kwargs.update(kwargs)218 num_video_patches = [219 self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)220 for video_size in video_sizes221 ]222 num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]223 vision_data["num_video_tokens"] = num_video_tokens224 225 return MultiModalData(**vision_data)226 227 def post_process_image_text_to_text(228 self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs229 ):230 """231 Post-process the output of the model to decode the text.232 233 Args:234 generated_outputs (`torch.Tensor` or `np.ndarray`):235 The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`236 or `(sequence_length,)`.237 skip_special_tokens (`bool`, *optional*, defaults to `True`):238 Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.239 clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):240 Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.241 **kwargs:242 Additional arguments to be passed to the tokenizer's `batch_decode method`.243 244 Returns:245 `list[str]`: The decoded text.246 """247 return self.tokenizer.batch_decode(248 generated_outputs,249 skip_special_tokens=skip_special_tokens,250 clean_up_tokenization_spaces=clean_up_tokenization_spaces,251 **kwargs,252 )253 254 255__all__ = ["Qwen2VLProcessor"]256 