merve HF staff commited on
Commit
f485129
1 Parent(s): 4a23c59

Create configuration_nllb_clip.py

Browse files
Files changed (1) hide show
  1. configuration_nllb_clip.py +273 -0
configuration_nllb_clip.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ NLLB-CLIP model configuration"""
2
+
3
+ import os
4
+ from collections import OrderedDict
5
+ from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
6
+
7
+ if TYPE_CHECKING:
8
+ from transformers.processing_utils import ProcessorMixin
9
+ from transformers.utils import TensorType
10
+
11
+ from transformers import CLIPVisionConfig
12
+ from transformers.configuration_utils import PretrainedConfig
13
+ from transformers.onnx import OnnxConfig
14
+ from transformers.utils import logging
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class NLLBCLIPTextConfig(PretrainedConfig):
20
+ model_type = "clip_text_model"
21
+ attribute_map = {
22
+ "num_attention_heads": "encoder_attention_heads",
23
+ "hidden_size": "d_model",
24
+ }
25
+
26
+ def __init__(
27
+ self,
28
+ vocab_size=128112,
29
+ max_position_embeddings=1024,
30
+ encoder_layers=12,
31
+ encoder_ffn_dim=4096,
32
+ encoder_attention_heads=16,
33
+ encoder_layerdrop=0.05,
34
+ use_cache=True,
35
+ activation_function="relu",
36
+ d_model=1024,
37
+ dropout=0.1,
38
+ attention_dropout=0.1,
39
+ activation_dropout=0.0,
40
+ init_std=0.02,
41
+ scale_embedding=True,
42
+ pad_token_id=1,
43
+ bos_token_id=0,
44
+ eos_token_id=2,
45
+ layer_norm_eps=1e-5,
46
+ **kwargs,
47
+ ):
48
+ self.vocab_size = vocab_size
49
+ self.max_position_embeddings = max_position_embeddings
50
+ self.d_model = d_model
51
+ self.encoder_ffn_dim = encoder_ffn_dim
52
+ self.encoder_layers = encoder_layers
53
+ self.encoder_attention_heads = encoder_attention_heads
54
+ self.dropout = dropout
55
+ self.attention_dropout = attention_dropout
56
+ self.activation_dropout = activation_dropout
57
+ self.activation_function = activation_function
58
+ self.init_std = init_std
59
+ self.encoder_layerdrop = encoder_layerdrop
60
+ self.use_cache = use_cache
61
+ self.num_hidden_layers = encoder_layers
62
+ self.scale_embedding = scale_embedding
63
+ self.layer_norm_eps = layer_norm_eps
64
+
65
+ super().__init__(
66
+ pad_token_id=pad_token_id,
67
+ bos_token_id=bos_token_id,
68
+ eos_token_id=eos_token_id,
69
+ **kwargs,
70
+ )
71
+
72
+ @classmethod
73
+ def from_pretrained(
74
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
75
+ ) -> "PretrainedConfig":
76
+ config_dict, kwargs = cls.get_config_dict(
77
+ pretrained_model_name_or_path, **kwargs
78
+ )
79
+
80
+ # get the vision config dict if we are loading from CLIPConfig
81
+ if config_dict.get("model_type") == "clip":
82
+ config_dict = config_dict["text_config"]
83
+
84
+ if (
85
+ "model_type" in config_dict
86
+ and hasattr(cls, "model_type")
87
+ and config_dict["model_type"] != cls.model_type
88
+ ):
89
+ logger.warning(
90
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
91
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
92
+ )
93
+
94
+ return cls.from_dict(config_dict, **kwargs)
95
+
96
+
97
+ class NLLBCLIPConfig(PretrainedConfig):
98
+ model_type = "clip"
99
+
100
+ def __init__(
101
+ self,
102
+ text_config=None,
103
+ vision_config=None,
104
+ projection_dim=512,
105
+ logit_scale_init_value=2.6592,
106
+ **kwargs,
107
+ ):
108
+ # If `_config_dict` exist, we use them for the backward compatibility.
109
+ # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
110
+ # of confusion!).
111
+ text_config_dict = kwargs.pop("text_config_dict", None)
112
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
113
+
114
+ super().__init__(**kwargs)
115
+
116
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
117
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
118
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
119
+ if text_config_dict is not None:
120
+ if text_config is None:
121
+ text_config = {}
122
+
123
+ # This is the complete result when using `text_config_dict`.
124
+ _text_config_dict = NLLBCLIPTextConfig(**text_config_dict).to_dict()
125
+
126
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
127
+ for key, value in _text_config_dict.items():
128
+ if (
129
+ key in text_config
130
+ and value != text_config[key]
131
+ and key not in ["transformers_version"]
132
+ ):
133
+ # If specified in `text_config_dict`
134
+ if key in text_config_dict:
135
+ message = (
136
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
137
+ f'The value `text_config_dict["{key}"]` will be used instead.'
138
+ )
139
+ # If inferred from default argument values (just to be super careful)
140
+ else:
141
+ message = (
142
+ f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
143
+ f'value `text_config["{key}"]` will be overriden.'
144
+ )
145
+ logger.warning(message)
146
+
147
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
148
+ text_config.update(_text_config_dict)
149
+
150
+ if vision_config_dict is not None:
151
+ if vision_config is None:
152
+ vision_config = {}
153
+
154
+ # This is the complete result when using `vision_config_dict`.
155
+ _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
156
+ # convert keys to string instead of integer
157
+ if "id2label" in _vision_config_dict:
158
+ _vision_config_dict["id2label"] = {
159
+ str(key): value
160
+ for key, value in _vision_config_dict["id2label"].items()
161
+ }
162
+
163
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
164
+ for key, value in _vision_config_dict.items():
165
+ if (
166
+ key in vision_config
167
+ and value != vision_config[key]
168
+ and key not in ["transformers_version"]
169
+ ):
170
+ # If specified in `vision_config_dict`
171
+ if key in vision_config_dict:
172
+ message = (
173
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
174
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
175
+ )
176
+ # If inferred from default argument values (just to be super careful)
177
+ else:
178
+ message = (
179
+ f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
180
+ f'The value `vision_config["{key}"]` will be overriden.'
181
+ )
182
+ logger.warning(message)
183
+
184
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
185
+ vision_config.update(_vision_config_dict)
186
+
187
+ if text_config is None:
188
+ text_config = {}
189
+ logger.info(
190
+ "`text_config` is `None`. Initializing the `NLLBCLIPTextConfig` with default values."
191
+ )
192
+
193
+ if vision_config is None:
194
+ vision_config = {}
195
+ logger.info(
196
+ "`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values."
197
+ )
198
+
199
+ self.text_config = NLLBCLIPTextConfig(**text_config)
200
+ self.vision_config = CLIPVisionConfig(**vision_config)
201
+
202
+ self.projection_dim = projection_dim
203
+ self.logit_scale_init_value = logit_scale_init_value
204
+ self.initializer_factor = 1.0
205
+
206
+ @classmethod
207
+ def from_text_vision_configs(
208
+ cls, text_config: NLLBCLIPTextConfig, vision_config: CLIPVisionConfig, **kwargs
209
+ ):
210
+ r"""
211
+ Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
212
+ configuration.
213
+ Returns:
214
+ [`CLIPConfig`]: An instance of a configuration object
215
+ """
216
+
217
+ return cls(
218
+ text_config=text_config.to_dict(),
219
+ vision_config=vision_config.to_dict(),
220
+ **kwargs,
221
+ )
222
+
223
+
224
+ class CLIPOnnxConfig(OnnxConfig):
225
+ @property
226
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
227
+ return OrderedDict(
228
+ [
229
+ ("input_ids", {0: "batch", 1: "sequence"}),
230
+ ("attention_mask", {0: "batch", 1: "sequence"}),
231
+ (
232
+ "pixel_values",
233
+ {0: "batch", 1: "num_channels", 2: "height", 3: "width"},
234
+ ),
235
+ ]
236
+ )
237
+
238
+ @property
239
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
240
+ return OrderedDict(
241
+ [
242
+ ("logits_per_image", {0: "batch"}),
243
+ ("logits_per_text", {0: "batch"}),
244
+ ("text_embeds", {0: "batch"}),
245
+ ("image_embeds", {0: "batch"}),
246
+ ]
247
+ )
248
+
249
+ @property
250
+ def atol_for_validation(self) -> float:
251
+ return 1e-4
252
+
253
+ def generate_dummy_inputs(
254
+ self,
255
+ processor: "ProcessorMixin",
256
+ batch_size: int = -1,
257
+ seq_length: int = -1,
258
+ framework: Optional["TensorType"] = None,
259
+ ) -> Mapping[str, Any]:
260
+ text_input_dict = super().generate_dummy_inputs(
261
+ processor.tokenizer,
262
+ batch_size=batch_size,
263
+ seq_length=seq_length,
264
+ framework=framework,
265
+ )
266
+ image_input_dict = super().generate_dummy_inputs(
267
+ processor.image_processor, batch_size=batch_size, framework=framework
268
+ )
269
+ return {**text_input_dict, **image_input_dict}
270
+
271
+ @property
272
+ def default_onnx_opset(self) -> int:
273
+ return 14