Leyo commited on
Commit
8d33426
1 Parent(s): aa81487

make config similar to transformers except for flash

Browse files
Files changed (1) hide show
  1. configuration_siglip.py +26 -168
configuration_siglip.py CHANGED
@@ -1,5 +1,5 @@
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.
@@ -15,17 +15,10 @@
15
  """ Siglip model configuration"""
16
 
17
  import os
18
- from collections import OrderedDict
19
- from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
20
 
21
-
22
- if TYPE_CHECKING:
23
- from transformers.processing_utils import ProcessorMixin
24
- from transformers.utils import TensorType
25
-
26
- from transformers.configuration_utils import PretrainedConfig
27
- from transformers.onnx import OnnxConfig
28
- from transformers.utils import logging
29
 
30
 
31
  logger = logging.get_logger(__name__)
@@ -46,16 +39,16 @@ class SiglipTextConfig(PretrainedConfig):
46
  documentation from [`PretrainedConfig`] for more information.
47
 
48
  Args:
49
- vocab_size (`int`, *optional*, defaults to 49408):
50
  Vocabulary size of the Siglip text model. Defines the number of different tokens that can be represented by
51
  the `inputs_ids` passed when calling [`SiglipModel`].
52
- hidden_size (`int`, *optional*, defaults to 512):
53
  Dimensionality of the encoder layers and the pooler layer.
54
- intermediate_size (`int`, *optional*, defaults to 2048):
55
  Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
56
  num_hidden_layers (`int`, *optional*, defaults to 12):
57
  Number of hidden layers in the Transformer encoder.
58
- num_attention_heads (`int`, *optional*, defaults to 8):
59
  Number of attention heads for each attention layer in the Transformer encoder.
60
  max_position_embeddings (`int`, *optional*, defaults to 64):
61
  The maximum sequence length that this model might ever be used with. Typically set this to something large
@@ -63,15 +56,16 @@ class SiglipTextConfig(PretrainedConfig):
63
  hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
