kirp commited on
Commit
bef6ac6
1 Parent(s): 69d7e70

Use Official Transformers (#1)

Browse files

- include modeling files in repo (8241db4f3c6c84eae0a3083473a91135f2401f69)
- include automap in config.json (0c2389f06d7159973efd6f8b8dbc214ef10cf719)
- use real transformers lib and have changes locally (42896b390130ca774884ddb4fadf0a6dcb613199)
- config jsons missing (7f5c1613bb14d2ad35786291e5d99adaa814527f)
- updated readme (c3bc1837336b3013f851476a946551c054bc3122)

__init__.py ADDED
File without changes
config.json CHANGED
@@ -2,6 +2,13 @@
2
  "architectures": [
3
  "Kosmos2_5ForConditionalGeneration"
4
  ],
 
 
 
 
 
 
 
5
  "latent_query_num": 2048,
6
  "model_type": "kosmos-2.5",
7
  "text_config": {
 
2
  "architectures": [
3
  "Kosmos2_5ForConditionalGeneration"
4
  ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_kosmos2_5.Kosmos2_5Config",
7
+ "AutoProcessor": "processing_kosmos2_5.Kosmos2_5Processor",
8
+ "AutoImageProcessor": "image_processing_kosmos2_5.Kosmos2_5ImageProcessor",
9
+ "AutoModel": "modeling_kosmos2_5.Kosmos2_5Model",
10
+ "AutoModelForVision2Seq": "modeling_kosmos2_5.Kosmos2_5ForConditionalGeneration"
11
+ },
12
  "latent_query_num": 2048,
13
  "model_type": "kosmos-2.5",
14
  "text_config": {
configuration_kosmos2_5.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft Research 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 at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # 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 and
14
+ # limitations under the License.
15
+ """KOSMOS-2.5.5 model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class Kosmos2_5TextConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`Kosmos2_5TextModel`]. It is used to instantiate a
30
+ KOSMOS-2.5 text decoder according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the text decoder of the KOSMOS-2.5
32
+ [microsoft/KOSMOS-2.5](https://huggingface.co/microsoft/KOSMOS-2.5) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 108481):
39
+ Vocabulary size of the Kosmos2_5 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`Kosmos2_5Model`].
41
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
42
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
43
+ just in case (e.g., 512 or 1024 or 2048).
44
+ embed_dim (`int`, *optional*, defaults to 2048):
45
+ Dimensionality of the layers and the pooler layer.
46
+ layers (`int`, *optional*, defaults to 24):
47
+ Number of hidden layers in the Transformer encoder.
48
+ ffn_dim (`int`, *optional*, defaults to 8192):
49
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
50
+ attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ dropout (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_dropout (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ activation_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for activations inside the fully connected layer.
61
+ layerdrop (`float`, *optional*, defaults to 0.0):
62
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
63
+ for more details.
64
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
65
+ The epsilon used by the layer normalization layers.
66
+ init_std (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ scale_embedding (`bool`, *optional*, defaults to `True`):
69
+ Scale embeddings by diving by sqrt(embed_dim).
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models).
72
+ ```"""
73
+
74
+ model_type = "kosmos_2_5_text_model"
75
+ keys_to_ignore_at_inference = ["past_key_values"]
76
+ attribute_map = {
77
+ "num_attention_heads": "attention_heads",
78
+ "hidden_size": "embed_dim",
79
+ "num_hidden_layers": "layers",
80
+ }
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_size=108481,
85
+ max_position_embeddings=4096,
86
+ embed_dim=1536,
87
+ layers=24,
88
+ ffn_dim=6144,
89
+ attention_heads=16,
90
+ activation_function="gelu",
91
+ dropout=0.1,
92
+ attention_dropout=0,
93
+ activation_dropout=0.0,
94
+ layerdrop=0.0,
95
+ layer_norm_eps=1e-5,
96
+ init_std=0.02,
97
+ scale_embedding=True,
98
+ use_cache=True,
99
+ pad_token_id=1,
100
+ bos_token_id=0,
101
+ eos_token_id=2,
102
+ **kwargs,
103
+ ):
104
+ super().__init__(
105
+ pad_token_id=pad_token_id,
106
+ bos_token_id=bos_token_id,
107
+ eos_token_id=eos_token_id,
108
+ **kwargs,
109
+ )
110
+
111
+ self.vocab_size = vocab_size
112
+ self.max_position_embeddings = max_position_embeddings
113
+ self.embed_dim = embed_dim
114
+ self.layers = layers
115
+ self.ffn_dim = ffn_dim
116
+ self.attention_heads = attention_heads
117
+ self.activation_function = activation_function
118
+ self.dropout = dropout
119
+ self.attention_dropout = attention_dropout
120
+ self.activation_dropout = activation_dropout
121
+ self.layerdrop = layerdrop
122
+ self.layer_norm_eps = layer_norm_eps
123
+ self.init_std = init_std
124
+ self.scale_embedding = scale_embedding
125
+ self.use_cache = use_cache
126
+
127
+ @classmethod
128
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
129
+ cls._set_token_in_kwargs(kwargs)
130
+
131
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
132
+
133
+ # get the text config dict if we are loading from Kosmos2_5Config
134
+ if config_dict.get("model_type") == "kosmos-2.5":
135
+ config_dict = config_dict["text_config"]
136
+
137
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
138
+ logger.warning(
139
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
140
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
141
+ )
142
+
143
+ return cls.from_dict(config_dict, **kwargs)
144
+
145
+
146
+ class Kosmos2_5VisionConfig(PretrainedConfig):
147
+ r"""
148
+ This is the configuration class to store the configuration of a [`Kosmos2_5VisionModel`]. It is used to
149
+ instantiate a Kosmos2_5 vision model according to the specified arguments, defining the model architecture.
150
+ Instantiating a configuration defaults will yield a similar configuration to that of the kosmos-2.5
151
+ [microsoft/kosmos-2.5](https://huggingface.co/microsoft/kosmos-2.5) architecture.
152
+
153
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
154
+ documentation from [`PretrainedConfig`] for more information.
155
+
156
+ Args:
157
+ hidden_size (`int`, *optional*, defaults to 768):
158
+ Dimensionality of the encoder layers and the pooler layer.
159
+ patch_embed_hidden_size (`int`, *optional*, defaults to 768):
160
+ Dimensionality of the input patch_embedding layer in the Transformer encoder.
161
+ d_ff (`int`, *optional*, defaults to 2048):
162
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
163
+ d_kv (`int`, *optional*, defaults to 64):
164
+ Dimensionality of the key, query, value projections per attention head.
165
+ num_hidden_layers (`int`, *optional*, defaults to 12):
166
+ Number of hidden layers in the Transformer encoder.
167
+ num_attention_heads (`int`, *optional*, defaults to 12):
168
+ Number of attention heads for each attention layer in the Transformer encoder.
169
+ dense_act_fn (`str` or `function`, *optional*, defaults to `"gelu_new"`):
170
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
171
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
172
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
173
+ The epsilon used by the layer normalization layers.
174
+ dropout_rate (`float`, *optional*, defaults to 0.0):
175
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
176
+ attention_dropout (`float`, *optional*, defaults to 0.0):
177
+ The dropout ratio for the attention probabilities.
178
+ initializer_range (`float`, *optional*, defaults to 1e-10):
179
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
180
+ initializer_factor (`float`, *optional*, defaults to 1.0):
181
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
182
+ testing).
183
+ seq_len (`int`, *optional*, defaults to 4096):
184
+ Maximum sequence length (here number of patches) supported by the model.
185
+ Example:
186
+
187
+ ```python
188
+ >>> from transformers import Kosmos2_5VisionConfig, Kosmos2_5VisionModel
189
+
190
+ >>> # Initializing a Kosmos2_5VisionConfig with microsoft/kosmos-2.5 style configuration
191
+ >>> configuration = Kosmos2_5VisionConfig()
192
+
193
+ >>> # Initializing a Kosmos2_5VisionModel (with random weights) from the microsoft/kosmos-2.5 style configuration
194
+ >>> model = Kosmos2_5VisionModel(configuration)
195
+
196
+ >>> # Accessing the model configuration
197
+ >>> configuration = model.config
198
+ ```"""
199
+
200
+ model_type = "kosmos_2_5_vision_model"
201
+
202
+ def __init__(
203
+ self,
204
+ hidden_size=1536,
205
+ patch_embed_hidden_size=768,
206
+ d_ff=3968,
207
+ d_kv=64,
208
+ num_hidden_layers=18,
209
+ num_attention_heads=24,
210
+ dense_act_fn="gelu_new",
211
+ layer_norm_eps=1e-6,
212
+ dropout_rate=0.0,
213
+ attention_dropout=0.0,
214
+ initializer_range=1e-10,
215
+ initializer_factor=1.0,
216
+ seq_len=4096,
217
+ **kwargs,
218
+ ):
219
+ super().__init__(**kwargs)
220
+
221
+ self.hidden_size = hidden_size
222
+ self.patch_embed_hidden_size = patch_embed_hidden_size
223
+ self.d_ff = d_ff
224
+ self.dropout_rate = dropout_rate
225
+ self.num_hidden_layers = num_hidden_layers
226
+ self.num_attention_heads = num_attention_heads
227
+ self.initializer_range = initializer_range
228
+ self.initializer_factor = initializer_factor
229
+ self.attention_dropout = attention_dropout
230
+ self.layer_norm_eps = layer_norm_eps
231
+ self.dense_act_fn = dense_act_fn
232
+ self.seq_len = seq_len
233
+ self.d_kv = d_kv
234
+
235
+ @classmethod
236
+ def from_pretrained(
237
+ cls, pretrainehidden_size_name_or_path: Union[str, os.PathLike], **kwargs
238
+ ) -> "PretrainedConfig":
239
+ cls._set_token_in_kwargs(kwargs)
240
+
241
+ config_dict, kwargs = cls.get_config_dict(pretrainehidden_size_name_or_path, **kwargs)
242
+
243
+ # get the vision config dict if we are loading from Kosmos2_5Config
244
+ if config_dict.get("model_type") == "Kosmos2_5":
245
+ config_dict = config_dict["vision_config"]
246
+
247
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
248
+ logger.warning(
249
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
250
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
251
+ )
252
+
253
+ return cls.from_dict(config_dict, **kwargs)
254
+
255
+
256
+ class Kosmos2_5Config(PretrainedConfig):
257
+ r"""
258
+ This is the configuration class to store the configuration of a [`Kosmos2_5Model`]. It is used to instantiate a
259
+ KOSMOS-2.5 model according to the specified arguments, defining the model architecture. Instantiating a configuration
260
+ with the defaults will yield a similar configuration to that of the KOSMOS-2.5
261
+ [microsoft/KOSMOS-2.5-patch14-224](https://huggingface.co/microsoft/KOSMOS-2.5-patch14-224) architecture.
262
+
263
+ Args:
264
+ text_config (`dict`, *optional*):
265
+ Dictionary of configuration options used to initialize [`Kosmos2_5TextConfig`].
266
+ vision_config (`dict`, *optional*):
267
+ Dictionary of configuration options used to initialize [`Kosmos2_5VisionConfig`].
268
+ latent_query_num (`int`, *optional*, defaults to 2048):
269
+ The number of latent query tokens that represent the image features used in the text decoder component.
270
+ kwargs (*optional*):
271
+ Dictionary of keyword arguments.
272
+
273
+ Example:
274
+
275
+ ```python
276
+ >>> from .. import Kosmos2_5Config, Kosmos2_5Model
277
+
278
+ >>> # Initializing a KOSMOS-2.5 KOSMOS-2.5-patch14-224 style configuration
279
+ >>> configuration = Kosmos2_5Config()
280
+
281
+ >>> # Initializing a model (with random weights) from the KOSMOS-2.5-patch14-224 style configuration
282
+ >>> model = Kosmos2_5Model(configuration)
283
+
284
+ >>> # Accessing the model configuration
285
+ >>> configuration = model.config
286
+ ```"""
287
+
288
+ model_type = "kosmos-2.5"
289
+ is_composition = True
290
+
291
+ def __init__(
292
+ self,
293
+ text_config=None,
294
+ vision_config=None,
295
+ latent_query_num=2048,
296
+ **kwargs,
297
+ ):
298
+ super().__init__(**kwargs)
299
+ if text_config is None:
300
+ text_config = {}
301
+ logger.info("text_config is None. Initializing the Kosmos2_5TextConfig with default values.")
302
+ if vision_config is None:
303
+ vision_config = {}
304
+ logger.info("vision_config is None. Initializing the Kosmos2_5VisionConfig with default values.")
305
+
306
+ self.text_config = Kosmos2_5TextConfig(**text_config)
307
+ self.vision_config = Kosmos2_5VisionConfig(**vision_config)
308
+
309
+ self.latent_query_num = latent_query_num
310
+
311
+ @classmethod
312
+ def from_text_vision_configs(
313
+ cls,
314
+ text_config: Kosmos2_5TextConfig,
315
+ vision_config: Kosmos2_5VisionConfig,
316
+ **kwargs,
317
+ ):
318
+ r"""
319
+ Instantiate a [`Pix2StructConfig`] (or a derived class) from pix2struct text model configuration and pix2struct
320
+ vision model configuration.
321
+
322
+ Returns:
323
+ [`Pix2StructConfig`]: An instance of a configuration object
324
+ """
325
+
326
+ return cls(
327
+ text_config=text_config.to_dict(),
328
+ vision_config=vision_config.to_dict(),
329
+ **kwargs,
330
+ )
image_processing_kosmos2_5.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # 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 and
14
+ # limitations under the License.
15
+ """Image processor class for Kosmos2_5."""
16
+
17
+ import math
18
+ from typing import Dict, Optional, Union
19
+ from transformers import AutoImageProcessor
20
+ import numpy as np
21
+
22
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
23
+ from transformers.image_transforms import (
24
+ convert_to_rgb,
25
+ normalize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from transformers.image_utils import (
29
+ ChannelDimension,
30
+ ImageInput,
31
+ get_image_size,
32
+ infer_channel_dimension_format,
33
+ make_list_of_images,
34
+ to_numpy_array,
35
+ valid_images,
36
+ )
37
+ from transformers.utils import TensorType, is_torch_available, logging
38
+ from transformers.utils.import_utils import requires_backends
39
+
40
+
41
+ if is_torch_available():
42
+ import torch
43
+
44
+ logger = logging.get_logger(__name__)
45
+ DEFAULT_FONT_PATH = "ybelkada/fonts"
46
+
47
+
48
+ # adapted from: https://discuss.pytorch.org/t/tf-image-extract-patches-in-pytorch/171409/2
49
+ def torch_extract_patches(image_tensor, patch_height, patch_width):
50
+ """
51
+ Utiliy function to extract patches from a given image tensor. Returns a tensor of shape (1, `patch_height`,
52
+ `patch_width`, `num_channels`x `patch_height` x `patch_width`)
53
+
54
+ Args:
55
+ image_tensor (torch.Tensor):
56
+ The image tensor to extract patches from.
57
+ patch_height (int):
58
+ The height of the patches to extract.
59
+ patch_width (int):
60
+ The width of the patches to extract.
61
+ """
62
+ requires_backends(torch_extract_patches, ["torch"])
63
+
64
+ image_tensor = image_tensor.unsqueeze(0)
65
+ patches = torch.nn.functional.unfold(image_tensor, (patch_height, patch_width), stride=(patch_height, patch_width))
66
+ patches = patches.reshape(image_tensor.size(0), image_tensor.size(1), patch_height, patch_width, -1)
67
+ patches = patches.permute(0, 4, 2, 3, 1).reshape(
68
+ image_tensor.size(2) // patch_height,
69
+ image_tensor.size(3) // patch_width,
70
+ image_tensor.size(1) * patch_height * patch_width,
71
+ )
72
+ return patches.unsqueeze(0)
73
+
74
+
75
+ class Kosmos2_5ImageProcessor(BaseImageProcessor):
76
+ r"""
77
+ Constructs a Kosmos2_5 image processor.
78
+
79
+ Args:
80
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
81
+ Whether to convert the image to RGB.
82
+ do_normalize (`bool`, *optional*, defaults to `True`):
83
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
84
+ method. According to Kosmos2_5 paper and code, the image is normalized with its own mean and standard
85
+ deviation.
86
+ patch_size (`Dict[str, int]`, *optional*, defaults to `{"height": 16, "width": 16}`):
87
+ The patch size to use for the image. According to Kosmos2_5 paper and code, the patch size is 16x16.
88
+ max_patches (`int`, *optional*, defaults to 4096):
89
+ The maximum number of patches to extract from the image as per the [Kosmos2_5
90
+ paper](https://arxiv.org/pdf/2309.11419).
91
+ """
92
+
93
+ model_input_names = ["flattened_patches"]
94
+
95
+ def __init__(
96
+ self,
97
+ do_convert_rgb: bool = True,
98
+ do_normalize: bool = True,
99
+ patch_size: Dict[str, int] = None,
100
+ max_patches: int = 4096,
101
+ **kwargs,
102
+ ) -> None:
103
+ super().__init__(**kwargs)
104
+ self.patch_size = patch_size if patch_size is not None else {"height": 16, "width": 16}
105
+ self.do_normalize = do_normalize
106
+ self.do_convert_rgb = do_convert_rgb
107
+ self.max_patches = max_patches
108
+
109
+ def extract_flattened_patches(
110
+ self,
111
+ image: np.ndarray,
112
+ max_patches: int,
113
+ patch_size: dict,
114
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
115
+ **kwargs,
116
+ ) -> np.ndarray:
117
+ """
118
+ Extract flattened patches from an image.
119
+
120
+ Args:
121
+ image (`np.ndarray`):
122
+ Image to extract flattened patches from.
123
+ max_patches (`int`):
124
+ Maximum number of patches to extract.
125
+ patch_size (`dict`):
126
+ Dictionary containing the patch height and width.
127
+
128
+ Returns:
129
+ result (`np.ndarray`):
130
+ A sequence of `max_patches` flattened patches.
131
+ """
132
+ requires_backends(self.extract_flattened_patches, "torch")
133
+
134
+ # convert to torch
135
+ image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format)
136
+ image = torch.from_numpy(image)
137
+
138
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
139
+ image_height, image_width = get_image_size(image, ChannelDimension.FIRST)
140
+
141
+ # maximize scale s.t.
142
+ scale = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width))
143
+ num_feasible_rows = max(min(math.floor(scale * image_height / patch_height), max_patches), 1)
144
+ num_feasible_cols = max(min(math.floor(scale * image_width / patch_width), max_patches), 1)
145
+ resized_height = max(num_feasible_rows * patch_height, 1)
146
+ resized_width = max(num_feasible_cols * patch_width, 1)
147
+
148
+ image = torch.nn.functional.interpolate(
149
+ image.unsqueeze(0),
150
+ size=(resized_height, resized_width),
151
+ mode="bilinear",
152
+ align_corners=False,
153
+ antialias=True,
154
+ ).squeeze(0)
155
+
156
+ # [1, rows, columns, patch_height * patch_width * image_channels]
157
+ patches = torch_extract_patches(image, patch_height, patch_width)
158
+
159
+ patches_shape = patches.shape
160
+ rows = patches_shape[1]
161
+ columns = patches_shape[2]
162
+ depth = patches_shape[3]
163
+
164
+ # [rows * columns, patch_height * patch_width * image_channels]
165
+ patches = patches.reshape([rows * columns, depth])
166
+
167
+ # [rows * columns, 1]
168
+ row_ids = torch.arange(rows).reshape([rows, 1]).repeat(1, columns).reshape([rows * columns, 1])
169
+ col_ids = torch.arange(columns).reshape([1, columns]).repeat(rows, 1).reshape([rows * columns, 1])
170
+
171
+ # Offset by 1 so the ids do not contain zeros, which represent padding.
172
+ row_ids += 1
173
+ col_ids += 1
174
+
175
+ # Prepare additional patch features.
176
+ # [rows * columns, 1]
177
+ row_ids = row_ids.to(torch.float32)
178
+ col_ids = col_ids.to(torch.float32)
179
+
180
+ # [rows * columns, 2 + patch_height * patch_width * image_channels]
181
+ result = torch.cat([row_ids, col_ids, patches], -1)
182
+
183
+ # [max_patches, 2 + patch_height * patch_width * image_channels]
184
+ result = torch.nn.functional.pad(result, [0, 0, 0, max_patches - (rows * columns)]).float()
185
+
186
+ result = to_numpy_array(result)
187
+
188
+ return result, resized_width, resized_height, rows, columns
189
+
190
+ def normalize(
191
+ self,
192
+ image: np.ndarray,
193
+ data_format: Optional[Union[str, ChannelDimension]] = None,
194
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
195
+ **kwargs,
196
+ ) -> np.ndarray:
197
+ """
198
+ Normalize an image. image = (image - image_mean) / image_std.
199
+
200
+ The image std is to mimic the tensorflow implementation of the `per_image_standardization`:
201
+ https://www.tensorflow.org/api_docs/python/tf/image/per_image_standardization
202
+
203
+ Args:
204
+ image (`np.ndarray`):
205
+ Image to normalize.
206
+ data_format (`str` or `ChannelDimension`, *optional*):
207
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
208
+ image is used.
209
+ input_data_format (`str` or `ChannelDimension`, *optional*):
210
+ The channel dimension format of the input image. If not provided, it will be inferred.
211
+ """
212
+ if image.dtype == np.uint8:
213
+ image = image.astype(np.float32)
214
+
215
+ # take mean across the whole `image`
216
+ mean = np.mean(image)
217
+ std = np.std(image)
218
+ adjusted_stddev = max(std, 1.0 / math.sqrt(np.prod(image.shape)))
219
+
220
+ return normalize(
221
+ image,
222
+ mean=mean,
223
+ std=adjusted_stddev,
224
+ data_format=data_format,
225
+ input_data_format=input_data_format,
226
+ **kwargs,
227
+ )
228
+
229
+ def preprocess(
230
+ self,
231
+ images: ImageInput,
232
+ do_convert_rgb: bool = None,
233
+ do_normalize: Optional[bool] = None,
234
+ max_patches: Optional[int] = None,
235
+ patch_size: Optional[Dict[str, int]] = None,
236
+ return_tensors: Optional[Union[str, TensorType]] = None,
237
+ data_format: ChannelDimension = ChannelDimension.FIRST,
238
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
239
+ **kwargs,
240
+ ) -> ImageInput:
241
+ """
242
+ Preprocess an image or batch of images. The processor first computes the maximum possible number of
243
+ aspect-ratio preserving patches of size `patch_size` that can be extracted from the image. It then pads the
244
+ image with zeros to make the image respect the constraint of `max_patches`. Before extracting the patches the
245
+ images are standardized following the tensorflow implementation of `per_image_standardization`
246
+ (https://www.tensorflow.org/api_docs/python/tf/image/per_image_standardization).
247
+
248
+
249
+ Args:
250
+ images (`ImageInput`):
251
+ Image to preprocess. Expects a single or batch of images.
252
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
253
+ Whether to convert the image to RGB.
254
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
255
+ Whether to normalize the image.
256
+ max_patches (`int`, *optional*, defaults to `self.max_patches`):
257
+ Maximum number of patches to extract.
258
+ patch_size (`dict`, *optional*, defaults to `self.patch_size`):
259
+ Dictionary containing the patch height and width.
260
+ return_tensors (`str` or `TensorType`, *optional*):
261
+ The type of tensors to return. Can be one of:
262
+ - Unset: Return a list of `np.ndarray`.
263
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
264
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
265
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
266
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
267
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
268
+ The channel dimension format for the output image. Can be one of:
269
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
270
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
271
+ - Unset: Use the channel dimension format of the input image.
272
+ input_data_format (`ChannelDimension` or `str`, *optional*):
273
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
274
+ from the input image. Can be one of:
275
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
276
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
277
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
278
+ """
279
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
280
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
281
+ patch_size = patch_size if patch_size is not None else self.patch_size
282
+ max_patches = max_patches if max_patches is not None else self.max_patches
283
+
284
+ if kwargs.get("data_format", None) is not None:
285
+ raise ValueError("data_format is not an accepted input as the outputs are ")
286
+
287
+ images = make_list_of_images(images)
288
+
289
+ if not valid_images(images):
290
+ raise ValueError(
291
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
292
+ "torch.Tensor, tf.Tensor or jax.ndarray."
293
+ )
294
+
295
+ # PIL RGBA images are converted to RGB
296
+ if do_convert_rgb:
297
+ images = [convert_to_rgb(image) for image in images]
298
+
299
+ # All transformations expect numpy arrays.
300
+ images = [to_numpy_array(image) for image in images]
301
+
302
+ if input_data_format is None:
303
+ # We assume that all images have the same channel dimension format.
304
+ input_data_format = infer_channel_dimension_format(images[0])
305
+
306
+ if do_normalize:
307
+ images = [self.normalize(image=image, input_data_format=input_data_format) for image in images]
308
+
309
+ # convert to torch tensor and permute
310
+ images = [
311
+ self.extract_flattened_patches(
312
+ image=image,
313
+ max_patches=max_patches,
314
+ patch_size=patch_size,
315
+ input_data_format=input_data_format,
316
+ )
317
+ for image in images
318
+ ]
319
+
320
+ width = [image[1] for image in images]
321
+ height = [image[2] for image in images]
322
+ rows = [image[3] for image in images]
323
+ cols = [image[4] for image in images]
324
+ images = [image[0] for image in images]
325
+
326
+ # create attention mask in numpy
327
+ attention_masks = [(image.sum(axis=-1) != 0).astype(np.float32) for image in images]
328
+
329
+ encoded_outputs = BatchFeature(
330
+ data={
331
+ "flattened_patches": images,
332
+ "attention_mask": attention_masks,
333
+ "width": width,
334
+ "height": height,
335
+ "rows": rows,
336
+ "cols": cols,
337
+ },
338
+ tensor_type=return_tensors,
339
+ )
340
+
341
+ return encoded_outputs
342
+
343
+ AutoImageProcessor.register("Kosmos2_5ImageProcessor", Kosmos2_5ImageProcessor)
modeling_kosmos2_5.py ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json CHANGED
@@ -1,5 +1,15 @@
1
  {
2
- "image_processor_type": "Kosmos2_5ImageProcessor",
3
- "processor_class": "Kosmos2_5Processor"
 
 
 
 
 
 
 
 
 
 
4
  }
