Team Ai
Modelpublic

openbmb/AgentCPM-GUI

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
138likes266downloads
processing_minicpmv.py241 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2024 The HuggingFace Inc. team.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"""16Processor class for MiniCPMV.17"""18 19from typing import List, Optional, Union, Dict, Any20import torch21import re22 23from transformers.image_processing_utils import BatchFeature24from transformers.image_utils import ImageInput25from transformers.processing_utils import ProcessorMixin26from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy27from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device28 29from .image_processing_minicpmv import MiniCPMVBatchFeature30 31 32class MiniCPMVProcessor(ProcessorMixin):33    r"""34    Constructs a MiniCPMV processor which wraps a MiniCPMV image processor and a MiniCPMV tokenizer into a single processor.35 36    [`MiniCPMVProcessor`] offers all the functionalities of [`MiniCPMVImageProcessor`] and [`LlamaTokenizerWrapper`]. See the37    [`~MiniCPMVProcessor.__call__`] and [`~MiniCPMVProcessor.decode`] for more information.38 39    Args:40        image_processor ([`MiniCPMVImageProcessor`], *optional*):41            The image processor is a required input.42        tokenizer ([`LlamaTokenizerWrapper`], *optional*):43            The tokenizer is a required input.44    """45    attributes = ["image_processor", "tokenizer"]46    image_processor_class = "AutoImageProcessor"47    tokenizer_class = "AutoTokenizer"48 49    def __init__(self, image_processor=None, tokenizer=None):50        super().__init__(image_processor, tokenizer)51        self.version = image_processor.version52    53    def __call__(54        self,55        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],56        images: ImageInput = None,57        max_length: Optional[int] = None,58        do_pad: Optional[bool] = True,59        max_slice_nums: int = None,60        use_image_id: bool = None,61        return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,62        **kwargs63    ) -> MiniCPMVBatchFeature:64 65        if images is not None:66            image_inputs = self.image_processor(images, do_pad=do_pad, max_slice_nums=max_slice_nums, return_tensors=return_tensors)67        return self._convert_images_texts_to_inputs(image_inputs, text, max_slice_nums=max_slice_nums, use_image_id=use_image_id, max_length=max_length, **kwargs)68    69    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama70    def batch_decode(self, *args, **kwargs):71        """72        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please73        refer to the docstring of this method for more information.74        """75        output_ids = args[0]76        result_text = []77        for result in output_ids:78            result = result[result != 0]79            if result[0] == self.tokenizer.bos_id:80                result = result[1:]81            if result[-1] == self.tokenizer.eos_id:82                result = result[:-1]83            result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())84        return result_text85        # return self.tokenizer.batch_decode(*args, **kwargs)86    87    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama88    def decode(self, *args, **kwargs):89        """90        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to91        the docstring of this method for more information.92        """93        result = args[0]94        result = result[result != 0]95        if result[0] == self.tokenizer.bos_id:96            result = result[1:]97        if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):98            result = result[:-1]99        return self.tokenizer.decode(result, *args[1:], **kwargs).strip()100 101    def _convert(102        self, input_str, max_inp_length: Optional[int] = None103    ):104        if self.version > 2.5 or not getattr(self.tokenizer, "add_bos_token", False):105            input_ids = self.tokenizer.encode(input_str)106        else:107            input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)108        if max_inp_length is not None:109            input_ids = input_ids[:max_inp_length]110        input_ids = torch.tensor(input_ids, dtype=torch.int32)111 112        start_cond = (input_ids == self.tokenizer.im_start_id) | (input_ids == self.tokenizer.slice_start_id)113        end_cond = (input_ids == self.tokenizer.im_end_id) | (input_ids == self.tokenizer.slice_end_id)114 115        image_start_tokens = torch.where(start_cond)[0]116        image_start_tokens += 1117        image_end_tokens = torch.where(end_cond)[0]118 119        valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))120 121        image_bounds = torch.hstack(122            [123                image_start_tokens[:valid_image_nums].unsqueeze(-1),124                image_end_tokens[:valid_image_nums].unsqueeze(-1),125            ]126        )127        return input_ids, image_bounds128 129    def _convert_images_texts_to_inputs(130            self, 131            images, 132            texts: Union[str, List[str]], 133            truncation=None, 134            max_length=None,135            max_slice_nums=None,136            use_image_id=None, 137            return_tensors=None,138            **kwargs139        ):140        if images is None or not len(images):141            model_inputs = self.tokenizer(texts, return_tensors=return_tensors, truncation=truncation, max_length=max_length, **kwargs)142            return MiniCPMVBatchFeature(data={**model_inputs})143        144        pattern = "(<image>./</image>)"145        images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]146        147        if isinstance(texts, str):148            texts = [texts]149        input_ids_list = []150        image_bounds_list = []151        for index, text in enumerate(texts):152            image_tags = re.findall(pattern, text)153            assert len(image_tags) == len(image_sizes[index])154            text_chunks = text.split(pattern)155            final_text = ""156            for i in range(len(image_tags)):157                final_text = final_text + text_chunks[i] + \158                    self.image_processor.get_slice_image_placeholder(159                        image_sizes[index][i], 160                        i,161                        max_slice_nums,162                        use_image_id163                    )164            final_text += text_chunks[-1]165            input_ids, image_bounds = self._convert(final_text, max_length)166            input_ids_list.append(input_ids)167            image_bounds_list.append(image_bounds)168        padded_input_ids, padding_lengths = self.pad(169            input_ids_list,170            padding_side="left"171        )172        for i, length in enumerate(padding_lengths):173            image_bounds_list[i] = image_bounds_list[i] + length174        attention_mask = padded_input_ids.ne(0)175 176        return MiniCPMVBatchFeature(data={177            "input_ids": padded_input_ids,178            "attention_mask": attention_mask,179            "pixel_values": images,180            "image_sizes": image_sizes,181            "image_bound": image_bounds_list,182            "tgt_sizes": tgt_sizes183        })184 185    @property186    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names187    def model_input_names(self):188        tokenizer_input_names = self.tokenizer.model_input_names189        image_processor_input_names = self.image_processor.model_input_names190        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))191 192 193    def pad(self, inputs, max_length=None, padding_value=0, padding_side="left"):194        items = []195        if isinstance(inputs[0], list):196            assert isinstance(inputs[0][0], torch.Tensor)197            for it in inputs:198                for tr in it:199                    items.append(tr)200        else:201            assert isinstance(inputs[0], torch.Tensor)202            items = inputs203 204        batch_size = len(items)205        shape = items[0].shape206        dim = len(shape)207        assert dim <= 2208        if max_length is None:209            max_length = 0210        max_length = max(max_length, max(item.shape[-1] for item in items))211        min_length = min(item.shape[-1] for item in items)212        dtype = items[0].dtype213 214        if dim == 0:215            return torch.stack([item for item in items], dim=0), [0]216        elif dim == 1:217            if max_length == min_length:218                return torch.stack([item for item in items], dim=0), [0] * batch_size219            tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value220        else:221            tensor = (222                torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)223                + padding_value224            )225 226        padding_length = []227        for i, item in enumerate(items):228            if dim == 1:229                if padding_side == "left":230                    tensor[i, -len(item) :] = item.clone()231                else:232                    tensor[i, : len(item)] = item.clone()233            elif dim == 2:234                if padding_side == "left":235                    tensor[i, -len(item) :, :] = item.clone()236                else:237                    tensor[i, : len(item), :] = item.clone()238            padding_length.append(tensor.shape[-1] - len(item))239 240        return tensor, padding_length241