CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
processing_emu3.py249 linesDownload Raw Back to emu3
1# coding=utf-82# Copyright 2024 HuggingFace Inc. team. All rights reserved.3#4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9#     http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16 17from typing import Optional, Union18 19import numpy as np20 21from ...image_processing_utils import BatchFeature22from ...image_utils import ImageInput23from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack24from ...tokenization_utils_base import PreTokenizedInput, TextInput25from ...utils import is_vision_available26 27 28if is_vision_available():29    from .image_processing_emu3 import smart_resize30 31 32class Emu3TextKwargs(TextKwargs, total=False):33    return_for_image_generation: bool34 35 36class Emu3ImagesKwargs(ImagesKwargs, total=False):37    ratio: str38    image_area: int39 40 41class Emu3ProcessorKwargs(ProcessingKwargs, total=False):42    text_kwargs: Emu3TextKwargs43    images_kwargs: Emu3ImagesKwargs44    _defaults = {45        "text_kwargs": {46            "return_for_image_generation": False,47            "return_mm_token_type_ids": False,48        },49        "images_kwargs": {50            "ratio": "1:1",51            "image_area": 518400,52        },53    }54 55 56class Emu3Processor(ProcessorMixin):57    r"""58    Constructs a Emu3 processor which wraps a Emu3 image processor and a GPT2 tokenizer into a single59    processor.60 61    [`Emu3Processor`] offers all the functionalities of [`Emu3ImageProcessor`] and [`GPT2TokenizerFast`].62    See the [`~Emu3Processor.__call__`] and [`~Emu3Processor.decode`] for more information.63 64    Args:65        image_processor ([`Emu3ImageProcessor`]):66            The image processor is a required input.67        tokenizer ([`Emu3TokenizerFast`]):68            The tokenizer 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"]74    tokenizer_class = ("GPT2Tokenizer", "GPT2TokenizerFast")75    image_processor_class = "Emu3ImageProcessor"76 77    def __init__(78        self,79        image_processor,80        tokenizer,81        chat_template=None,82        **kwargs,83    ):84        self.image_token = tokenizer.image_token  # image_token as placeholder to be replaced by vq-vae tokens85        self.image_token_id = tokenizer.image_token_id86        self.image_start_token = tokenizer.boi_token  # "<|image start|>" fixed tokens for start and end of image87        self.image_end_token = tokenizer.eoi_token  # "<|image end|>"88        self.fake_token_around_image = tokenizer.image_wrapper_token  # "<|image token|>"  every image starts with it89        self.eof_token = tokenizer.eof_token  # "<|extra_201|>"90        self.bos_token = tokenizer.bos_token91        self.downsample_ratio = 892        super().__init__(image_processor, tokenizer, chat_template=chat_template)93 94    def __call__(95        self,96        images: Optional[ImageInput] = None,97        text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,98        audio=None,99        videos=None,100        **kwargs: Unpack[Emu3ProcessorKwargs],101    ) -> BatchFeature:102        """103        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`104        and `kwargs` arguments to Emu3TokenizerFast's [`~Emu3TokenizerFast.__call__`] if `text` is not `None` to encode105        the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to106        CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring107        of the above two methods for more information.108 109        Args:110            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):111                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch112                tensor. Both channels-first and channels-last formats are supported.113            text (`str`, `list[str]`, `list[list[str]]`):114                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings115                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set116                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).117            return_tensors (`str` or [`~utils.TensorType`], *optional*):118                If set, will return tensors of a particular framework. Acceptable values are:119 120                - `'tf'`: Return TensorFlow `tf.constant` objects.121                - `'pt'`: Return PyTorch `torch.Tensor` objects.122                - `'np'`: Return NumPy `np.ndarray` objects.123                - `'jax'`: Return JAX `jnp.ndarray` objects.124 125        Returns:126            [`BatchFeature`]: A [`BatchFeature`] with the following fields:127 128            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.129            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when130              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not131              `None`).132            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.133        """134        # check if images and text inputs are reversed for BC135 136        if isinstance(text, str):137            text = [text]138        elif not isinstance(text, list) and not isinstance(text[0], str):139            raise TypeError("Invalid input text. Please provide a string, or a list of strings")140 141        output_kwargs = self._merge_kwargs(142            Emu3ProcessorKwargs,143            tokenizer_init_kwargs=self.tokenizer.init_kwargs,144            **kwargs,145        )146        return_for_image_generation = output_kwargs["text_kwargs"].pop("return_for_image_generation", False)147        ratio = output_kwargs["images_kwargs"].pop("ratio", None)148        image_area = output_kwargs["images_kwargs"].pop("image_area", None)149 150        if return_for_image_generation and images is not None:151            raise ValueError("You should not provide `images` when `return_for_image_generation=True`")152 153        if not return_for_image_generation and text is None and images is None:154            raise ValueError("You must provide either text or images when `return_for_image_generation=False`")155 156        image_features = {}157        image_start_tokens = f"{self.image_start_token}"158        image_end_tokens = f"{self.eof_token}{self.image_end_token}"159 160        # generate text from image + text input, so we add placeholders for image tokens161        if not return_for_image_generation and images is not None:162            image_features = self.image_processor(images, **output_kwargs["images_kwargs"])163            image_sizes = iter(image_features.image_sizes)164 165            prompt_strings = []166            for sample in text:167                while self.image_token in sample:168                    image_size = next(image_sizes)169                    height, width = image_size170                    height = height // self.downsample_ratio171                    width = width // self.downsample_ratio172                    image_seq_length = height * (width + 1)  # +1 for extra row when converting to BPE in modeling code173 174                    image_placeholder = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}{'<placeholder>' * image_seq_length}{image_end_tokens}"175                    sample = sample.replace(self.image_token, image_placeholder, 1)176                    sample = f"{self.bos_token}{sample}"  # add BOS because GPT tokenizer doesn't add it177                prompt_strings.append(sample)178            text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings]179 180        # generate image from text input, so we add begin-of-image tokens from where image generation starts181        elif return_for_image_generation:182            height, width = self.calculate_generate_size(ratio, image_area, self.downsample_ratio)183            image_prompt = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}"184            text = [f"{self.bos_token}{sample}{image_prompt}" for sample in text]185            image_features["image_sizes"] = [[height, width]] * len(text)186 187        # else just generate from text-only input, and we do no special treatment for text188        return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)189        return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)190        text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)191        self._check_special_mm_tokens(text, text_inputs, modalities=["image"])192 193        if return_mm_token_type_ids:194            array_ids = np.array(text_inputs["input_ids"])195            mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])196            mm_token_type_ids[array_ids == self.image_token_id] = 1197            text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()198 199        return BatchFeature(data={**text_inputs, **image_features}, tensor_type=return_tensors)200 201    def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):202        """203        Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.204 205        Args:206            image_sizes (`list[list[int]]`, *optional*):207                The input sizes formatted as (height, width) per each image.208 209        Returns:210            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided211            input modalities, along with other useful data.212        """213 214        vision_data = {}215        if image_sizes is not None:216            num_image_tokens = []217            for height, width in image_sizes:218                height, width = smart_resize(219                    height,220                    width,221                    self.image_processor.spatial_factor,222                    self.image_processor.min_pixels,223                    self.image_processor.max_pixels,224                )225                height = height // self.downsample_ratio226                width = width // self.downsample_ratio227                image_seq_length = height * (width + 1)  # +1 for extra row when converting to BPE in modeling code228                num_image_tokens.append(image_seq_length)229 230            num_image_patches = [1] * len(image_sizes)231            vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})232 233        return MultiModalData(**vision_data)234 235    def calculate_generate_size(self, ratio, image_area, spatial_factor):236        width, height = map(int, ratio.split(":"))237        current_area = width * height238        target_ratio = (image_area / current_area) ** 0.5239 240        token_height = int(round(height * target_ratio / spatial_factor))241        token_width = int(round(width * target_ratio / spatial_factor))242        return token_height, token_width243 244    def postprocess(self, images: ImageInput, **kwargs):245        return self.image_processor.postprocess(images, **kwargs)246 247 248__all__ = ["Emu3Processor"]249