5
-
 
1
  {
2
+ "do_convert_rgb": true,
3
+ "do_normalize": true,
4
+ "image_processor_type": "Kosmos2_5ImageProcessor",
5
+ "max_patches": 4096,
6
+ "patch_size": {
7
+ "height": 16,
8
+ "width": 16
9
+ },
10
+ "processor_class": "Kosmos2_5Processor",
11
+ "auto_map": {
12
+ "AutoProcessor": "processing_kosmos2_5.Kosmos2_5Processor",
13
+ "AutoImageProcessor": "image_processing_kosmos2_5.Kosmos2_5ImageProcessor"
14
  }
15
+ }
processing_kosmos2_5.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft Research 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 at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # 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 and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Kosmos2_5.
17
+ """
18
+
19
+ from typing import List, Optional, Union
20
+ import transformers
21
+ from transformers.image_processing_utils import BatchFeature
22
+ from transformers.processing_utils import ProcessorMixin
23
+ from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
24
+ from transformers.utils import TensorType, is_torch_available
25
+ from .image_processing_kosmos2_5 import Kosmos2_5ImageProcessor
26
+ transformers.Kosmos2_5ImageProcessor = Kosmos2_5ImageProcessor
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+
32
+ class Kosmos2_5Processor(ProcessorMixin):
33
+ r"""
34
+ Constructs a Kosmos2_5 processor which wraps a BERT tokenizer and Kosmos2_5 image processor into a single
35
+ processor.
36
+
37
+ [`Kosmos2_5Processor`] offers all the functionalities of [`Kosmos2_5ImageProcessor`] and [`T5TokenizerFast`]. See
38
+ the docstring of [`~Kosmos2_5Processor.__call__`] and [`~Kosmos2_5Processor.decode`] for more information.
39
+
40
+ Args:
41
+ image_processor (`Kosmos2_5ImageProcessor`):
42
+ An instance of [`Kosmos2_5ImageProcessor`]. The image processor is a required input.
43
+ tokenizer (Union[`T5TokenizerFast`, `T5Tokenizer`]):
44
+ An instance of ['T5TokenizerFast`] or ['T5Tokenizer`]. The tokenizer is a required input.
45
+ """
46
+
47
+ attributes = ["image_processor", "tokenizer"]
48
+ image_processor_class = "Kosmos2_5ImageProcessor"
49
+ tokenizer_class = "PreTrainedTokenizerFast"
50
+
51
+ def __init__(self, image_processor, tokenizer):
52
+ tokenizer.return_token_type_ids = False
53
+ self.image_processor = image_processor
54
+ self.tokenizer = tokenizer
55
+
56
+ def __call__(
57
+ self,
58
+ images=None,
59
+ text: Union[TextInput, List[TextInput]] = None,
60
+ add_special_tokens: bool = True,
61
+ padding: Union[bool, str, PaddingStrategy] = True,
62
+ truncation: Union[bool, str, TruncationStrategy] = True,
63
+ max_length: Optional[int] = None,
64
+ max_patches: Optional[int] = 4096,
65
+ stride: int = 0,
66
+ pad_to_multiple_of: Optional[int] = None,
67
+ return_attention_mask: Optional[bool] = None,
68
+ return_tensors: Optional[Union[str, TensorType]] = "pt",
69
+ **kwargs,
70
+ ) -> BatchFeature:
71
+ """
72
+ This method uses [`Kosmos2_5ImageProcessor.preprocess`] method to prepare image(s) for the model, and
73
+ [`PreTrainedTokenizerFast.__call__`] to prepare text for the model.
74
+
75
+ Please refer to the docstring of the above two methods for more information.
76
+
77
+ The rest of this documentation shows the arguments specific to `Kosmos2_5Processor`.
78
+ """
79
+ if images is None and text is None:
80
+ raise ValueError("You have to specify either images or text.")
81
+
82
+ encoding = BatchFeature()
83
+
84
+ if images is not None:
85
+ image_encoding = self.image_processor(
86
+ images, return_tensors=return_tensors, max_patches=max_patches, **kwargs
87
+ )
88
+ image_encoding.pop("rows")
89
+ image_encoding.pop("cols")
90
+ encoding.update(image_encoding)
91
+
92
+ if text is not None:
93
+ # use updates or pop
94
+ input = self.tokenizer(
95
+ text,
96
+ add_special_tokens=add_special_tokens,
97
+ padding=padding,
98
+ truncation=truncation,
99
+ max_length=max_length,
100
+ stride=stride,
101
+ pad_to_multiple_of=pad_to_multiple_of,
102
+ return_attention_mask=return_attention_mask,
103
+ return_tensors="pt",
104
+ )
105
+
106
+ batch_size, seq_len = input.input_ids.shape
107
+ additional_tokens = [0, 100283] + [0] * 2048 + [100284]
108
+ additional_tokens_tensor = torch.tensor(additional_tokens).unsqueeze(0).repeat(batch_size, 1)
109
+ input_ids = torch.cat([additional_tokens_tensor, input.input_ids], dim=1)
110
+
111
+ image_embeds_position_mask = [0, -1] + [1] * 2048 + [-1] + [0] * seq_len
112
+ image_embeds_position_mask = (
113
+ torch.LongTensor(image_embeds_position_mask).unsqueeze(0).repeat(batch_size, 1)
114
+ )
115
+
116
+ added_attention_mask = [1, 1] + [1] * 2048 + [1]
117
+ added_attention_mask_tensor = torch.tensor(added_attention_mask).unsqueeze(0).repeat(batch_size, 1)
118
+ attention_mask = torch.cat([added_attention_mask_tensor, input.attention_mask], dim=1)
119
+ encoding.update(
120
+ {
121
+ "input_ids": input_ids,
122
+ "attention_mask": attention_mask,
123
+ "image_embeds_position_mask": image_embeds_position_mask,
124
+ }
125
+ )
126
+
127
+ return encoding
128
+
129
+ def batch_decode(self, *args, **kwargs):
130
+ """
131
+ This method forwards all its arguments to Kosmos2_5TokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
132
+ Please refer to the docstring of this method for more information.
133
+ """
134
+ return self.tokenizer.batch_decode(*args, **kwargs)
135
+
136
+ def decode(self, *args, **kwargs):
137
+ """
138
+ This method forwards all its arguments to Kosmos2_5TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
139
+ refer to the docstring of this method for more information.
140
+ """
141
+ return self.tokenizer.decode(*args, **kwargs)
142
+
143
+ @property
144
+ def model_input_names(self):
145
+ tokenizer_input_names = self.tokenizer.model_input_names
146
+ image_processor_input_names = self.image_processor.model_input_names
147
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<pad>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json CHANGED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json CHANGED
The diff for this file is too large to render. See raw diff