File size: 13,320 Bytes
786ef94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""

Processor class for TraVisionLM.

"""

import logging
from typing import List, Optional, Union

from transformers.feature_extraction_utils import BatchFeature
from transformers.image_utils import ImageInput, is_valid_image
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils import (
    AddedToken,
    PaddingStrategy,
    PreTokenizedInput,
    TextInput,
    TruncationStrategy,  
)
from transformers.utils import TensorType

logger = logging.getLogger(__name__)

IMAGE_TOKEN = "<image>"
EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] # for object detection task

# Copied from transformers.models.idefics2.processing_idefics2.is_url
def is_url(val) -> bool:
    return isinstance(val, str) and val.startswith("http")


# Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
def is_image_or_image_url(elem):
    return is_url(elem) or is_valid_image(elem)

# Copied from transformers.models.paligemma.processing_paligemma._is_str_or_image
def _is_str_or_image(elem):
    return isinstance(elem, (str)) or is_image_or_image_url(elem)


def build_string_from_input(image_seq_len, image_token):
    """

    Builds a string from the input prompt and image tokens.

    For example, for the call:

    build_string_from_input(

        image_seq_len=3,

        image_token="<im>",

    )

    The output will be:

    "<im><im><im>"

    Args:

        image_seq_len (`int`): The length of the image sequence.

        image_token (`str`): The image token.

    """
    return f"{image_token * image_seq_len}"


class TraVisionProcessor(ProcessorMixin):
    r"""

    Constructs a TraVision processor which wraps a SigLIP image processor and a GPT2 tokenizer into a single processor.



    [`TraVisionProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GPT2TokenizerFast`]. See the

    [`~TraVisionProcessor.__call__`] and [`~TraVisionProcessor.decode`] for more information.



    Args:

        image_processor ([`SiglipImageProcessor`], *optional*):

            The image processor is a required input.

        tokenizer ([`GPT2TokenizerFast`], *optional*):

            The tokenizer 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"]
    valid_kwargs = ["chat_template"]
    image_processor_class = "SiglipImageProcessor"
    tokenizer_class = ("GPT2Tokenizer", "GPT2TokenizerFast")

    def __init__(

        self,

        image_processor=None,

        tokenizer=None,

        chat_template=None,

        **kwargs,

    ):
        if image_processor is None:
            raise ValueError("You need to specify an `image_processor`.")
        if tokenizer is None:
            raise ValueError("You need to specify a `tokenizer`.")
        if not hasattr(image_processor, "image_seq_length"):
            raise ValueError("Image processor is missing an `image_seq_length` attribute.")

        self.image_seq_length = image_processor.image_seq_length

        image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
        tokens_to_add = {"additional_special_tokens": [image_token]}
        tokenizer.add_special_tokens(tokens_to_add)
        tokenizer.add_tokens(EXTRA_TOKENS)
        self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
        tokenizer.add_bos_token = False
        tokenizer.add_eos_token = False

        super().__init__(image_processor, tokenizer, chat_template=chat_template)

    def __call__(

        self,

        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,

        images: ImageInput = None,

        tokenize_newline_separately: bool = True,

        padding: Union[bool, str, PaddingStrategy] = False,

        truncation: Union[bool, str, TruncationStrategy] = None,

        max_length=None,

        return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,

        do_resize: bool = None,

        do_normalize: bool = None,

        image_mean: Optional[Union[float, List[float]]] = None,

        image_std: Optional[Union[float, List[float]]] = None,

        data_format: Optional["ChannelDimension"] = "channels_first",  # noqa: F821

        input_data_format: Optional[

            Union[str, "ChannelDimension"]  # noqa: F821

        ] = None,

        resample: "PILImageResampling" = None,  # noqa: F821

        do_convert_rgb: bool = None,

        do_thumbnail: bool = None,

        do_align_long_axis: bool = None,

        do_rescale: bool = None,

        labels: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,

    ) -> 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 GPT2TokenizerFast's [`~GPT2TokenizerFast.__call__`] if `text` is not `None` to encode

        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to

        SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring

        of the above two methods for more information.



        The usage for TraVisionLM fine-tuning preparation follows a standard 4D causal mask where only the prompt and label tokens

        are attended in an auto-regressive manner. The label in `text` are to be passed separately to the __call__ function and 

        will be placed after the prompt, which is the instruction to steer the model generation. 



        Args:

            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).

            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. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a

                number of channels, H and W are image height and width.

            tokenize_newline_separately (`bool`, defaults to `True`):

                Adds a separately tokenized '\n' at the end of the prompt.

            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):

                Select a strategy to pad the returned sequences (according to the model's padding side and padding

                index) among:

                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single

                  sequence if provided).

                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum

                  acceptable input length for the model if that argument is not provided.

                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different

                  lengths).

            max_length (`int`, *optional*):

                Maximum length of the returned list and optionally padding length (see above).

            truncation (`bool`, *optional*):

                Activates truncation to cut input sequences longer than `max_length` to `max_length`.

            return_tensors (`str` or [`~utils.TensorType`], *optional*):

                If set, will return tensors of a particular framework. Acceptable values are:



                - `'tf'`: Return TensorFlow `tf.constant` objects.

                - `'pt'`: Return PyTorch `torch.Tensor` objects.

                - `'np'`: Return NumPy `np.ndarray` objects.

                - `'jax'`: Return JAX `jnp.ndarray` objects.

            label (`str`, `List[str]`, `List[List[str]]`):

                The label or batch of labels to be encoded. Only necessary for training. 

                for more information. If your prompt is "<image> Resimde ne var", the label corresponds to the expected prediction "çimlerde uzanan bir köpek".



        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`. If `label`

              is provided, the `input_ids` will also contain the label input ids.

            - **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`.

            - **labels** -- Labels compatible with training if `label` is not None

        """

        # return_token_type_ids = True if labels is not None else False
        return_token_type_ids = True

        if images is None:
            raise ValueError("`images` are expected as arguments to a `TraVisionProcessor` instance.")
        if text is None:
            logger.warning_once(
                "You are using TraVisionLM without a text prefix. It will perform as a picture-captioning model."
            )
            text = "Açıkla"  # default prompt if it is not provided as an argument

        if isinstance(text, List) and isinstance(images, List):
            if len(images) < len(text):
                raise ValueError(
                    f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image."
                )
        if _is_str_or_image(text):
            text = [text]
        elif isinstance(text, list) and _is_str_or_image(text[0]):
            pass
        text = [f"{prompt}\n" for prompt in text]

        if labels is not None and _is_str_or_image(labels):
            labels = [labels]
        if labels is not None:
            labels = [label + self.tokenizer.eos_token for label in labels]
        
            text = [f"{prompt}{label}" for prompt, label in zip(text, labels)]

        input_strings = [
            build_string_from_input(
                image_seq_len=self.image_seq_length,
                image_token=IMAGE_TOKEN,
            )            
            for _ in text
        ]

        pixel_values = self.image_processor(
            images,
            do_resize=do_resize,
            do_normalize=do_normalize,
            return_tensors=return_tensors,
            image_mean=image_mean,
            image_std=image_std,
            input_data_format=input_data_format,
            data_format=data_format,
            resample=resample,
            do_convert_rgb=do_convert_rgb,
        )["pixel_values"]

        if max_length is not None:
            max_length += self.image_seq_length  # max_length has to account for the image tokens

        inputs = self.tokenizer(
            input_strings,
            text_pair=text,
            return_tensors=return_tensors,
            padding=padding,
            max_length=max_length,
            truncation=truncation,
            return_token_type_ids=return_token_type_ids,
        )

        return_data = {**inputs, "pixel_values": pixel_values}

        if labels is not None:
            labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
            return_data.update({"labels": labels})
        return BatchFeature(data=return_data)

    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->GPT2
    def batch_decode(self, *args, **kwargs):
        """

        This method forwards all its arguments to GPT2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please

        refer to the docstring of this method for more information.

        """
        return self.tokenizer.batch_decode(*args, **kwargs)

    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->GPT2
    def decode(self, *args, **kwargs):
        """

        This method forwards all its arguments to GPT2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to

        the docstring of this method for more information.

        """
        return self.tokenizer.decode(*args, **kwargs)

    @property
    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names with CLIP->TraVision
    def model_input_names(self):
        tokenizer_input_names = self.tokenizer.model_input_names
        image_processor_input_names = self.image_processor.model_input_names
        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))