Lukas Pfahler commited on
Commit
8241db4
1 Parent(s): 426fbbd

include modeling files in repo

Browse files
__init__.py ADDED
File without changes
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,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
modeling_kosmos2_5.py ADDED
The diff for this file is too large to render. See raw diff
 
processing_kosmos2_5.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+
31
+ class Kosmos2_5Processor(ProcessorMixin):
32
+ r"""
33
+ Constructs a Kosmos2_5 processor which wraps a BERT tokenizer and Kosmos2_5 image processor into a single
34
+ processor.
35
+
36
+ [`Kosmos2_5Processor`] offers all the functionalities of [`Kosmos2_5ImageProcessor`] and [`T5TokenizerFast`]. See
37
+ the docstring of [`~Kosmos2_5Processor.__call__`] and [`~Kosmos2_5Processor.decode`] for more information.
38
+
39
+ Args:
40
+ image_processor (`Kosmos2_5ImageProcessor`):
41
+ An instance of [`Kosmos2_5ImageProcessor`]. The image processor is a required input.
42
+ tokenizer (Union[`T5TokenizerFast`, `T5Tokenizer`]):
43
+ An instance of ['T5TokenizerFast`] or ['T5Tokenizer`]. The tokenizer is a required input.
44
+ """
45
+
46
+ attributes = ["image_processor", "tokenizer"]
47
+ image_processor_class = "Kosmos2_5ImageProcessor"
48
+ tokenizer_class = "PreTrainedTokenizerFast"
49
+
50
+ def __init__(self, image_processor, tokenizer):
51
+ tokenizer.return_token_type_ids = False
52
+ super().__init__(image_processor, tokenizer)
53
+
54
+ def __call__(
55
+ self,
56
+ images=None,
57
+ text: Union[TextInput, List[TextInput]] = None,
58
+ add_special_tokens: bool = True,
59
+ padding: Union[bool, str, PaddingStrategy] = True,
60
+ truncation: Union[bool, str, TruncationStrategy] = True,
61
+ max_length: Optional[int] = None,
62
+ max_patches: Optional[int] = 4096,
63
+ stride: int = 0,
64
+ pad_to_multiple_of: Optional[int] = None,
65
+ return_attention_mask: Optional[bool] = None,
66
+ return_tensors: Optional[Union[str, TensorType]] = "pt",
67
+ **kwargs,
68
+ ) -> BatchFeature:
69
+ """
70
+ This method uses [`Kosmos2_5ImageProcessor.preprocess`] method to prepare image(s) for the model, and
71
+ [`PreTrainedTokenizerFast.__call__`] to prepare text for the model.
72
+
73
+ Please refer to the docstring of the above two methods for more information.
74
+
75
+ The rest of this documentation shows the arguments specific to `Kosmos2_5Processor`.
76
+ """
77
+ if images is None and text is None:
78
+ raise ValueError("You have to specify either images or text.")
79
+
80
+ encoding = BatchFeature()
81
+
82
+ if images is not None:
83
+ image_encoding = self.image_processor(
84
+ images, return_tensors=return_tensors, max_patches=max_patches, **kwargs
85
+ )
86
+ image_encoding.pop("rows")
87
+ image_encoding.pop("cols")
88
+ encoding.update(image_encoding)
89
+
90
+ if text is not None:
91
+ # use updates or pop
92
+ input = self.tokenizer(
93
+ text,
94
+ add_special_tokens=add_special_tokens,
95
+ padding=padding,
96
+ truncation=truncation,
97
+ max_length=max_length,
98
+ stride=stride,
99
+ pad_to_multiple_of=pad_to_multiple_of,
100
+ return_attention_mask=return_attention_mask,
101
+ return_tensors="pt",
102
+ )
103
+
104
+ batch_size, seq_len = input.input_ids.shape
105
+ additional_tokens = [0, 100283] + [0] * 2048 + [100284]
106
+ additional_tokens_tensor = torch.tensor(additional_tokens).unsqueeze(0).repeat(batch_size, 1)
107
+ input_ids = torch.cat([additional_tokens_tensor, input.input_ids], dim=1)
108
+
109
+ image_embeds_position_mask = [0, -1] + [1] * 2048 + [-1] + [0] * seq_len
110
+ image_embeds_position_mask = (
111
+ torch.LongTensor(image_embeds_position_mask).unsqueeze(0).repeat(batch_size, 1)
112
+ )
113
+
114
+ added_attention_mask = [1, 1] + [1] * 2048 + [1]
115
+ added_attention_mask_tensor = torch.tensor(added_attention_mask).unsqueeze(0).repeat(batch_size, 1)
116
+ attention_mask = torch.cat([added_attention_mask_tensor, input.attention_mask], dim=1)
117
+ encoding.update(
118
+ {
119
+ "input_ids": input_ids,
120
+ "attention_mask": attention_mask,
121
+ "image_embeds_position_mask": image_embeds_position_mask,
122
+ }
123
+ )
124
+
125
+ return encoding
126
+
127
+ def batch_decode(self, *args, **kwargs):
128
+ """
129
+ This method forwards all its arguments to Kosmos2_5TokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
130
+ Please refer to the docstring of this method for more information.
131
+ """
132
+ return self.tokenizer.batch_decode(*args, **kwargs)
133
+
134
+ def decode(self, *args, **kwargs):
135
+ """
136
+ This method forwards all its arguments to Kosmos2_5TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
137
+ refer to the docstring of this method for more information.
138
+ """
139
+ return self.tokenizer.decode(*args, **kwargs)
140
+
141
+ @property
142
+ def model_input_names(self):
143
+ tokenizer_input_names = self.tokenizer.model_input_names
144
+ image_processor_input_names = self.image_processor.model_input_names
145
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))