64
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
65
  `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
66
- layer_norm_eps (`float`, *optional*, defaults to 1e-6):
67
  The epsilon used by the layer normalization layers.
68
  attention_dropout (`float`, *optional*, defaults to 0.0):
69
  The dropout ratio for the attention probabilities.
70
- initializer_range (`float`, *optional*, defaults to 0.02):
71
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
- initializer_factor (`float`, *optional*, defaults to 1):
73
- A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
74
- testing).
 
75
 
76
  Example:
77
 
@@ -87,22 +81,20 @@ class SiglipTextConfig(PretrainedConfig):
87
  >>> # Accessing the model configuration
88
  >>> configuration = model.config
89
  ```"""
 
90
  model_type = "siglip_text_model"
91
 
92
  def __init__(
93
  self,
94
- vocab_size=49408,
95
- hidden_size=512,
96
- intermediate_size=2048,
97
- projection_dim=512,
98
  num_hidden_layers=12,
99
- num_attention_heads=8,
100
  max_position_embeddings=64,
101
  hidden_act="gelu_pytorch_tanh",
102
  layer_norm_eps=1e-6,
103
  attention_dropout=0.0,
104
- initializer_range=0.02,
105
- initializer_factor=1.0,
106
  # This differs from `CLIPTokenizer`'s default and from openai/siglip
107
  # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
108
  pad_token_id=1,
@@ -116,14 +108,11 @@ class SiglipTextConfig(PretrainedConfig):
116
  self.vocab_size = vocab_size
117
  self.hidden_size = hidden_size
118
  self.intermediate_size = intermediate_size
119
- self.projection_dim = projection_dim
120
  self.num_hidden_layers = num_hidden_layers
121
  self.num_attention_heads = num_attention_heads
122
  self.max_position_embeddings = max_position_embeddings
123
  self.layer_norm_eps = layer_norm_eps
124
  self.hidden_act = hidden_act
125
- self.initializer_range = initializer_range
126
- self.initializer_factor = initializer_factor
127
  self.attention_dropout = attention_dropout
128
  self._flash_attn_2_enabled = _flash_attn_2_enabled
129
 
@@ -165,22 +154,19 @@ class SiglipVisionConfig(PretrainedConfig):
165
  Number of hidden layers in the Transformer encoder.
166
  num_attention_heads (`int`, *optional*, defaults to 12):
167
  Number of attention heads for each attention layer in the Transformer encoder.
 
 
168
  image_size (`int`, *optional*, defaults to 224):
169
  The size (resolution) of each image.
170
- patch_size (`int`, *optional*, defaults to 32):
171
  The size (resolution) of each patch.
172
  hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
173
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
174
  `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
175
- layer_norm_eps (`float`, *optional*, defaults to 1e-6):
176
  The epsilon used by the layer normalization layers.
177
  attention_dropout (`float`, *optional*, defaults to 0.0):
178
  The dropout ratio for the attention probabilities.
179
- initializer_range (`float`, *optional*, defaults to 0.02):
180
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
181
- initializer_factor (`float`, *optional*, defaults to 1):
182
- A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
183
- testing).
184
 
185
  Example:
186
 
@@ -203,17 +189,14 @@ class SiglipVisionConfig(PretrainedConfig):
203
  self,
204
  hidden_size=768,
205
  intermediate_size=3072,
206
- projection_dim=512,
207
  num_hidden_layers=12,
208
  num_attention_heads=12,
209
  num_channels=3,
210
  image_size=224,
211
- patch_size=32,
212
  hidden_act="gelu_pytorch_tanh",
213
  layer_norm_eps=1e-6,
214
  attention_dropout=0.0,
215
- initializer_range=0.02,
216
- initializer_factor=1.0,
217
  _flash_attn_2_enabled=True,
218
  **kwargs,
219
  ):
@@ -221,14 +204,11 @@ class SiglipVisionConfig(PretrainedConfig):
221
 
222
  self.hidden_size = hidden_size
223
  self.intermediate_size = intermediate_size
224
- self.projection_dim = projection_dim
225
  self.num_hidden_layers = num_hidden_layers
226
  self.num_attention_heads = num_attention_heads
227
  self.num_channels = num_channels
228
  self.patch_size = patch_size
229
  self.image_size = image_size
230
- self.initializer_range = initializer_range
231
- self.initializer_factor = initializer_factor
232
  self.attention_dropout = attention_dropout
233
  self.layer_norm_eps = layer_norm_eps
234
  self.hidden_act = hidden_act
@@ -268,10 +248,6 @@ class SiglipConfig(PretrainedConfig):
268
  Dictionary of configuration options used to initialize [`SiglipTextConfig`].
269
  vision_config (`dict`, *optional*):
270
  Dictionary of configuration options used to initialize [`SiglipVisionConfig`].
271
- projection_dim (`int`, *optional*, defaults to 512):
272
- Dimentionality of text and vision projection layers.
273
- logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
274
- The inital value of the *logit_scale* paramter. Default is used as per the original Siglip implementation.
275
  kwargs (*optional*):
276
  Dictionary of keyword arguments.
277
 
@@ -301,79 +277,9 @@ class SiglipConfig(PretrainedConfig):
301
 
302
  model_type = "siglip"
303
 
304
- def __init__(
305
- self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
306
- ):
307
- # If `_config_dict` exist, we use them for the backward compatibility.
308
- # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
309
- # of confusion!).
310
- text_config_dict = kwargs.pop("text_config_dict", None)
311
- vision_config_dict = kwargs.pop("vision_config_dict", None)
312
-
313
  super().__init__(**kwargs)
314
 
315
- # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
316
- # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
317
- # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
318
- if text_config_dict is not None:
319
- if text_config is None:
320
- text_config = {}
321
-
322
- # This is the complete result when using `text_config_dict`.
323
- _text_config_dict = SiglipTextConfig(**text_config_dict).to_dict()
324
-
325
- # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
326
- for key, value in _text_config_dict.items():
327
- if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
328
- # If specified in `text_config_dict`
329
- if key in text_config_dict:
330
- message = (
331
- f"`{key}` is found in both `text_config_dict` and `text_config` but with different values."
332
- f' The value `text_config_dict["{key}"]` will be used instead.'
333
- )
334
- # If inferred from default argument values (just to be super careful)
335
- else:
336
- message = (
337
- "`text_config_dict` is provided which will be used to initialize `SiglipTextConfig`. The "
338
- f'value `text_config["{key}"]` will be overriden.'
339
- )
340
- logger.warning(message)
341
-
342
- # Update all values in `text_config` with the ones in `_text_config_dict`.
343
- text_config.update(_text_config_dict)
344
-
345
- if vision_config_dict is not None:
346
- if vision_config is None:
347
- vision_config = {}
348
-
349
- # This is the complete result when using `vision_config_dict`.
350
- _vision_config_dict = SiglipVisionConfig(**vision_config_dict).to_dict()
351
- # convert keys to string instead of integer
352
- if "id2label" in _vision_config_dict:
353
- _vision_config_dict["id2label"] = {
354
- str(key): value for key, value in _vision_config_dict["id2label"].items()
355
- }
356
-
357
- # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
358
- for key, value in _vision_config_dict.items():
359
- if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
360
- # If specified in `vision_config_dict`
361
- if key in vision_config_dict:
362
- message = (
363
- f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
364
- f'values. The value `vision_config_dict["{key}"]` will be used instead.'
365
- )
366
- # If inferred from default argument values (just to be super careful)
367
- else:
368
- message = (
369
- "`vision_config_dict` is provided which will be used to initialize `SiglipVisionConfig`. "
370
- f'The value `vision_config["{key}"]` will be overriden.'
371
- )
372
- logger.warning(message)
373
-
374
- # Update all values in `vision_config` with the ones in `_vision_config_dict`.
375
- vision_config.update(_vision_config_dict)
376
-
377
  if text_config is None:
378
  text_config = {}
379
  logger.info("`text_config` is `None`. Initializing the `SiglipTextConfig` with default values.")
@@ -385,8 +291,6 @@ class SiglipConfig(PretrainedConfig):
385
  self.text_config = SiglipTextConfig(**text_config)
386
  self.vision_config = SiglipVisionConfig(**vision_config)
387
 
388
- self.projection_dim = projection_dim
389
- self.logit_scale_init_value = logit_scale_init_value
390
  self.initializer_factor = 1.0
391
 
392
  @classmethod
@@ -400,49 +304,3 @@ class SiglipConfig(PretrainedConfig):
400
  """
