CoolFace
Modelpublic

TIGER-Lab/VLM2Vec-LoRA

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
11likes538downloads
processing_phi3_v.py511 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16"""17Processor class for Phi3-V.18"""19import re20from typing import List, Optional, Union21 22import torch23 24import transformers25from transformers.feature_extraction_utils import BatchFeature26from transformers.image_utils import ImageInput27from transformers.processing_utils import ProcessorMixin28from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy29from transformers.utils import TensorType30 31"""Image processor class for Phi3-V."""32 33from typing import List, Optional, Union34 35import numpy as np36 37from transformers.image_processing_utils import BaseImageProcessor, BatchFeature38from transformers.image_transforms import (39    convert_to_rgb,40)41from transformers.image_utils import (42    OPENAI_CLIP_MEAN,43    OPENAI_CLIP_STD,44    is_valid_image,45    make_list_of_images,46    valid_images,47)48from transformers.utils import TensorType, is_vision_available, logging49 50from transformers import AutoImageProcessor51 52logger = logging.get_logger(__name__)53 54if is_vision_available():55    from PIL import Image56 57import torch58import torchvision59 60MultiFrameImageInput = Union[List[List["Image.Image"]], List[List[np.ndarray]], List[List["torch.Tensor"]]]61 62def padding_336(b):63    width, height = b.size64    tar = int(np.ceil(height / 336) * 336)65    top_padding = int((tar - height) / 2)66    bottom_padding = tar - height - top_padding67    left_padding = 068    right_padding = 069    b = torchvision.transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding],70                                              fill=[255, 255, 255])71 72    return b73 74 75def calc_padded_size(width, height, padding_unit=336):76    target_height = int(np.ceil(height / padding_unit) * padding_unit)77    top_padding = int((target_height - height) / 2)78    bottom_padding = target_height - height - top_padding79    left_padding = 080    right_padding = 081    padded_width = width + left_padding + right_padding82    padded_height = height + top_padding + bottom_padding83    return padded_width, padded_height84 85 86def HD_transform(img, hd_num=16):87    width, height = img.size88    trans = False89    if width < height:90        img = img.transpose(Image.TRANSPOSE)91        trans = True92        width, height = img.size93    ratio = (width / height)94    scale = 195    while scale * np.ceil(scale / ratio) <= hd_num:96        scale += 197    scale -= 198    new_w = int(scale * 336)99    new_h = int(new_w / ratio)100 101    img = torchvision.transforms.functional.resize(img, [new_h, new_w], )102    img = padding_336(img)103    width, height = img.size104    if trans:105        img = img.transpose(Image.TRANSPOSE)106 107    return img108 109 110def calc_hd_transform_size(width, height, hd_num=16):111    transposed = False112    if width < height:113        width, height = height, width114        transposed = True115 116    ratio = width / height117    scale = 1118    while scale * np.ceil(scale / ratio) <= hd_num:119        scale += 1120    scale -= 1121 122    new_width = int(scale * 336)123    new_height = int(new_width / ratio)124 125    padded_width, padded_height = calc_padded_size(new_width, new_height)126 127    if transposed:128        padded_width, padded_height = padded_height, padded_width129 130    return padded_width, padded_height131 132 133def pad_to_max_num_crops_tensor(images, max_crops=5):134    """135    images: B x 3 x H x W, B<=max_crops136    """137    B, _, H, W = images.shape138    if B < max_crops:139        pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)140        images = torch.cat([images, pad], dim=0)141    return images142 143def is_multi_frames(images):144    if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)):145        return is_valid_image(images[0][0])146    else:147        return False148 149class Phi3VImageProcessor(BaseImageProcessor):150    r"""151    Constructs a Phi3 image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques152    for processing high resolution images as explained in the [InternLM-XComposer2-4KHD](https://arxiv.org/pdf/2404.06512)153 154    Args:155        image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):156            Mean to use if normalizing the image. This is a float or list of floats the length of the number of157            channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.158        image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):159            Standard deviation to use if normalizing the image. This is a float or list of floats the length of the160            number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.161            Can be overridden by the `image_std` parameter in the `preprocess` method.162        do_convert_rgb (`bool`, *optional*, defaults to `True`):163            Whether to convert the image to RGB.164    """165 166    model_input_names = ["pixel_values"]167 168    def __init__(169        self,170        num_crops: int = 1,171        image_mean: Optional[Union[float, List[float]]] = None,172        image_std: Optional[Union[float, List[float]]] = None,173        do_convert_rgb: bool = True,174        **kwargs,175    ) -> None:176        super().__init__(**kwargs)177        self.num_crops = num_crops178        self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN179        self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD180        self.do_convert_rgb = do_convert_rgb181 182    def calc_num_image_tokens(183        self,184        images: ImageInput185    ):186        """ Calculate the number of image tokens for each image.187        Args:188            images (`ImageInput`):189                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If190                passing in images with pixel values between 0 and 1, set `do_rescale=False`.191        """192        images = make_list_of_images(images)193 194        if not valid_images(images):195            raise ValueError(196                "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "197                "torch.Tensor, tf.Tensor or jax.ndarray."198            )199 200        images = [image.convert('RGB') for image in images]201        # (H, W, C)202        elems = [HD_transform(im, hd_num=self.num_crops) for im in images]203        shapes = [[im.size[1], im.size[0]] for im in elems]204        num_img_tokens = [int((h // 336 * w // 336 + 1) * 144 + 1 + (h // 336 + 1) * 12) for h, w in shapes]205        return num_img_tokens206 207    def calc_num_image_tokens_from_image_size(self, width, height):208        """209        Calculate the number of image tokens for a given image size.210        Args:211            width (`int`): Width of the image.212            height (`int`): Height of the image.213        """214        new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)215        num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)216        return num_img_tokens217 218    def preprocess(219        self,220        images: ImageInput,221        image_mean: Optional[Union[float, List[float]]] = None,222        image_std: Optional[Union[float, List[float]]] = None,223        do_convert_rgb: bool = None,224        return_tensors: Optional[Union[str, TensorType]] = None,225    ):226        """227        Args:228            images (`ImageInput`):229                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If230                passing in images with pixel values between 0 and 1, set `do_rescale=False`.231            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):232                Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.233            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):234                Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to235                `True`.236            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):237                Whether to convert the image to RGB.238            return_tensors (`str` or `TensorType`, *optional*):239                The type of tensors to return. Can be one of:240                - Unset: Return a list of `np.ndarray`.241                - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.242                - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.243                - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.244                - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.245        """246        image_mean = image_mean if image_mean is not None else self.image_mean247        image_std = image_std if image_std is not None else self.image_std248        do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb249 250        images = make_list_of_images(images)251 252        if not valid_images(images):253            raise ValueError(254                "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "255                "torch.Tensor, tf.Tensor or jax.ndarray."256            )257 258        if do_convert_rgb:259            images = [convert_to_rgb(image) for image in images]260 261        image_sizes = []262        img_processor = torchvision.transforms.Compose([263            torchvision.transforms.ToTensor(),264            torchvision.transforms.Normalize(image_mean, image_std)265        ])266 267        # PIL images268        # HD_transform pad images to size of multiiply of 336, 336269        # convert to RGB first270        images = [image.convert('RGB') for image in images]271        elems = [HD_transform(im, hd_num=self.num_crops) for im in images]272        # tensor transform and normalize273        hd_images = [img_processor(im) for im in elems]274        # create global image275        global_image = [276            torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic', ).to(im.dtype) for277            im in hd_images]278 279        # [(3, h, w)], where h, w is multiple of 336280        shapes = [[im.size(1), im.size(2)] for im in hd_images]281        num_img_tokens = [int(((h // 336) * (w // 336) + 1) * 144 + 1 + (h // 336 + 1) * 12) for h, w in shapes]282        # reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)283        # (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)284        hd_images_reshape = [285            im.reshape(1, 3, h // 336, 336, w // 336, 336).permute(0, 2, 4, 1, 3, 5).reshape(-1, 3, 336, 336).contiguous() for286            im, (h, w) in zip(hd_images, shapes)]287        # concat global image and local image288        hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in289                             zip(global_image, hd_images_reshape)]290 291        # pad to max_num_crops292        image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops + 1) for im in hd_images_reshape]293        image_transformed = torch.stack(image_transformed, dim=0)294        image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]295        padded_images = image_transformed296        image_sizes = shapes297 298        data = {"pixel_values": padded_images,299                "image_sizes": image_sizes,300                "num_img_tokens": num_img_tokens301                }302 303        return BatchFeature(data=data, tensor_type=return_tensors)304 305 306AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)307 308transformers.Phi3VImageProcessor = Phi3VImageProcessor309 310 311class Phi3VProcessor(ProcessorMixin):312    r"""313    Constructs a Phi3-V processor which wraps a Phi3-V image processor and a LLaMa tokenizer into a single processor.314 315    [`Phi3VProcessor`] offers all the functionalities of [`Phi3VImageProcessor`] and [`LlamaTokenizerFast`]. See the316    [`~Phi3VProcessor.__call__`] and [`~Phi3VProcessor.decode`] for more information.317 318    Args:319        image_processor ([`Phi3VImageProcessor`], *optional*):320            The image processor is a required input.321        tokenizer ([`LlamaTokenizerFast`], *optional*):322            The tokenizer is a required input.323    """324 325    attributes = ["image_processor", "tokenizer"]326    image_processor_class = "Phi3VImageProcessor"327    tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")328    special_image_token = "<|image|>"329 330    def __init__(self, image_processor, tokenizer):331        self.image_processor = image_processor332        self.tokenizer = tokenizer333        self.num_img_tokens = image_processor.num_img_tokens334        self.img_tokens = [f"<|image_{i + 1}|>" for i in range(1000000)]335 336    def __call__(337        self,338        text: Union[TextInput, List[TextInput]],339        images: Union[ImageInput, MultiFrameImageInput] = None,340        padding: Union[bool, str, PaddingStrategy] = False,341        truncation: Union[bool, str, TruncationStrategy] = None,342        max_length=None,343        return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,344    ) -> BatchFeature:345        """346        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`347        and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode348        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to349        Phi3ImageProcessor's [`~Phi3ImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring350        of the above two methods for more information.351 352        Args:353            text (`str`, `List[str]`, `List[List[str]]`):354                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings355                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set356                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).357            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):358                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch359                tensor. Both channels-first and channels-last formats are supported.360            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):361                Select a strategy to pad the returned sequences (according to the model's padding side and padding362                index) among:363                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single364                  sequence if provided).365                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum366                  acceptable input length for the model if that argument is not provided.367                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different368                  lengths).369            max_length (`int`, *optional*):370                Maximum length of the returned list and optionally padding length (see above).371            truncation (`bool`, *optional*):372                Activates truncation to cut input sequences longer than `max_length` to `max_length`.373            return_tensors (`str` or [`~utils.TensorType`], *optional*):374                If set, will return tensors of a particular framework. Acceptable values are:375 376                - `'tf'`: Return TensorFlow `tf.constant` objects.377                - `'pt'`: Return PyTorch `torch.Tensor` objects.378                - `'np'`: Return NumPy `np.ndarray` objects.379                - `'jax'`: Return JAX `jnp.ndarray` objects.380 381        Returns:382            [`BatchFeature`]: A [`BatchFeature`] with the following fields:383 384            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.385            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when386              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not387              `None`).388            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.389        """390        if images is not None:391            if is_multi_frames(images):392                images = [image for sample_images in images for image in sample_images]393            image_inputs = self.image_processor(images, return_tensors=return_tensors)394        else:395            image_inputs = {}396        inputs = self._convert_images_texts_to_inputs(image_inputs, text, padding=padding, truncation=truncation,397                                                      max_length=max_length, return_tensors=return_tensors)398        return inputs399 400    def calc_num_image_tokens(self, images: ImageInput):401        """ Calculate the number of image tokens for each image.402        Args:403            images (`ImageInput`):404                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If405                passing in images with pixel values between 0 and 1, set `do_rescale=False`.406        """407        return self.image_processor.calc_num_image_tokens(images)408 409    def calc_num_image_tokens_from_image_size(self, width, height):410        """ Calculate the number of image token for an image with given width and height.411        Args:412            width (`int`):413                Width of the image.414            height (`int`):415                Height of the image.416        """417        return self.image_processor.calc_num_image_tokens_from_image_size(width, height)418 419    @property420    def special_image_token_id(self):421        return self.tokenizer.convert_tokens_to_ids(self.special_image_token)422 423    def get_special_image_token_id(self):424        return self.tokenizer.convert_tokens_to_ids(self.special_image_token)425 426    def _convert_images_texts_to_inputs(self, images, texts, padding=False, truncation=None, max_length=None, return_tensors=None):427        if not len(images):428            model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length)429            return BatchFeature(data={**model_inputs})430 431        pattern = r"<\|image_\d+\|>"432        if isinstance(texts, str):433           texts = [texts]434        435        prompt_chunks = []436        image_tags = []437        for text in texts:438            prompt_chunks.append([self.tokenizer(chunk, truncation=truncation, max_length=max_length).input_ids for chunk in re.split(pattern, text)])439            image_tags.append(re.findall(pattern, text))    440 441        if 'num_img_tokens' in images:442            num_img_tokens = images['num_img_tokens']443        else:444            assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'445            num_crops = images['num_crops']446            num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]447 448        images, image_sizes = images['pixel_values'], images['image_sizes']449 450        # image_tags needs to start from 1 to n451        # image_tags = re.findall(pattern, texts)452        # image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]453        # image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]454        455        image_ids_counter = 0456        image_ids = []457        for tags in image_tags:458            image_ids.append([int(s.split("|")[1].split("_")[-1]) + image_ids_counter for s in tags])459            image_ids_counter += len(tags)460        unique_image_ids = sorted(list(set([iid for ids in image_ids for iid in ids])))461        # image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]462        # check the condition463        assert unique_image_ids == list(range(1, len(unique_image_ids) + 1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"464        # total images must be the same as the number of image tags465        assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"466 467        image_ids_pad = [[[-iid]*num_img_tokens[iid-1] for iid in ids] for ids in image_ids]468 469        def insert_separator(X, sep_list):470            if len(X) > len(sep_list):471                sep_list.append([])472            return [ele for sublist in zip(X, sep_list) for ele in sublist]473 474        input_ids = []475        for sub_prompt_chunks, sub_image_ids_pad in zip(prompt_chunks, image_ids_pad):476            input_ids.append([])477            offset = 0478            for x in insert_separator(sub_prompt_chunks, sub_image_ids_pad):479                input_ids[-1].extend(x[offset:])480 481        input_ids = torch.tensor(input_ids, dtype=torch.long)482        attention_mask = (input_ids > -1000000).to(torch.long)483        attention_mask[input_ids == self.tokenizer.pad_token_id] = 0484 485        return BatchFeature(data={"input_ids": input_ids,486                                  "attention_mask": attention_mask,487                                  "pixel_values": images,488                                  "image_sizes": image_sizes})489 490    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama491    def batch_decode(self, *args, **kwargs):492        """493        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please494        refer to the docstring of this method for more information.495        """496        return self.tokenizer.batch_decode(*args, **kwargs)497 498    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama499    def decode(self, *args, **kwargs):500        """501        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to502        the docstring of this method for more information.503        """504        return self.tokenizer.decode(*args, **kwargs)505 506    @property507    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names508    def model_input_names(self):509        tokenizer_input_names = self.tokenizer.model_input_names510        image_processor_input_names = self.image_processor.model_input_names511        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))