benchang1110 commited on
Commit
b48abc0
1 Parent(s): a362e35

Upload processor

Browse files
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<image>": 32000
3
+ }
preprocessor_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_taivisionlm.TaiVisionProcessor"
4
+ },
5
+ "do_convert_rgb": null,
6
+ "do_normalize": true,
7
+ "do_rescale": true,
8
+ "do_resize": true,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_processor_type": "SiglipImageProcessor",
15
+ "image_seq_length": 196,
16
+ "image_std": [
17
+ 0.5,
18
+ 0.5,
19
+ 0.5
20
+ ],
21
+ "processor_class": "TaiVisionProcessor",
22
+ "resample": 3,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "height": 224,
26
+ "width": 224
27
+ }
28
+ }
processing_taivisionlm.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Processor class for TraVisionLM.
3
+ """
4
+ import transformers
5
+ import logging
6
+ from typing import List, Optional, Union
7
+
8
+ from transformers.feature_extraction_utils import BatchFeature
9
+ from transformers.image_utils import ImageInput, is_valid_image
10
+ from transformers.processing_utils import ProcessorMixin
11
+ from transformers.tokenization_utils import (
12
+ AddedToken,
13
+ PaddingStrategy,
14
+ PreTokenizedInput,
15
+ TextInput,
16
+ TruncationStrategy,
17
+ )
18
+ from transformers.utils import TensorType
19
+ from .configuration_taivisionlm import TaiVisionLMConfig
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ IMAGE_TOKEN = "<image>"
24
+
25
+ # Copied from transformers.models.idefics2.processing_idefics2.is_url
26
+ def is_url(val) -> bool:
27
+ return isinstance(val, str) and val.startswith("http")
28
+
29
+
30
+ # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
31
+ def is_image_or_image_url(elem):
32
+ return is_url(elem) or is_valid_image(elem)
33
+
34
+ # Copied from transformers.models.paligemma.processing_paligemma._is_str_or_image
35
+ def _is_str_or_image(elem):
36
+ return isinstance(elem, (str)) or is_image_or_image_url(elem)
37
+
38
+
39
+ def build_string_from_input(image_seq_len, image_token):
40
+ """
41
+ Builds a string from the input prompt and image tokens.
42
+ For example, for the call:
43
+ build_string_from_input(
44
+ image_seq_len=3,
45
+ image_token="<im>",
46
+ )
47
+ The output will be:
48
+ "<im><im><im>"
49
+ Args:
50
+ image_seq_len (`int`): The length of the image sequence.
51
+ image_token (`str`): The image token.
52
+ """
53
+ return f"{image_token * image_seq_len}"
54
+
55
+
56
+ class TaiVisionProcessor(ProcessorMixin):
57
+ r"""
58
+ Constructs a TraVision processor which wraps a SigLIP image processor and a GPT2 tokenizer into a single processor.
59
+
60
+ [`TaiVisionProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`LlamaTokenizerFast`]. See the
61
+ [`~TaiVisionProcessor.__call__`] and [`~TaiVisionProcessor.decode`] for more information.
62
+
63
+ Args:
64
+ image_processor ([`SiglipImageProcessor`], *optional*):
65
+ The image processor is a required input.
66
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
67
+ The tokenizer is a required input.
68
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
69
+ in a chat into a tokenizable string.
70
+ """
71
+
72
+ attributes = ["image_processor", "tokenizer"]
73
+ valid_kwargs = ["chat_template"]
74
+ image_processor_class = "SiglipImageProcessor"
75
+ tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
76
+
77
+ def __init__(
78
+ self,
79
+ image_processor=None,
80
+ tokenizer=None,
81
+ chat_template=None,
82
+ **kwargs,
83
+ ):
84
+ if image_processor is None:
85
+ raise ValueError("You need to specify an `image_processor`.")
86
+ if tokenizer is None:
87
+ raise ValueError("You need to specify a `tokenizer`.")
88
+ if not hasattr(image_processor, "image_seq_length"):
89
+ raise ValueError("Image processor is missing an `image_seq_length` attribute.")
90
+
91
+ self.image_seq_length = image_processor.image_seq_length
92
+
93
+ image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
94
+ tokens_to_add = {"additional_special_tokens": [image_token]}
95
+ tokenizer.add_special_tokens(tokens_to_add)
96
+ self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
97
+ tokenizer.add_bos_token = False
98
+ tokenizer.add_eos_token = False
99
+
100
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
101
+
102
+ def __call__(
103
+ self,
104
+ prompts: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
105
+ images: ImageInput = None,
106
+ padding: Union[bool, str, PaddingStrategy] = False,
107
+ truncation: Union[bool, str, TruncationStrategy] = None,
108
+ max_length=None,
109
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
110
+ do_resize: bool = None,
111
+ do_normalize: bool = None,
112
+ image_mean: Optional[Union[float, List[float]]] = None,
113
+ image_std: Optional[Union[float, List[float]]] = None,
114
+ data_format: Optional["ChannelDimension"] = "channels_first", # noqa: F821
115
+ input_data_format: Optional[
116
+ Union[str, "ChannelDimension"] # noqa: F821
117
+ ] = None,
118
+ resample: "PILImageResampling" = None, # noqa: F821
119
+ do_convert_rgb: bool = None,
120
+ do_thumbnail: bool = None,
121
+ do_align_long_axis: bool = None,
122
+ do_rescale: bool = None,
123
+ labels: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
124
+ ) -> BatchFeature:
125
+ """
126
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
127
+ and `kwargs` arguments to GPT2TokenizerFast's [`~GPT2TokenizerFast.__call__`] if `text` is not `None` to encode
128
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
129
+ SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
130
+ of the above two methods for more information.
131
+
132
+ The usage for TraVisionLM fine-tuning preparation follows a standard 4D causal mask where only the prompt and label tokens
133
+ are attended in an auto-regressive manner. The label in `text` are to be passed separately to the __call__ function and
134
+ will be placed after the prompt, which is the instruction to steer the model generation.
135
+
136
+ Args:
137
+ prompts (`str`, `List[str]`, `List[List[str]]`):
138
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
139
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
140
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
141
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
142
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
143
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
144
+ number of channels, H and W are \image height and width.
145
+ tokenize_newline_separately (`bool`, defaults to `False`):
146
+ Adds a separately tokenized '\n' at the end of the prompt.
147
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
148
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
149
+ index) among:
150
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
151
+ sequence if provided).
152
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
153
+ acceptable input length for the model if that argument is not provided.
154
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
155
+ lengths).
156
+ max_length (`int`, *optional*):
157
+ Maximum length of the returned list and optionally padding length (see above).
158
+ truncation (`bool`, *optional*):
159
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
160
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
161
+ If set, will return tensors of a particular framework. Acceptable values are:
162
+
163
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
164
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
165
+ - `'np'`: Return NumPy `np.ndarray` objects.
166
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
167
+ labels (`str`, `List[str]`, `List[List[str]]`):
168
+ The label or batch of labels to be encoded. Only necessary for training.
169
+ text (`str`, `List[str]`, `List[List[str]]`):
170
+ The text or batch of text to be encoded. If provided, the prompt and label should be
171
+
172
+ Returns:
173
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
174
+
175
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `label`
176
+ is provided, the `input_ids` will also contain the label input ids.
177
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
178
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
179
+ `None`).
180
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
181
+ - **labels** -- Labels compatible with training if `label` is not None
182
+ """
183
+
184
+ # return_token_type_ids = True if labels is not None else False
185
+ return_token_type_ids = True
186
+
187
+ if images is None:
188
+ raise ValueError("`images` are expected as arguments to a `TraVisionProcessor` instance.")
189
+
190
+ images = [images] if not isinstance(images, list) else images
191
+
192
+ if prompts is None:
193
+ logger.warning_once(
194
+ "You are using TaiVisionLM without a text prefix. It will perform as a picture-captioning model."
195
+ )
196
+ prompts = "描述這張圖片" # default prompt if it is not provided as an argument
197
+ if len(images) != 1:
198
+ prompts = [prompts] * len(images)
199
+
200
+ if isinstance(prompts, List) and isinstance(images, List):
201
+ if len(images) < len(text):
202
+ raise ValueError(
203
+ f"Received {len(images)} images for {len(prompts)} prompts. Each prompt should be associated with an image."
204
+ )
205
+ if _is_str_or_image(prompts):
206
+ prompts = [prompts]
207
+ elif isinstance(prompts, list) and _is_str_or_image(prompts[0]):
208
+ pass
209
+
210
+ # add \n after image tokens
211
+ prompts = [f"\n<|user|>\n{prompt}{self.tokenizer.eos_token}\n" for prompt in prompts]
212
+ # TODO: tokenize the prompt twice, and check if the prompt is too long
213
+ prompt_length = [len(self.tokenizer.tokenize(prompt)) + self.image_seq_length for prompt in prompts]
214
+
215
+
216
+ if labels is not None:
217
+ if _is_str_or_image(labels):
218
+ labels = [labels] # convert it to list if it is a string
219
+ labels = [f"<|assistant|>\n{label}{self.tokenizer.eos_token}" for label in labels]
220
+
221
+ text = [f"{prompt}{label}" for prompt, label in zip(prompts, labels)]
222
+
223
+ else:
224
+ text = prompts
225
+
226
+ assert len(images) == len(text), "The number of images and text should be the same."
227
+
228
+ input_strings = [
229
+ build_string_from_input(
230
+ image_seq_len=self.image_seq_length,
231
+ image_token=IMAGE_TOKEN,
232
+ )
233
+ for _ in text
234
+ ]
235
+
236
+ # this will do some image processing, like resizing, normalizing, etc.
237
+ pixel_values = self.image_processor(
238
+ images,
239
+ do_resize=do_resize,
240
+ do_normalize=do_normalize,
241
+ return_tensors=return_tensors,
242
+ image_mean=image_mean,
243
+ image_std=image_std,
244
+ input_data_format=input_data_format,
245
+ data_format=data_format,
246
+ resample=resample,
247
+ do_convert_rgb=do_convert_rgb,
248
+ )["pixel_values"]
249
+
250
+ if max_length is not None:
251
+ max_length += self.image_seq_length # max_length has to account for the image tokens
252
+
253
+ inputs = self.tokenizer(
254
+ input_strings,
255
+ text_pair=text,
256
+ return_tensors=return_tensors,
257
+ padding=padding,
258
+ max_length=max_length,
259
+ truncation=truncation,
260
+ return_token_type_ids=return_token_type_ids,
261
+ )
262
+
263
+ return_data = {**inputs, "pixel_values": pixel_values}
264
+
265
+ # we are doing training, so we need to return the labels
266
+ if labels is not None:
267
+ # fill the labels with -100 where we don't have to compute the loss
268
+ # mask the padding part
269
+ labels = inputs["input_ids"].masked_fill(inputs["attention_mask"] == 0, -100)
270
+ # mask the image + prompt part, so that we don't train the model to predict the image tokens
271
+ import torch
272
+ prompt_length_tensor = torch.tensor(prompt_length)
273
+ labels = labels.masked_fill(torch.arange(labels.size(1)).unsqueeze(0) < prompt_length_tensor.unsqueeze(1), -100)
274
+ return_data.update({"labels": labels})
275
+
276
+ return BatchFeature(data=return_data)
277
+
278
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->GPT2
279
+ def batch_decode(self, *args, **kwargs):
280
+ """
281
+ This method forwards all its arguments to GPT2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
282
+ refer to the docstring of this method for more information.
283
+ """
284
+ return self.tokenizer.batch_decode(*args, **kwargs)
285
+
286
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->GPT2
287
+ def decode(self, *args, **kwargs):
288
+ """
289
+ This method forwards all its arguments to GPT2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
290
+ the docstring of this method for more information.
291
+ """
292
+ return self.tokenizer.decode(*args, **kwargs)
293
+
294
+ @property
295
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names with CLIP->TraVision
296
+ def model_input_names(self):
297
+ tokenizer_input_names = self.tokenizer.model_input_names
298
+ image_processor_input_names = self.image_processor.model_input_names
299
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
300
+
301
+
302
+ # if __name__ == '__main__':
303
+ # config = TaiVisionLMConfig.from_pretrained("./")
304
+ # preprocessor = transformers.SiglipImageProcessor.from_pretrained("google/siglip-base-patch16-224")
305
+ # preprocessor.image_seq_length = config.num_image_tokens
306
+ # tokenizer = transformers.AutoTokenizer.from_pretrained("benchang1110/Taiwan-tinyllama-v1.0-chat")
307
+ # processor = TaiVisionProcessor(tokenizer=tokenizer, image_processor=preprocessor)
308
+ # processor.save_pretrained("./")
309
+
310
+ # from PIL import Image
311
+ # import requests
312
+ # processor = TaiVisionProcessor.from_pretrained("./")
313
+ # url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"
314
+ # image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
315
+ # prompt = "Hello< what is your name?"
316
+ # label = "I am fine, thank you."
317
+ # inputs = processor(prompts=prompt, labels=label,images=image, return_tensors="pt",padding="max_length",max_length=512)
318
+ # for key, value in inputs.items():
319
+ # print(f"{key}: {value}")
320
+ # print(processor.decode(inputs.input_ids.tolist()[0]))
processor_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_taivisionlm.TaiVisionProcessor"
4
+ },
5
+ "chat_template": null,
6
+ "processor_class": "TaiVisionProcessor"
7
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<image>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ }
10
+ ],
11
+ "bos_token": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "eos_token": {
19
+ "content": "</s>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ },
25
+ "pad_token": {
26
+ "content": "<unk>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ "unk_token": {
33
+ "content": "<unk>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ }
39
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "32000": {
31
+ "content": "<image>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ }
38
+ },
39
+ "additional_special_tokens": [
40
+ "<image>"
41
+ ],
42
+ "auto_map": {
43
+ "AutoProcessor": "processing_taivisionlm.TaiVisionProcessor"
44
+ },
45
+ "bos_token": "<s>",
46
+ "chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
47
+ "clean_up_tokenization_spaces": false,
48
+ "eos_token": "</s>",
49
+ "legacy": false,
50
+ "model_max_length": 2048,
51
+ "pad_token": "<unk>",
52
+ "padding_side": "right",
53
+ "processor_class": "TaiVisionProcessor",
54
+ "sp_model_kwargs": {},
55
+ "spaces_between_special_tokens": false,
56
+ "tokenizer_class": "LlamaTokenizer",
57
+ "unk_token": "<unk>",
58
+ "use_default_system_prompt": false
59
+ }