401
 
402
  return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
403
-
404
-
405
- class SiglipOnnxConfig(OnnxConfig):
406
- @property
407
- def inputs(self) -> Mapping[str, Mapping[int, str]]:
408
- return OrderedDict(
409
- [
410
- ("input_ids", {0: "batch", 1: "sequence"}),
411
- ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
412
- ("attention_mask", {0: "batch", 1: "sequence"}),
413
- ]
414
- )
415
-
416
- @property
417
- def outputs(self) -> Mapping[str, Mapping[int, str]]:
418
- return OrderedDict(
419
- [
420
- ("logits_per_image", {0: "batch"}),
421
- ("logits_per_text", {0: "batch"}),
422
- ("text_embeds", {0: "batch"}),
423
- ("image_embeds", {0: "batch"}),
424
- ]
425
- )
426
-
427
- @property
428
- def atol_for_validation(self) -> float:
429
- return 1e-4
430
-
431
- def generate_dummy_inputs(
432
- self,
433
- processor: "ProcessorMixin",
434
- batch_size: int = -1,
435
- seq_length: int = -1,
436
- framework: Optional["TensorType"] = None,
437
- ) -> Mapping[str, Any]:
438
- text_input_dict = super().generate_dummy_inputs(
439
- processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
440
- )
441
- image_input_dict = super().generate_dummy_inputs(
442
- processor.image_processor, batch_size=batch_size, framework=framework
443
- )
444
- return {**text_input_dict, **image_input_dict}
445
-
446
- @property
447
- def default_onnx_opset(self) -> int:
448
- return 14
 
1
  # coding=utf-8
2
+ # Copyright 2024 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.
 
15
  """ Siglip model configuration"""
16
 
17
  import os
18
+ from typing import Union
 
19
 
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
 
 
 
 
 
 
22
 
23
 
24
  logger = logging.get_logger(__name__)
 
39
  documentation from [`PretrainedConfig`] for more information.
40
 
41
  Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
  Vocabulary size of the Siglip text model. Defines the number of different tokens that can be represented by
44
  the `inputs_ids` passed when calling [`SiglipModel`].
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
  Dimensionality of the encoder layers and the pooler layer.
47
+ intermediate_size (`int`, *optional*, defaults to 3072):
48
  Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
49
  num_hidden_layers (`int`, *optional*, defaults to 12):
50
  Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 12):
52
  Number of attention heads for each attention layer in the Transformer encoder.
53
  max_position_embeddings (`int`, *optional*, defaults to 64):
54
  The maximum sequence length that this model might ever be used with. Typically set this to something large
 
56
  hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
57
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
  `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
59
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
60
  The epsilon used by the layer normalization layers.
61
  attention_dropout (`float`, *optional*, defaults to 0.0):
62
  The dropout ratio for the attention probabilities.
63
+ pad_token_id (`int`, *optional*, defaults to 1):
64
+ The id of the padding token in the vocabulary.
65
+ bos_token_id (`int`, *optional*, defaults to 49406):
66
+ The id of the beginning-of-sequence token in the vocabulary.
67
+ eos_token_id (`int`, *optional*, defaults to 49407):
68
+ The id of the end-of-sequence token in the vocabulary.
69
 
70
  Example:
71
 
 
81
  >>> # Accessing the model configuration
82
  >>> configuration = model.config
83
  ```"""
84
+
85
  model_type = "siglip_text_model"
86
 
87
  def __init__(
88
  self,
89
+ vocab_size=32000,
90
+ hidden_size=768,
91
+ intermediate_size=3072,
 
92
  num_hidden_layers=12,
93
+ num_attention_heads=12,
94
  max_position_embeddings=64,
95
  hidden_act="gelu_pytorch_tanh",
96
  layer_norm_eps=1e-6,
97
  attention_dropout=0.0,
 
 
98
  # This differs from `CLIPTokenizer`'s default and from openai/siglip
99
  # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
100
  pad_token_id=1,
 
108
  self.vocab_size = vocab_size
109
  self.hidden_size = hidden_size
110
  self.intermediate_size = intermediate_size
 
111
  self.num_hidden_layers = num_hidden_layers
112
  self.num_attention_heads = num_attention_heads
113
  self.max_position_embeddings = max_position_embeddings
114
  self.layer_norm_eps = layer_norm_eps
115
  self.hidden_act = hidden_act
 
 
116
  self.attention_dropout = attention_dropout
117
  self._flash_attn_2_enabled = _flash_attn_2_enabled
118
 
 
154
  Number of hidden layers in the Transformer encoder.
155
  num_attention_heads (`int`, *optional*, defaults to 12):
156
  Number of attention heads for each attention layer in the Transformer encoder.
157
+ num_channels (`int`, *optional*, defaults to 3):
158
+ Number of channels in the input images.
159
  image_size (`int`, *optional*, defaults to 224):
160
  The size (resolution) of each image.
161
+ patch_size (`int`, *optional*, defaults to 16):
162
  The size (resolution) of each patch.
163
  hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
164
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
165
  `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
166
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
167
  The epsilon used by the layer normalization layers.
168
  attention_dropout (`float`, *optional*, defaults to 0.0):
169
  The dropout ratio for the attention probabilities.
 
 
 
 
 
170
 
171
  Example:
172
 
 
189
  self,
190
  hidden_size=768,
191
  intermediate_size=3072,
 
192
  num_hidden_layers=12,
193
  num_attention_heads=12,
194
  num_channels=3,
195
  image_size=224,
196
+ patch_size=16,
197
  hidden_act="gelu_pytorch_tanh",
198
  layer_norm_eps=1e-6,
199
  attention_dropout=0.0,
 
 
200
  _flash_attn_2_enabled=True,
201
  **kwargs,
202
  ):
 
204
 
205
  self.hidden_size = hidden_size
206
  self.intermediate_size = intermediate_size
 
207
  self.num_hidden_layers = num_hidden_layers
208
  self.num_attention_heads = num_attention_heads
209
  self.num_channels = num_channels
210
  self.patch_size = patch_size
211
  self.image_size = image_size
 
 
212
  self.attention_dropout = attention_dropout
213
  self.layer_norm_eps = layer_norm_eps
214
  self.hidden_act = hidden_act
 
248
  Dictionary of configuration options used to initialize [`SiglipTextConfig`].
249
  vision_config (`dict`, *optional*):
250
  Dictionary of configuration options used to initialize [`SiglipVisionConfig`].
 
 
 
 
251
  kwargs (*optional*):
252
  Dictionary of keyword arguments.
253
 
 
277
 
278
  model_type = "siglip"
279
 
280
+ def __init__(self, text_config=None, vision_config=None, **kwargs):
 
 
 
 
 
 
 
 
281
  super().__init__(**kwargs)
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  if text_config is None:
284
  text_config = {}
285
  logger.info("`text_config` is `None`. Initializing the `SiglipTextConfig` with default values.")
 
291
  self.text_config = SiglipTextConfig(**text_config)
292
  self.vision_config = SiglipVisionConfig(**vision_config)
293
 
 
 
294
  self.initializer_factor = 1.0
295
 
296
  @classmethod
 
304
  """
305
 
306
  return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)