Gengzigang commited on
Commit
aec4766
1 Parent(s): e44c31c
Files changed (7) hide show
  1. CLIP.png +0 -0
  2. README.md +55 -3
  3. config.json +179 -0
  4. configuration_clip.py +420 -0
  5. modeling_clip.py +1598 -0
  6. pytorch_model.bin +3 -0
  7. teaser.png +0 -0
CLIP.png ADDED
README.md CHANGED
@@ -1,3 +1,55 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+ <div align="center">
5
+
6
+ <h2><a href="">LLM2CLIP: Extending the Capability Boundaries of CLIP through Large Language Models</a></h2>
7
+ Weiquan Huang<sup>1*</sup>, Aoqi Wu<sup>1*</sup>, Yifan Yang<sup>2†</sup>, Xufang Luo<sup>2</sup>, Yuqing Yang<sup>2</sup>, Liang Hu<sup>1</sup>, Qi Dai<sup>2</sup>, Xiyang Dai<sup>2</sup>, Dongdong Chen<sup>2</sup>, Chong Luo<sup>2</sup>, Lili Qiu<sup>2</sup>
8
+
9
+ <sup>1</sup>Tongji Universiy, <sup>2</sup>Microsoft Corporation <br><sup>*</sup>Equal contribution <br><sup>†</sup> Corresponding to: [email protected]
10
+
11
+ <p><a rel="nofollow" href="https://github.com/microsoft/LLM2CLIP">[📂 GitHub]</a> <a rel="nofollow" href="https://microsoft.github.io/LLM2CLIP/">[🆕 Blog]</a> <a rel="nofollow" href="">[📜 LLM2CLIP]</a>
12
+ </div>
13
+
14
+
15
+ In this paper, we propose LLM2CLIP, a novel approach that embraces the power of LLMs to unlock CLIP’s potential. By fine-tuning the LLM in the caption space with contrastive learning, we extract its textual capabilities into the output embeddings, significantly improving the output layer’s textual discriminability. We then design an efficient training process where the fine-tuned LLM acts as a powerful teacher for CLIP’s visual encoder. Thanks to the LLM’s presence, we can now incorporate longer and more complex captions without being restricted by vanilla CLIP text encoder’s context window and ability limitations. Our experiments demonstrate that this approach brings substantial improvements in cross-modal tasks. Our method directly boosted the performance of the previously SOTA EVA02 model by 16.5% on both long-text and short-text retrieval tasks, transforming a CLIP model trained solely on English data into a state-of-the-art cross-lingual model. Moreover, when integrated into mul- timodal training with models like Llava 1.5, it consistently outperformed CLIP across nearly all benchmarks, demonstrating comprehensive performance improvements.
16
+
17
+ ## LLM2CLIP performance
18
+
19
+ <div align="center">
20
+ <img src="teaser.png" alt="summary_tab" width="85%">
21
+ </div>
22
+ **It's important to note that all results presented in the paper are evaluated using PyTorch weights. There may be differences in performance when using Hugging Face (hf) models.**
23
+
24
+ ## Model Details
25
+ - **Model Type:** vision foundation model, feature backbone
26
+ - **Pretrain Dataset:** CC3M, CC12M, YFCC15M and Recap-DataComp-1B(30M subset)
27
+
28
+
29
+ ## Usage
30
+
31
+ ### Huggingface Version
32
+ ```python
33
+ from PIL import Image
34
+ from transformers import AutoModel
35
+ from transformers import CLIPImageProcessor
36
+ import torch
37
+
38
+ image_path = "CLIP.png"
39
+ model_name_or_path = "LLM2CLIP-Openai-L-14-336" # or /path/to/local/LLM2CLIP-Openai-L-14-336
40
+ image_size = 224
41
+
42
+ processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14-336")
43
+ model = AutoModel.from_pretrained(
44
+ model_name_or_path,
45
+ torch_dtype=torch.float16,
46
+ trust_remote_code=True).to('cuda').eval()
47
+
48
+ image = Image.open(image_path)
49
+ input_pixels = processor(images=image, return_tensors="pt").pixel_values.to('cuda')
50
+
51
+ with torch.no_grad(), torch.cuda.amp.autocast():
52
+ outputs = model.get_image_features(input_pixels)
53
+ ```
54
+
55
+ ## BibTeX & Citation
config.json ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "LLM2CLIP-Openai-L-14",
4
+ "architectures": [
5
+ "CLIPModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_clip.CLIPConfig",
9
+ "AutoModel": "modeling_clip.CLIPModel"
10
+ },
11
+ "initializer_factor": 1.0,
12
+ "logit_scale_init_value": 2.6592,
13
+ "model_type": "clip",
14
+ "projection_dim": 1280,
15
+ "text_config": {
16
+ "_name_or_path": "",
17
+ "add_cross_attention": false,
18
+ "architectures": null,
19
+ "attention_dropout": 0.0,
20
+ "bad_words_ids": null,
21
+ "begin_suppress_tokens": null,
22
+ "bos_token_id": 0,
23
+ "chunk_size_feed_forward": 0,
24
+ "cross_attention_hidden_size": null,
25
+ "decoder_start_token_id": null,
26
+ "diversity_penalty": 0.0,
27
+ "do_sample": false,
28
+ "early_stopping": false,
29
+ "encoder_no_repeat_ngram_size": 0,
30
+ "eos_token_id": 2,
31
+ "exponential_decay_length_penalty": null,
32
+ "finetuning_task": null,
33
+ "forced_bos_token_id": null,
34
+ "forced_eos_token_id": null,
35
+ "hidden_act": "gelu",
36
+ "hidden_size": 512,
37
+ "id2label": {
38
+ "0": "LABEL_0",
39
+ "1": "LABEL_1"
40
+ },
41
+ "initializer_factor": 1.0,
42
+ "initializer_range": 0.02,
43
+ "intermediate_size": 2048,
44
+ "is_decoder": false,
45
+ "is_encoder_decoder": false,
46
+ "k_bias": true,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1
50
+ },
51
+ "layer_norm_eps": 1e-05,
52
+ "length_penalty": 1.0,
53
+ "max_length": 20,
54
+ "max_position_embeddings": 77,
55
+ "min_length": 0,
56
+ "model_type": "clip_text_model",
57
+ "no_repeat_ngram_size": 0,
58
+ "num_attention_heads": 8,
59
+ "num_beam_groups": 1,
60
+ "num_beams": 1,
61
+ "num_hidden_layers": 12,
62
+ "num_return_sequences": 1,
63
+ "output_attentions": false,
64
+ "output_hidden_states": false,
65
+ "output_scores": false,
66
+ "pad_token_id": 1,
67
+ "post_layernorm": false,
68
+ "prefix": null,
69
+ "problem_type": null,
70
+ "projection_dim": 512,
71
+ "pruned_heads": {},
72
+ "q_bias": true,
73
+ "remove_invalid_values": false,
74
+ "repetition_penalty": 1.0,
75
+ "return_dict": true,
76
+ "return_dict_in_generate": false,
77
+ "sep_token_id": null,
78
+ "suppress_tokens": null,
79
+ "task_specific_params": null,
80
+ "temperature": 1.0,
81
+ "tf_legacy_loss": false,
82
+ "tie_encoder_decoder": false,
83
+ "tie_word_embeddings": true,
84
+ "tokenizer_class": null,
85
+ "top_k": 50,
86
+ "top_p": 1.0,
87
+ "torch_dtype": null,
88
+ "torchscript": false,
89
+ "transformers_version": "4.44.2",
90
+ "typical_p": 1.0,
91
+ "use_bfloat16": false,
92
+ "v_bias": true,
93
+ "vocab_size": 49408
94
+ },
95
+ "torch_dtype": "float32",
96
+ "transformers_version": null,
97
+ "vision_config": {
98
+ "_name_or_path": "",
99
+ "add_cross_attention": false,
100
+ "architectures": null,
101
+ "attention_dropout": 0.0,
102
+ "bad_words_ids": null,
103
+ "begin_suppress_tokens": null,
104
+ "bos_token_id": null,
105
+ "chunk_size_feed_forward": 0,
106
+ "cross_attention_hidden_size": null,
107
+ "decoder_start_token_id": null,
108
+ "diversity_penalty": 0.0,
109
+ "do_sample": false,
110
+ "dropout": 0.0,
111
+ "early_stopping": false,
112
+ "encoder_no_repeat_ngram_size": 0,
113
+ "eos_token_id": null,
114
+ "exponential_decay_length_penalty": null,
115
+ "finetuning_task": null,
116
+ "forced_bos_token_id": null,
117
+ "forced_eos_token_id": null,
118
+ "hidden_act": "gelu",
119
+ "hidden_size": 1024,
120
+ "id2label": {
121
+ "0": "LABEL_0",
122
+ "1": "LABEL_1"
123
+ },
124
+ "image_size": 336,
125
+ "initializer_factor": 1.0,
126
+ "initializer_range": 0.02,
127
+ "intermediate_size": 4096,
128
+ "is_decoder": false,
129
+ "is_encoder_decoder": false,
130
+ "k_bias": true,
131
+ "label2id": {
132
+ "LABEL_0": 0,
133
+ "LABEL_1": 1
134
+ },
135
+ "layer_norm_eps": 1e-05,
136
+ "length_penalty": 1.0,
137
+ "max_length": 20,
138
+ "min_length": 0,
139
+ "model_type": "clip_vision_model",
140
+ "no_repeat_ngram_size": 0,
141
+ "num_attention_heads": 16,
142
+ "num_beam_groups": 1,
143
+ "num_beams": 1,
144
+ "num_channels": 3,
145
+ "num_hidden_layers": 24,
146
+ "num_return_sequences": 1,
147
+ "output_attentions": false,
148
+ "output_hidden_states": false,
149
+ "output_scores": false,
150
+ "pad_token_id": null,
151
+ "patch_size": 14,
152
+ "post_layernorm": false,
153
+ "prefix": null,
154
+ "problem_type": null,
155
+ "projection_dim": 768,
156
+ "pruned_heads": {},
157
+ "q_bias": true,
158
+ "remove_invalid_values": false,
159
+ "repetition_penalty": 1.0,
160
+ "return_dict": true,
161
+ "return_dict_in_generate": false,
162
+ "sep_token_id": null,
163
+ "suppress_tokens": null,
164
+ "task_specific_params": null,
165
+ "temperature": 1.0,
166
+ "tf_legacy_loss": false,
167
+ "tie_encoder_decoder": false,
168
+ "tie_word_embeddings": true,
169
+ "tokenizer_class": null,
170
+ "top_k": 50,
171
+ "top_p": 1.0,
172
+ "torch_dtype": null,
173
+ "torchscript": false,
174
+ "transformers_version": "4.44.2",
175
+ "typical_p": 1.0,
176
+ "use_bfloat16": false,
177
+ "v_bias": true
178
+ }
179
+ }
configuration_clip.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """CLIP model configuration"""
16
+ # Code mainly copied here: https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/configuration_clip.py
17
+
18
+ import copy
19
+ import os
20
+ from collections import OrderedDict
21
+ from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import ProcessorMixin
26
+ from transformers.utils import TensorType
27
+
28
+ from transformers.configuration_utils import PretrainedConfig
29
+ from transformers.utils import logging
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ class CLIPTextConfig(PretrainedConfig):
36
+ r"""
37
+ This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
38
+ text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
39
+ with the defaults will yield a similar configuration to that of the text encoder of the CLIP
40
+ [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
41
+
42
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
43
+ documentation from [`PretrainedConfig`] for more information.
44
+
45
+ Args:
46
+ vocab_size (`int`, *optional*, defaults to 49408):
47
+ Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
48
+ the `inputs_ids` passed when calling [`CLIPModel`].
49
+ hidden_size (`int`, *optional*, defaults to 512):
50
+ Dimensionality of the encoder layers and the pooler layer.
51
+ intermediate_size (`int`, *optional*, defaults to 2048):
52
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
53
+ num_hidden_layers (`int`, *optional*, defaults to 12):
54
+ Number of hidden layers in the Transformer encoder.
55
+ num_attention_heads (`int`, *optional*, defaults to 8):
56
+ Number of attention heads for each attention layer in the Transformer encoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 77):`
58
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
59
+ just in case (e.g., 512 or 1024 or 2048).
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
61
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
62
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
63
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
64
+ The epsilon used by the layer normalization layers.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio for the attention probabilities.
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ initializer_factor (`float`, *optional*, defaults to 1):
70
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
71
+ testing).
72
+
73
+ Example:
74
+
75
+ ```python
76
+ >>> from transformers import CLIPTextConfig, CLIPTextModel
77
+
78
+ >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
79
+ >>> configuration = CLIPTextConfig()
80
+
81
+ >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
82
+ >>> model = CLIPTextModel(configuration)
83
+
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+ model_type = "clip_text_model"
88
+
89
+ def __init__(
90
+ self,
91
+ vocab_size=49408,
92
+ hidden_size=512,
93
+ intermediate_size=2048,
94
+ projection_dim=512,
95
+ num_hidden_layers=12,
96
+ num_attention_heads=8,
97
+ max_position_embeddings=77,
98
+ hidden_act="gelu",
99
+ layer_norm_eps=1e-5,
100
+ attention_dropout=0.0,
101
+ initializer_range=0.02,
102
+ initializer_factor=1.0,
103
+ q_bias=True,
104
+ k_bias=True,
105
+ v_bias=True,
106
+ post_layernorm=False,
107
+ pad_token_id=1,
108
+ bos_token_id=0,
109
+ eos_token_id=2,
110
+ **kwargs,
111
+ ):
112
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
113
+
114
+ self.vocab_size = vocab_size
115
+ self.hidden_size = hidden_size
116
+ self.intermediate_size = intermediate_size
117
+ self.projection_dim = projection_dim
118
+ self.num_hidden_layers = num_hidden_layers
119
+ self.num_attention_heads = num_attention_heads
120
+ self.max_position_embeddings = max_position_embeddings
121
+ self.layer_norm_eps = layer_norm_eps
122
+ self.hidden_act = hidden_act
123
+ self.initializer_range = initializer_range
124
+ self.initializer_factor = initializer_factor
125
+ self.q_bias=q_bias
126
+ self.k_bias=k_bias
127
+ self.v_bias=v_bias
128
+ self.post_layernorm = post_layernorm
129
+ self.attention_dropout = attention_dropout
130
+
131
+ @classmethod
132
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
133
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
134
+
135
+ # get the text config dict if we are loading from CLIPConfig
136
+ if config_dict.get("model_type") == "clip":
137
+ config_dict = config_dict["text_config"]
138
+
139
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
140
+ logger.warning(
141
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
142
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
143
+ )
144
+
145
+ return cls.from_dict(config_dict, **kwargs)
146
+
147
+
148
+ class CLIPVisionConfig(PretrainedConfig):
149
+ r"""
150
+ This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
151
+ CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
152
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
153
+ [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
154
+
155
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
156
+ documentation from [`PretrainedConfig`] for more information.
157
+
158
+ Args:
159
+ hidden_size (`int`, *optional*, defaults to 768):
160
+ Dimensionality of the encoder layers and the pooler layer.
161
+ intermediate_size (`int`, *optional*, defaults to 3072):
162
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
163
+ num_hidden_layers (`int`, *optional*, defaults to 12):
164
+ Number of hidden layers in the Transformer encoder.
165
+ num_attention_heads (`int`, *optional*, defaults to 12):
166
+ Number of attention heads for each attention layer in the Transformer encoder.
167
+ image_size (`int`, *optional*, defaults to 224):
168
+ The size (resolution) of each image.
169
+ patch_size (`int`, *optional*, defaults to 32):
170
+ The size (resolution) of each patch.
171
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
172
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
173
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
174
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
175
+ The epsilon used by the layer normalization layers.
176
+ attention_dropout (`float`, *optional*, defaults to 0.0):
177
+ The dropout ratio for the attention probabilities.
178
+ initializer_range (`float`, *optional*, defaults to 0.02):
179
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
180
+ initializer_factor (`float`, *optional*, defaults to 1):
181
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
182
+ testing).
183
+
184
+ Example:
185
+
186
+ ```python
187
+ >>> from transformers import CLIPVisionConfig, CLIPVisionModel
188
+
189
+ >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
190
+ >>> configuration = CLIPVisionConfig()
191
+
192
+ >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
193
+ >>> model = CLIPVisionModel(configuration)
194
+
195
+ >>> # Accessing the model configuration
196
+ >>> configuration = model.config
197
+ ```"""
198
+
199
+ model_type = "clip_vision_model"
200
+
201
+ def __init__(
202
+ self,
203
+ hidden_size=768,
204
+ intermediate_size=3072,
205
+ projection_dim=512,
206
+ num_hidden_layers=12,
207
+ num_attention_heads=12,
208
+ num_channels=3,
209
+ image_size=224,
210
+ patch_size=32,
211
+ hidden_act="gelu",
212
+ layer_norm_eps=1e-5,
213
+ attention_dropout=0.0,
214
+ initializer_range=0.02,
215
+ initializer_factor=1.0,
216
+ q_bias=True,
217
+ k_bias=True,
218
+ v_bias=True,
219
+ post_layernorm=False,
220
+ **kwargs,
221
+ ):
222
+ super().__init__(**kwargs)
223
+
224
+ self.hidden_size = hidden_size
225
+ self.intermediate_size = intermediate_size
226
+ self.projection_dim = projection_dim
227
+ self.num_hidden_layers = num_hidden_layers
228
+ self.num_attention_heads = num_attention_heads
229
+ self.num_channels = num_channels
230
+ self.patch_size = patch_size
231
+ self.image_size = image_size
232
+ self.initializer_range = initializer_range
233
+ self.initializer_factor = initializer_factor
234
+ self.q_bias=q_bias
235
+ self.k_bias=k_bias
236
+ self.v_bias=v_bias
237
+ self.post_layernorm = post_layernorm
238
+ self.attention_dropout = attention_dropout
239
+ self.layer_norm_eps = layer_norm_eps
240
+ self.hidden_act = hidden_act
241
+
242
+ @classmethod
243
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
244
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
245
+
246
+ # get the vision config dict if we are loading from CLIPConfig
247
+ if config_dict.get("model_type") == "clip":
248
+ config_dict = config_dict["vision_config"]
249
+
250
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
251
+ logger.warning(
252
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
253
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
254
+ )
255
+
256
+ return cls.from_dict(config_dict, **kwargs)
257
+
258
+
259
+ class CLIPConfig(PretrainedConfig):
260
+ r"""
261
+ [`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
262
+ a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
263
+ a configuration with the defaults will yield a similar configuration to that of the CLIP
264
+ [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
265
+
266
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
267
+ documentation from [`PretrainedConfig`] for more information.
268
+
269
+ Args:
270
+ text_config (`dict`, *optional*):
271
+ Dictionary of configuration options used to initialize [`CLIPTextConfig`].
272
+ vision_config (`dict`, *optional*):
273
+ Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
274
+ projection_dim (`int`, *optional*, defaults to 512):
275
+ Dimentionality of text and vision projection layers.
276
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
277
+ The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
278
+ kwargs (*optional*):
279
+ Dictionary of keyword arguments.
280
+
281
+ Example:
282
+
283
+ ```python
284
+ >>> from transformers import CLIPConfig, CLIPModel
285
+
286
+ >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
287
+ >>> configuration = CLIPConfig()
288
+
289
+ >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
290
+ >>> model = CLIPModel(configuration)
291
+
292
+ >>> # Accessing the model configuration
293
+ >>> configuration = model.config
294
+
295
+ >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
296
+ >>> from transformers import CLIPTextConfig, CLIPVisionConfig
297
+
298
+ >>> # Initializing a CLIPText and CLIPVision configuration
299
+ >>> config_text = CLIPTextConfig()
300
+ >>> config_vision = CLIPVisionConfig()
301
+
302
+ >>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
303
+ ```"""
304
+
305
+ model_type = "clip"
306
+ is_composition = True
307
+
308
+ def __init__(
309
+ self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
310
+ ):
311
+ # If `_config_dict` exist, we use them for the backward compatibility.
312
+ # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
313
+ # of confusion!).
314
+ text_config_dict = kwargs.pop("text_config_dict", None)
315
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
316
+
317
+ super().__init__(**kwargs)
318
+
319
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
320
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
321
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
322
+ if text_config_dict is not None:
323
+ if text_config is None:
324
+ text_config = {}
325
+
326
+ # This is the complete result when using `text_config_dict`.
327
+ _text_config_dict = CLIPTextConfig(**text_config_dict).to_dict()
328
+
329
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
330
+ for key, value in _text_config_dict.items():
331
+ if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
332
+ # If specified in `text_config_dict`
333
+ if key in text_config_dict:
334
+ message = (
335
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
336
+ f'The value `text_config_dict["{key}"]` will be used instead.'
337
+ )
338
+ # If inferred from default argument values (just to be super careful)
339
+ else:
340
+ message = (
341
+ f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
342
+ f'value `text_config["{key}"]` will be overriden.'
343
+ )
344
+ logger.warning(message)
345
+
346
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
347
+ text_config.update(_text_config_dict)
348
+
349
+ if vision_config_dict is not None:
350
+ if vision_config is None:
351
+ vision_config = {}
352
+
353
+ # This is the complete result when using `vision_config_dict`.
354
+ _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
355
+ # convert keys to string instead of integer
356
+ if "id2label" in _vision_config_dict:
357
+ _vision_config_dict["id2label"] = {
358
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
359
+ }
360
+
361
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
362
+ for key, value in _vision_config_dict.items():
363
+ if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
364
+ # If specified in `vision_config_dict`
365
+ if key in vision_config_dict:
366
+ message = (
367
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
368
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
369
+ )
370
+ # If inferred from default argument values (just to be super careful)
371
+ else:
372
+ message = (
373
+ f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
374
+ f'The value `vision_config["{key}"]` will be overriden.'
375
+ )
376
+ logger.warning(message)
377
+
378
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
379
+ vision_config.update(_vision_config_dict)
380
+
381
+ if text_config is None:
382
+ text_config = {}
383
+ logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
384
+
385
+ if vision_config is None:
386
+ vision_config = {}
387
+ logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
388
+
389
+ self.text_config = CLIPTextConfig(**text_config)
390
+ self.vision_config = CLIPVisionConfig(**vision_config)
391
+
392
+ self.projection_dim = projection_dim
393
+ self.logit_scale_init_value = logit_scale_init_value
394
+ self.initializer_factor = 1.0
395
+
396
+ @classmethod
397
+ def from_text_vision_configs(cls, text_config: CLIPTextConfig, vision_config: CLIPVisionConfig, **kwargs):
398
+ r"""
399
+ Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
400
+ configuration.
401
+
402
+ Returns:
403
+ [`CLIPConfig`]: An instance of a configuration object
404
+ """
405
+
406
+ return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
407
+
408
+ def to_dict(self):
409
+ """
410
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
411
+
412
+ Returns:
413
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
414
+ """
415
+ output = copy.deepcopy(self.__dict__)
416
+ output["text_config"] = self.text_config.to_dict()
417
+ output["vision_config"] = self.vision_config.to_dict()
418
+ output["model_type"] = self.__class__.model_type
419
+ return output
420
+
modeling_clip.py ADDED
@@ -0,0 +1,1598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The OpenAI Team Authors and The HuggingFace 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
+ """PyTorch CLIP model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Any, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.modeling_attn_mask_utils import _create_4d_causal_attention_mask, _prepare_4d_attention_mask
27
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_2
30
+ from transformers.utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ is_flash_attn_2_available,
36
+ is_flash_attn_greater_or_equal_2_10,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+ from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
41
+
42
+
43
+ if is_flash_attn_2_available():
44
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ # General docstring
50
+ _CONFIG_FOR_DOC = "CLIPConfig"
51
+ _CHECKPOINT_FOR_DOC = "openai/clip-vit-base-patch32"
52
+
53
+ # Image classification docstring
54
+ _IMAGE_CLASS_CHECKPOINT = "openai/clip-vit-base-patch32"
55
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "LABEL_0"
56
+
57
+
58
+ # contrastive loss function, adapted from
59
+ # https://sachinruk.github.io/blog/2021-03-07-clip.html
60
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
61
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
62
+
63
+
64
+ def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
65
+ caption_loss = contrastive_loss(similarity)
66
+ image_loss = contrastive_loss(similarity.t())
67
+ return (caption_loss + image_loss) / 2.0
68
+
69
+
70
+ @dataclass
71
+ class CLIPVisionModelOutput(ModelOutput):
72
+ """
73
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
74
+
75
+ Args:
76
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
77
+ The image embeddings obtained by applying the projection layer to the pooler_output.
78
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
79
+ Sequence of hidden-states at the output of the last layer of the model.
80
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
81
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
82
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
83
+
84
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
85
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
86
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
87
+ sequence_length)`.
88
+
89
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
90
+ heads.
91
+ """
92
+
93
+ image_embeds: Optional[torch.FloatTensor] = None
94
+ last_hidden_state: torch.FloatTensor = None
95
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
96
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
97
+
98
+
99
+ @dataclass
100
+ class CLIPTextModelOutput(ModelOutput):
101
+ """
102
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
103
+
104
+ Args:
105
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
106
+ The text embeddings obtained by applying the projection layer to the pooler_output.
107
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
108
+ Sequence of hidden-states at the output of the last layer of the model.
109
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
110
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
111
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
112
+
113
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
114
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
115
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
116
+ sequence_length)`.
117
+
118
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
119
+ heads.
120
+ """
121
+
122
+ text_embeds: Optional[torch.FloatTensor] = None
123
+ last_hidden_state: torch.FloatTensor = None
124
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
125
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
126
+
127
+
128
+ @dataclass
129
+ class CLIPOutput(ModelOutput):
130
+ """
131
+ Args:
132
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
133
+ Contrastive loss for image-text similarity.
134
+ logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
135
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
136
+ similarity scores.
137
+ logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
138
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
139
+ similarity scores.
140
+ text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
141
+ The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
142
+ image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
143
+ The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
144
+ text_model_output(`BaseModelOutputWithPooling`):
145
+ The output of the [`CLIPTextModel`].
146
+ vision_model_output(`BaseModelOutputWithPooling`):
147
+ The output of the [`CLIPVisionModel`].
148
+ """
149
+
150
+ loss: Optional[torch.FloatTensor] = None
151
+ logits_per_image: torch.FloatTensor = None
152
+ logits_per_text: torch.FloatTensor = None
153
+ text_embeds: torch.FloatTensor = None
154
+ image_embeds: torch.FloatTensor = None
155
+ text_model_output: BaseModelOutputWithPooling = None
156
+ vision_model_output: BaseModelOutputWithPooling = None
157
+
158
+ def to_tuple(self) -> Tuple[Any]:
159
+ return tuple(
160
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
161
+ for k in self.keys()
162
+ )
163
+
164
+
165
+ class CLIPVisionEmbeddings(nn.Module):
166
+ def __init__(self, config: CLIPVisionConfig):
167
+ super().__init__()
168
+ self.config = config
169
+ self.embed_dim = config.hidden_size
170
+ self.image_size = config.image_size
171
+ self.patch_size = config.patch_size
172
+
173
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
174
+
175
+ self.patch_embedding = nn.Conv2d(
176
+ in_channels=config.num_channels,
177
+ out_channels=self.embed_dim,
178
+ kernel_size=self.patch_size,
179
+ stride=self.patch_size,
180
+ bias=False,
181
+ )
182
+
183
+ self.num_patches = (self.image_size // self.patch_size) ** 2
184
+ self.num_positions = self.num_patches + 1
185
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
186
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
187
+
188
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
189
+ batch_size = pixel_values.shape[0]
190
+ target_dtype = self.patch_embedding.weight.dtype
191
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
192
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
193
+
194
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
195
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
196
+ embeddings = embeddings + self.position_embedding(self.position_ids)
197
+ return embeddings
198
+
199
+
200
+ class CLIPTextEmbeddings(nn.Module):
201
+ def __init__(self, config: CLIPTextConfig):
202
+ super().__init__()
203
+ embed_dim = config.hidden_size
204
+
205
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
206
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
207
+
208
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
209
+ self.register_buffer(
210
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
211
+ )
212
+
213
+ def forward(
214
+ self,
215
+ input_ids: Optional[torch.LongTensor] = None,
216
+ position_ids: Optional[torch.LongTensor] = None,
217
+ inputs_embeds: Optional[torch.FloatTensor] = None,
218
+ ) -> torch.Tensor:
219
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
220
+
221
+ if position_ids is None:
222
+ position_ids = self.position_ids[:, :seq_length]
223
+
224
+ if inputs_embeds is None:
225
+ inputs_embeds = self.token_embedding(input_ids)
226
+
227
+ position_embeddings = self.position_embedding(position_ids)
228
+ embeddings = inputs_embeds + position_embeddings
229
+
230
+ return embeddings
231
+
232
+
233
+ class CLIPAttention(nn.Module):
234
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
235
+
236
+ def __init__(self, config):
237
+ super().__init__()
238
+ self.config = config
239
+ self.embed_dim = config.hidden_size
240
+ self.num_heads = config.num_attention_heads
241
+ self.head_dim = self.embed_dim // self.num_heads
242
+ if self.head_dim * self.num_heads != self.embed_dim:
243
+ raise ValueError(
244
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
245
+ f" {self.num_heads})."
246
+ )
247
+ self.scale = self.head_dim**-0.5
248
+ self.dropout = config.attention_dropout
249
+
250
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
251
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
252
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
253
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
254
+
255
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
256
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
257
+
258
+ def forward(
259
+ self,
260
+ hidden_states: torch.Tensor,
261
+ attention_mask: Optional[torch.Tensor] = None,
262
+ causal_attention_mask: Optional[torch.Tensor] = None,
263
+ output_attentions: Optional[bool] = False,
264
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
265
+ """Input shape: Batch x Time x Channel"""
266
+
267
+ bsz, tgt_len, embed_dim = hidden_states.size()
268
+
269
+ # get query proj
270
+ query_states = self.q_proj(hidden_states) * self.scale
271
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
272
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
273
+
274
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
275
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
276
+ key_states = key_states.view(*proj_shape)
277
+ value_states = value_states.view(*proj_shape)
278
+
279
+ src_len = key_states.size(1)
280
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
281
+
282
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
283
+ raise ValueError(
284
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
285
+ f" {attn_weights.size()}"
286
+ )
287
+
288
+ # apply the causal_attention_mask first
289
+ if causal_attention_mask is not None:
290
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
291
+ raise ValueError(
292
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
293
+ f" {causal_attention_mask.size()}"
294
+ )
295
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
296
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
297
+
298
+ if attention_mask is not None:
299
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
300
+ raise ValueError(
301
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
302
+ )
303
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
304
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
305
+
306
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
307
+
308
+ if output_attentions:
309
+ # this operation is a bit akward, but it's required to
310
+ # make sure that attn_weights keeps its gradient.
311
+ # In order to do so, attn_weights have to reshaped
312
+ # twice and have to be reused in the following
313
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
314
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
315
+ else:
316
+ attn_weights_reshaped = None
317
+
318
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
319
+
320
+ attn_output = torch.bmm(attn_probs, value_states)
321
+
322
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
323
+ raise ValueError(
324
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
325
+ f" {attn_output.size()}"
326
+ )
327
+
328
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
329
+ attn_output = attn_output.transpose(1, 2)
330
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
331
+
332
+ attn_output = self.out_proj(attn_output)
333
+
334
+ return attn_output, attn_weights_reshaped
335
+
336
+
337
+ class CLIPFlashAttention2(CLIPAttention):
338
+ """
339
+ CLIPAttention flash attention module. This module inherits from `CLIPAttention` as the weights of the module stays
340
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
341
+ flash attention and deal with padding tokens in case the input contains any of them.
342
+ """
343
+
344
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
345
+ def __init__(self, *args, **kwargs):
346
+ super().__init__(*args, **kwargs)
347
+
348
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
349
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
350
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
351
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
352
+
353
+ # Adapted from transformers.models.llama.modeling_llama.LlamaFlashAttention2.forward
354
+ def forward(
355
+ self,
356
+ hidden_states: torch.Tensor,
357
+ attention_mask: Optional[torch.Tensor] = None,
358
+ causal_attention_mask: Optional[torch.Tensor] = None,
359
+ output_attentions: Optional[bool] = False,
360
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
361
+ output_attentions = False
362
+
363
+ batch_size, q_len, _ = hidden_states.size()
364
+
365
+ query_states = self.q_proj(hidden_states)
366
+ key_states = self.k_proj(hidden_states)
367
+ value_states = self.v_proj(hidden_states)
368
+
369
+ # Flash attention requires the input to have the shape
370
+ # batch_size x seq_length x head_dim x hidden_dim
371
+ # therefore we just need to keep the original shape
372
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim)
373
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim)
374
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim)
375
+
376
+ dropout_rate = self.dropout if self.training else 0.0
377
+
378
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
379
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
380
+ # cast them back in the correct dtype just to be sure everything works as expected.
381
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
382
+ # in fp32.
383
+
384
+ input_dtype = query_states.dtype
385
+ if input_dtype == torch.float32:
386
+ if torch.is_autocast_enabled():
387
+ target_dtype = torch.get_autocast_gpu_dtype()
388
+ # Handle the case where the model is quantized
389
+ elif hasattr(self.config, "_pre_quantization_dtype"):
390
+ target_dtype = self.config._pre_quantization_dtype
391
+ else:
392
+ target_dtype = self.q_proj.weight.dtype
393
+
394
+ logger.warning_once(
395
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
396
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
397
+ f" {target_dtype}."
398
+ )
399
+
400
+ query_states = query_states.to(target_dtype)
401
+ key_states = key_states.to(target_dtype)
402
+ value_states = value_states.to(target_dtype)
403
+
404
+ attn_output = _flash_attention_forward(
405
+ query_states,
406
+ key_states,
407
+ value_states,
408
+ attention_mask,
409
+ q_len,
410
+ dropout=dropout_rate,
411
+ is_causal=causal_attention_mask is not None,
412
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
413
+ )
414
+
415
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim).contiguous()
416
+ attn_output = self.out_proj(attn_output)
417
+
418
+ if not output_attentions:
419
+ attn_weights = None
420
+
421
+ return attn_output, attn_weights
422
+
423
+
424
+ class CLIPSdpaAttention(CLIPAttention):
425
+ """
426
+ SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
427
+ `CLIPAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
428
+ SDPA API.
429
+ """
430
+
431
+ # Adapted from CLIPAttention.forward
432
+ def forward(
433
+ self,
434
+ hidden_states: torch.Tensor,
435
+ attention_mask: Optional[torch.Tensor] = None,
436
+ causal_attention_mask: Optional[torch.Tensor] = None,
437
+ output_attentions: Optional[bool] = False,
438
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
439
+ if output_attentions:
440
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
441
+ logger.warning_once(
442
+ "CLIPModel is using CLIPSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not "
443
+ "support `output_attentions=True`. Falling back to the manual attention implementation, but specifying "
444
+ "the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can "
445
+ 'be removed using the argument `attn_implementation="eager"` when loading the model.'
446
+ )
447
+ return super().forward(
448
+ hidden_states=hidden_states,
449
+ attention_mask=attention_mask,
450
+ causal_attention_mask=causal_attention_mask,
451
+ output_attentions=output_attentions,
452
+ )
453
+
454
+ # CLIP text model uses both `causal_attention_mask` and `attention_mask`
455
+ if attention_mask is not None and causal_attention_mask is not None:
456
+ attn_mask = attention_mask + causal_attention_mask
457
+ elif causal_attention_mask is not None:
458
+ attn_mask = causal_attention_mask
459
+ else:
460
+ attn_mask = attention_mask
461
+
462
+ bsz, tgt_len, embed_dim = hidden_states.size()
463
+
464
+ query_states = self.q_proj(hidden_states)
465
+ key_states = self.k_proj(hidden_states)
466
+ value_states = self.v_proj(hidden_states)
467
+
468
+ query_states = query_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
469
+ key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
470
+ value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
471
+
472
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
473
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
474
+ if not is_torch_greater_or_equal_than_2_2 and query_states.device.type == "cuda" and attn_mask is not None:
475
+ query_states = query_states.contiguous()
476
+ key_states = key_states.contiguous()
477
+ value_states = value_states.contiguous()
478
+
479
+ # CLIP text model uses both `causal_attention_mask` and `attention_mask` sequentially.
480
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
481
+ query_states,
482
+ key_states,
483
+ value_states,
484
+ attn_mask=attn_mask,
485
+ dropout_p=self.dropout if self.training else 0.0,
486
+ scale=self.scale,
487
+ )
488
+
489
+ attn_output = attn_output.transpose(1, 2)
490
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
491
+
492
+ attn_output = self.out_proj(attn_output)
493
+
494
+ return attn_output, None
495
+
496
+
497
+ CLIP_ATTENTION_CLASSES = {
498
+ "eager": CLIPAttention,
499
+ "sdpa": CLIPSdpaAttention,
500
+ "flash_attention_2": CLIPFlashAttention2,
501
+ }
502
+
503
+
504
+ class CLIPMLP(nn.Module):
505
+ def __init__(self, config):
506
+ super().__init__()
507
+ self.config = config
508
+ self.activation_fn = ACT2FN[config.hidden_act]
509
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
510
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
511
+
512
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
513
+ hidden_states = self.fc1(hidden_states)
514
+ hidden_states = self.activation_fn(hidden_states)
515
+ hidden_states = self.fc2(hidden_states)
516
+ return hidden_states
517
+
518
+
519
+ class CLIPEncoderLayer(nn.Module):
520
+ def __init__(self, config: CLIPConfig):
521
+ super().__init__()
522
+ self.embed_dim = config.hidden_size
523
+ self.self_attn = CLIP_ATTENTION_CLASSES[config._attn_implementation](config)
524
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
525
+ self.mlp = CLIPMLP(config)
526
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
527
+
528
+ def forward(
529
+ self,
530
+ hidden_states: torch.Tensor,
531
+ attention_mask: torch.Tensor,
532
+ causal_attention_mask: torch.Tensor,
533
+ output_attentions: Optional[bool] = False,
534
+ ) -> Tuple[torch.FloatTensor]:
535
+ """
536
+ Args:
537
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
538
+ attention_mask (`torch.FloatTensor`): attention mask of size
539
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
540
+ `(config.encoder_attention_heads,)`.
541
+ output_attentions (`bool`, *optional*):
542
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
543
+ returned tensors for more detail.
544
+ """
545
+ residual = hidden_states
546
+
547
+ hidden_states = self.layer_norm1(hidden_states)
548
+ hidden_states, attn_weights = self.self_attn(
549
+ hidden_states=hidden_states,
550
+ attention_mask=attention_mask,
551
+ causal_attention_mask=causal_attention_mask,
552
+ output_attentions=output_attentions,
553
+ )
554
+ hidden_states = residual + hidden_states
555
+
556
+ residual = hidden_states
557
+ hidden_states = self.layer_norm2(hidden_states)
558
+ hidden_states = self.mlp(hidden_states)
559
+ hidden_states = residual + hidden_states
560
+
561
+ outputs = (hidden_states,)
562
+
563
+ if output_attentions:
564
+ outputs += (attn_weights,)
565
+
566
+ return outputs
567
+
568
+
569
+ class CLIPPreTrainedModel(PreTrainedModel):
570
+ """
571
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
572
+ models.
573
+ """
574
+
575
+ config_class = CLIPConfig
576
+ base_model_prefix = "clip"
577
+ supports_gradient_checkpointing = True
578
+ _supports_sdpa = True
579
+ _supports_flash_attn_2 = True
580
+
581
+ def _init_weights(self, module):
582
+ """Initialize the weights"""
583
+ factor = self.config.initializer_factor
584
+ if isinstance(module, CLIPTextEmbeddings):
585
+ module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
586
+ module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
587
+ elif isinstance(module, CLIPVisionEmbeddings):
588
+ factor = self.config.initializer_factor
589
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
590
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
591
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
592
+ elif isinstance(module, CLIPAttention):
593
+ factor = self.config.initializer_factor
594
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
595
+ out_proj_std = (module.embed_dim**-0.5) * factor
596
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
597
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
598
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
599
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
600
+ elif isinstance(module, CLIPMLP):
601
+ factor = self.config.initializer_factor
602
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
603
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
604
+ nn.init.normal_(module.fc1.weight, std=fc_std)
605
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
606
+ elif isinstance(module, CLIPModel):
607
+ pass
608
+ # nn.init.normal_(
609
+ # module.text_projection.weight,
610
+ # std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
611
+ # )
612
+ # nn.init.normal_(
613
+ # module.visual_projection.weight,
614
+ # std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
615
+ # )
616
+ elif isinstance(module, CLIPVisionModelWithProjection):
617
+ nn.init.normal_(
618
+ module.visual_projection.weight,
619
+ std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
620
+ )
621
+ elif isinstance(module, CLIPTextModelWithProjection):
622
+ nn.init.normal_(
623
+ module.text_projection.weight,
624
+ std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
625
+ )
626
+ elif isinstance(module, CLIPForImageClassification):
627
+ nn.init.normal_(
628
+ module.classifier.weight,
629
+ std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
630
+ )
631
+
632
+ if isinstance(module, nn.LayerNorm):
633
+ module.bias.data.zero_()
634
+ module.weight.data.fill_(1.0)
635
+ if isinstance(module, nn.Linear) and module.bias is not None:
636
+ module.bias.data.zero_()
637
+
638
+
639
+ CLIP_START_DOCSTRING = r"""
640
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
641
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
642
+ etc.)
643
+
644
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
645
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
646
+ and behavior.
647
+
648
+ Parameters:
649
+ config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
650
+ Initializing with a config file does not load the weights associated with the model, only the
651
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
652
+ """
653
+
654
+ CLIP_TEXT_INPUTS_DOCSTRING = r"""
655
+ Args:
656
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
657
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
658
+ it.
659
+
660
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
661
+ [`PreTrainedTokenizer.__call__`] for details.
662
+
663
+ [What are input IDs?](../glossary#input-ids)
664
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
665
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
666
+
667
+ - 1 for tokens that are **not masked**,
668
+ - 0 for tokens that are **masked**.
669
+
670
+ [What are attention masks?](../glossary#attention-mask)
671
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
672
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
673
+ config.max_position_embeddings - 1]`.
674
+
675
+ [What are position IDs?](../glossary#position-ids)
676
+ output_attentions (`bool`, *optional*):
677
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
678
+ tensors for more detail.
679
+ output_hidden_states (`bool`, *optional*):
680
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
681
+ more detail.
682
+ return_dict (`bool`, *optional*):
683
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
684
+ """
685
+
686
+ CLIP_VISION_INPUTS_DOCSTRING = r"""
687
+ Args:
688
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
689
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
690
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
691
+ output_attentions (`bool`, *optional*):
692
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
693
+ tensors for more detail.
694
+ output_hidden_states (`bool`, *optional*):
695
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
696
+ more detail.
697
+ return_dict (`bool`, *optional*):
698
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
699
+ """
700
+
701
+ CLIP_INPUTS_DOCSTRING = r"""
702
+ Args:
703
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
704
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
705
+ it.
706
+
707
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
708
+ [`PreTrainedTokenizer.__call__`] for details.
709
+
710
+ [What are input IDs?](../glossary#input-ids)
711
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
712
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
713
+
714
+ - 1 for tokens that are **not masked**,
715
+ - 0 for tokens that are **masked**.
716
+
717
+ [What are attention masks?](../glossary#attention-mask)
718
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
719
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
720
+ config.max_position_embeddings - 1]`.
721
+
722
+ [What are position IDs?](../glossary#position-ids)
723
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
724
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
725
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
726
+ return_loss (`bool`, *optional*):
727
+ Whether or not to return the contrastive loss.
728
+ output_attentions (`bool`, *optional*):
729
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
730
+ tensors for more detail.
731
+ output_hidden_states (`bool`, *optional*):
732
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
733
+ more detail.
734
+ return_dict (`bool`, *optional*):
735
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
736
+ """
737
+
738
+
739
+ class CLIPEncoder(nn.Module):
740
+ """
741
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
742
+ [`CLIPEncoderLayer`].
743
+
744
+ Args:
745
+ config: CLIPConfig
746
+ """
747
+
748
+ def __init__(self, config: CLIPConfig):
749
+ super().__init__()
750
+ self.config = config
751
+ self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
752
+ self.gradient_checkpointing = False
753
+
754
+ def forward(
755
+ self,
756
+ inputs_embeds,
757
+ attention_mask: Optional[torch.Tensor] = None,
758
+ causal_attention_mask: Optional[torch.Tensor] = None,
759
+ output_attentions: Optional[bool] = None,
760
+ output_hidden_states: Optional[bool] = None,
761
+ return_dict: Optional[bool] = None,
762
+ ) -> Union[Tuple, BaseModelOutput]:
763
+ r"""
764
+ Args:
765
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
766
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
767
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
768
+ than the model's internal embedding lookup matrix.
769
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
770
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
771
+
772
+ - 1 for tokens that are **not masked**,
773
+ - 0 for tokens that are **masked**.
774
+
775
+ [What are attention masks?](../glossary#attention-mask)
776
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
777
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
778
+
779
+ - 1 for tokens that are **not masked**,
780
+ - 0 for tokens that are **masked**.
781
+
782
+ [What are attention masks?](../glossary#attention-mask)
783
+ output_attentions (`bool`, *optional*):
784
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
785
+ returned tensors for more detail.
786
+ output_hidden_states (`bool`, *optional*):
787
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
788
+ for more detail.
789
+ return_dict (`bool`, *optional*):
790
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
791
+ """
792
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
793
+ output_hidden_states = (
794
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
795
+ )
796
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
797
+
798
+ encoder_states = () if output_hidden_states else None
799
+ all_attentions = () if output_attentions else None
800
+
801
+ hidden_states = inputs_embeds
802
+ for idx, encoder_layer in enumerate(self.layers):
803
+ if output_hidden_states:
804
+ encoder_states = encoder_states + (hidden_states,)
805
+ if self.gradient_checkpointing and self.training:
806
+ layer_outputs = self._gradient_checkpointing_func(
807
+ encoder_layer.__call__,
808
+ hidden_states,
809
+ attention_mask,
810
+ causal_attention_mask,
811
+ output_attentions,
812
+ )
813
+ else:
814
+ layer_outputs = encoder_layer(
815
+ hidden_states,
816
+ attention_mask,
817
+ causal_attention_mask,
818
+ output_attentions=output_attentions,
819
+ )
820
+
821
+ hidden_states = layer_outputs[0]
822
+
823
+ if output_attentions:
824
+ all_attentions = all_attentions + (layer_outputs[1],)
825
+
826
+ if output_hidden_states:
827
+ encoder_states = encoder_states + (hidden_states,)
828
+
829
+ if not return_dict:
830
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
831
+ return BaseModelOutput(
832
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
833
+ )
834
+
835
+
836
+ class CLIPTextTransformer(nn.Module):
837
+ def __init__(self, config: CLIPTextConfig):
838
+ super().__init__()
839
+ self.config = config
840
+ embed_dim = config.hidden_size
841
+ self.embeddings = CLIPTextEmbeddings(config)
842
+ self.encoder = CLIPEncoder(config)
843
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
844
+
845
+ # For `pooled_output` computation
846
+ self.eos_token_id = config.eos_token_id
847
+
848
+ # For attention mask, it differs between `flash_attention_2` and other attention implementations
849
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
850
+
851
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
852
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
853
+ def forward(
854
+ self,
855
+ input_ids: Optional[torch.Tensor] = None,
856
+ attention_mask: Optional[torch.Tensor] = None,
857
+ position_ids: Optional[torch.Tensor] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ output_hidden_states: Optional[bool] = None,
860
+ return_dict: Optional[bool] = None,
861
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
862
+ r"""
863
+ Returns:
864
+
865
+ """
866
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
867
+ output_hidden_states = (
868
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
869
+ )
870
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
871
+
872
+ if input_ids is None:
873
+ raise ValueError("You have to specify input_ids")
874
+
875
+ input_shape = input_ids.size()
876
+ input_ids = input_ids.view(-1, input_shape[-1])
877
+
878
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
879
+
880
+ # CLIP's text model uses causal mask, prepare it here.
881
+ # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
882
+ causal_attention_mask = _create_4d_causal_attention_mask(
883
+ input_shape, hidden_states.dtype, device=hidden_states.device
884
+ )
885
+
886
+ # expand attention_mask
887
+ if attention_mask is not None and not self._use_flash_attention_2:
888
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
889
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
890
+
891
+ encoder_outputs = self.encoder(
892
+ inputs_embeds=hidden_states,
893
+ attention_mask=attention_mask,
894
+ causal_attention_mask=causal_attention_mask,
895
+ output_attentions=output_attentions,
896
+ output_hidden_states=output_hidden_states,
897
+ return_dict=return_dict,
898
+ )
899
+
900
+ last_hidden_state = encoder_outputs[0]
901
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
902
+
903
+ if self.eos_token_id == 2:
904
+ # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
905
+ # A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
906
+ # ------------------------------------------------------------
907
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
908
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
909
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
910
+ pooled_output = last_hidden_state[
911
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
912
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
913
+ ]
914
+ else:
915
+ # The config gets updated `eos_token_id` from PR #24773 (so the use of exta new tokens is possible)
916
+ pooled_output = last_hidden_state[
917
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
918
+ # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
919
+ # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer)
920
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
921
+ .int()
922
+ .argmax(dim=-1),
923
+ ]
924
+
925
+ if not return_dict:
926
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
927
+
928
+ return BaseModelOutputWithPooling(
929
+ last_hidden_state=last_hidden_state,
930
+ pooler_output=pooled_output,
931
+ hidden_states=encoder_outputs.hidden_states,
932
+ attentions=encoder_outputs.attentions,
933
+ )
934
+
935
+
936
+ @add_start_docstrings(
937
+ """The text model from CLIP without any head or projection on top.""",
938
+ CLIP_START_DOCSTRING,
939
+ )
940
+ class CLIPTextModel(CLIPPreTrainedModel):
941
+ config_class = CLIPTextConfig
942
+
943
+ _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
944
+
945
+ def __init__(self, config: CLIPTextConfig):
946
+ super().__init__(config)
947
+ self.text_model = CLIPTextTransformer(config)
948
+ # Initialize weights and apply final processing
949
+ self.post_init()
950
+
951
+ def get_input_embeddings(self) -> nn.Module:
952
+ return self.text_model.embeddings.token_embedding
953
+
954
+ def set_input_embeddings(self, value):
955
+ self.text_model.embeddings.token_embedding = value
956
+
957
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
958
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
959
+ def forward(
960
+ self,
961
+ input_ids: Optional[torch.Tensor] = None,
962
+ attention_mask: Optional[torch.Tensor] = None,
963
+ position_ids: Optional[torch.Tensor] = None,
964
+ output_attentions: Optional[bool] = None,
965
+ output_hidden_states: Optional[bool] = None,
966
+ return_dict: Optional[bool] = None,
967
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
968
+ r"""
969
+ Returns:
970
+
971
+ Examples:
972
+
973
+ ```python
974
+ >>> from transformers import AutoTokenizer, CLIPTextModel
975
+
976
+ >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
977
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
978
+
979
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
980
+
981
+ >>> outputs = model(**inputs)
982
+ >>> last_hidden_state = outputs.last_hidden_state
983
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
984
+ ```"""
985
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
986
+
987
+ return self.text_model(
988
+ input_ids=input_ids,
989
+ attention_mask=attention_mask,
990
+ position_ids=position_ids,
991
+ output_attentions=output_attentions,
992
+ output_hidden_states=output_hidden_states,
993
+ return_dict=return_dict,
994
+ )
995
+
996
+
997
+ class CLIPVisionTransformer(nn.Module):
998
+ def __init__(self, config: CLIPVisionConfig):
999
+ super().__init__()
1000
+ self.config = config
1001
+ embed_dim = config.hidden_size
1002
+
1003
+ self.embeddings = CLIPVisionEmbeddings(config)
1004
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1005
+ self.encoder = CLIPEncoder(config)
1006
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1007
+
1008
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1009
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
1010
+ def forward(
1011
+ self,
1012
+ pixel_values: Optional[torch.FloatTensor] = None,
1013
+ output_attentions: Optional[bool] = None,
1014
+ output_hidden_states: Optional[bool] = None,
1015
+ return_dict: Optional[bool] = None,
1016
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1017
+ r"""
1018
+ Returns:
1019
+
1020
+ """
1021
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1022
+ output_hidden_states = (
1023
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1024
+ )
1025
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1026
+
1027
+ if pixel_values is None:
1028
+ raise ValueError("You have to specify pixel_values")
1029
+
1030
+ hidden_states = self.embeddings(pixel_values)
1031
+ hidden_states = self.pre_layrnorm(hidden_states)
1032
+
1033
+ encoder_outputs = self.encoder(
1034
+ inputs_embeds=hidden_states,
1035
+ output_attentions=output_attentions,
1036
+ output_hidden_states=output_hidden_states,
1037
+ return_dict=return_dict,
1038
+ )
1039
+
1040
+ last_hidden_state = encoder_outputs[0]
1041
+ pooled_output = last_hidden_state[:, 0, :]
1042
+ pooled_output = self.post_layernorm(pooled_output)
1043
+
1044
+ if not return_dict:
1045
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1046
+
1047
+ return BaseModelOutputWithPooling(
1048
+ last_hidden_state=last_hidden_state,
1049
+ pooler_output=pooled_output,
1050
+ hidden_states=encoder_outputs.hidden_states,
1051
+ attentions=encoder_outputs.attentions,
1052
+ )
1053
+
1054
+
1055
+ @add_start_docstrings(
1056
+ """The vision model from CLIP without any head or projection on top.""",
1057
+ CLIP_START_DOCSTRING,
1058
+ )
1059
+ class CLIPVisionModel(CLIPPreTrainedModel):
1060
+ config_class = CLIPVisionConfig
1061
+ main_input_name = "pixel_values"
1062
+ _no_split_modules = ["CLIPEncoderLayer"]
1063
+
1064
+ def __init__(self, config: CLIPVisionConfig):
1065
+ super().__init__(config)
1066
+ self.vision_model = CLIPVisionTransformer(config)
1067
+ # Initialize weights and apply final processing
1068
+ self.post_init()
1069
+
1070
+ def get_input_embeddings(self) -> nn.Module:
1071
+ return self.vision_model.embeddings.patch_embedding
1072
+
1073
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1074
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
1075
+ def forward(
1076
+ self,
1077
+ pixel_values: Optional[torch.FloatTensor] = None,
1078
+ output_attentions: Optional[bool] = None,
1079
+ output_hidden_states: Optional[bool] = None,
1080
+ return_dict: Optional[bool] = None,
1081
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1082
+ r"""
1083
+ Returns:
1084
+
1085
+ Examples:
1086
+
1087
+ ```python
1088
+ >>> from PIL import Image
1089
+ >>> import requests
1090
+ >>> from transformers import AutoProcessor, CLIPVisionModel
1091
+
1092
+ >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
1093
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1094
+
1095
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1096
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1097
+
1098
+ >>> inputs = processor(images=image, return_tensors="pt")
1099
+
1100
+ >>> outputs = model(**inputs)
1101
+ >>> last_hidden_state = outputs.last_hidden_state
1102
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
1103
+ ```"""
1104
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1105
+
1106
+ return self.vision_model(
1107
+ pixel_values=pixel_values,
1108
+ output_attentions=output_attentions,
1109
+ output_hidden_states=output_hidden_states,
1110
+ return_dict=return_dict,
1111
+ )
1112
+
1113
+
1114
+ @add_start_docstrings(CLIP_START_DOCSTRING)
1115
+ class CLIPModel(CLIPPreTrainedModel):
1116
+ config_class = CLIPConfig
1117
+ _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer", "CLIPVisionEmbeddings"]
1118
+
1119
+ def __init__(self, config: CLIPConfig):
1120
+ super().__init__(config)
1121
+ if not isinstance(config.vision_config, CLIPVisionConfig):
1122
+ raise TypeError(
1123
+ "config.vision_config is expected to be of type CLIPVisionConfig but is of type"
1124
+ f" {type(config.vision_config)}."
1125
+ )
1126
+
1127
+ vision_config = config.vision_config
1128
+
1129
+ self.projection_dim = config.projection_dim
1130
+ self.vision_embed_dim = vision_config.hidden_size
1131
+
1132
+ vision_model = CLIPVisionModel._from_config(vision_config, attn_implementation=config._attn_implementation)
1133
+ self.vision_model = vision_model.vision_model
1134
+
1135
+ # self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
1136
+ scale = self.vision_embed_dim ** -0.5
1137
+ self.visual_projection = nn.Parameter(scale * torch.randn(self.vision_embed_dim, self.projection_dim))
1138
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
1139
+
1140
+ # Initialize weights and apply final processing
1141
+ self.post_init()
1142
+
1143
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
1144
+ def get_text_features(
1145
+ self,
1146
+ input_ids: Optional[torch.Tensor] = None,
1147
+ attention_mask: Optional[torch.Tensor] = None,
1148
+ position_ids: Optional[torch.Tensor] = None,
1149
+ output_attentions: Optional[bool] = None,
1150
+ output_hidden_states: Optional[bool] = None,
1151
+ return_dict: Optional[bool] = None,
1152
+ ) -> torch.FloatTensor:
1153
+ r"""
1154
+ Returns:
1155
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1156
+ applying the projection layer to the pooled output of [`CLIPTextModel`].
1157
+
1158
+ Examples:
1159
+
1160
+ ```python
1161
+ >>> from transformers import AutoTokenizer, CLIPModel
1162
+
1163
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1164
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
1165
+
1166
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1167
+ >>> text_features = model.get_text_features(**inputs)
1168
+ ```"""
1169
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1170
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1171
+ output_hidden_states = (
1172
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1173
+ )
1174
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1175
+
1176
+ text_outputs = self.text_model(
1177
+ input_ids=input_ids,
1178
+ attention_mask=attention_mask,
1179
+ position_ids=position_ids,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+
1185
+ pooled_output = text_outputs[1]
1186
+ text_features = self.text_projection(pooled_output)
1187
+
1188
+ return text_features
1189
+
1190
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1191
+ def get_image_features(
1192
+ self,
1193
+ pixel_values: Optional[torch.FloatTensor] = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ ) -> torch.FloatTensor:
1198
+ r"""
1199
+ Returns:
1200
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1201
+ applying the projection layer to the pooled output of [`CLIPVisionModel`].
1202
+
1203
+ Examples:
1204
+
1205
+ ```python
1206
+ >>> from PIL import Image
1207
+ >>> import requests
1208
+ >>> from transformers import AutoProcessor, CLIPModel
1209
+
1210
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1211
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1212
+
1213
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1214
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1215
+
1216
+ >>> inputs = processor(images=image, return_tensors="pt")
1217
+
1218
+ >>> image_features = model.get_image_features(**inputs)
1219
+ ```"""
1220
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1221
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1222
+ output_hidden_states = (
1223
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1224
+ )
1225
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1226
+
1227
+ vision_outputs = self.vision_model(
1228
+ pixel_values=pixel_values,
1229
+ output_attentions=output_attentions,
1230
+ output_hidden_states=output_hidden_states,
1231
+ return_dict=return_dict,
1232
+ )
1233
+
1234
+ pooled_output = vision_outputs[1] # pooled_output
1235
+ image_features = pooled_output @ self.visual_projection
1236
+
1237
+ return image_features
1238
+
1239
+ @add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
1240
+ @replace_return_docstrings(output_type=CLIPOutput, config_class=CLIPConfig)
1241
+ def forward(
1242
+ self,
1243
+ input_ids: Optional[torch.LongTensor] = None,
1244
+ pixel_values: Optional[torch.FloatTensor] = None,
1245
+ attention_mask: Optional[torch.Tensor] = None,
1246
+ position_ids: Optional[torch.LongTensor] = None,
1247
+ return_loss: Optional[bool] = None,
1248
+ output_attentions: Optional[bool] = None,
1249
+ output_hidden_states: Optional[bool] = None,
1250
+ return_dict: Optional[bool] = None,
1251
+ ) -> Union[Tuple, CLIPOutput]:
1252
+ r"""
1253
+ Returns:
1254
+
1255
+ Examples:
1256
+
1257
+ ```python
1258
+ >>> from PIL import Image
1259
+ >>> import requests
1260
+ >>> from transformers import AutoProcessor, CLIPModel
1261
+
1262
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1263
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1264
+
1265
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1266
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1267
+
1268
+ >>> inputs = processor(
1269
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
1270
+ ... )
1271
+
1272
+ >>> outputs = model(**inputs)
1273
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
1274
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
1275
+ ```"""
1276
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1277
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1278
+ output_hidden_states = (
1279
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1280
+ )
1281
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1282
+
1283
+ vision_outputs = self.vision_model(
1284
+ pixel_values=pixel_values,
1285
+ output_attentions=output_attentions,
1286
+ output_hidden_states=output_hidden_states,
1287
+ return_dict=return_dict,
1288
+ )
1289
+
1290
+ text_outputs = self.text_model(
1291
+ input_ids=input_ids,
1292
+ attention_mask=attention_mask,
1293
+ position_ids=position_ids,
1294
+ output_attentions=output_attentions,
1295
+ output_hidden_states=output_hidden_states,
1296
+ return_dict=return_dict,
1297
+ )
1298
+
1299
+ image_embeds = vision_outputs[1]
1300
+ image_embeds = self.visual_projection(image_embeds)
1301
+
1302
+ text_embeds = text_outputs[1]
1303
+ text_embeds = self.text_projection(text_embeds)
1304
+
1305
+ # normalized features
1306
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1307
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1308
+
1309
+ # cosine similarity as logits
1310
+ logit_scale = self.logit_scale.exp()
1311
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device)) * logit_scale.to(
1312
+ text_embeds.device
1313
+ )
1314
+ logits_per_image = logits_per_text.t()
1315
+
1316
+ loss = None
1317
+ if return_loss:
1318
+ loss = clip_loss(logits_per_text)
1319
+
1320
+ if not return_dict:
1321
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1322
+ return ((loss,) + output) if loss is not None else output
1323
+
1324
+ return CLIPOutput(
1325
+ loss=loss,
1326
+ logits_per_image=logits_per_image,
1327
+ logits_per_text=logits_per_text,
1328
+ text_embeds=text_embeds,
1329
+ image_embeds=image_embeds,
1330
+ text_model_output=text_outputs,
1331
+ vision_model_output=vision_outputs,
1332
+ )
1333
+
1334
+
1335
+ @add_start_docstrings(
1336
+ """
1337
+ CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
1338
+ """,
1339
+ CLIP_START_DOCSTRING,
1340
+ )
1341
+ class CLIPTextModelWithProjection(CLIPPreTrainedModel):
1342
+ config_class = CLIPTextConfig
1343
+
1344
+ _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
1345
+
1346
+ def __init__(self, config: CLIPTextConfig):
1347
+ super().__init__(config)
1348
+
1349
+ text_model = CLIPTextModel._from_config(config, attn_implementation=config._attn_implementation)
1350
+ self.text_model = text_model.text_model
1351
+
1352
+ self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ def get_input_embeddings(self) -> nn.Module:
1358
+ return self.text_model.embeddings.token_embedding
1359
+
1360
+ def set_input_embeddings(self, value):
1361
+ self.text_model.embeddings.token_embedding = value
1362
+
1363
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
1364
+ @replace_return_docstrings(output_type=CLIPTextModelOutput, config_class=CLIPTextConfig)
1365
+ def forward(
1366
+ self,
1367
+ input_ids: Optional[torch.Tensor] = None,
1368
+ attention_mask: Optional[torch.Tensor] = None,
1369
+ position_ids: Optional[torch.Tensor] = None,
1370
+ output_attentions: Optional[bool] = None,
1371
+ output_hidden_states: Optional[bool] = None,
1372
+ return_dict: Optional[bool] = None,
1373
+ ) -> Union[Tuple, CLIPTextModelOutput]:
1374
+ r"""
1375
+ Returns:
1376
+
1377
+ Examples:
1378
+
1379
+ ```python
1380
+ >>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
1381
+
1382
+ >>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
1383
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
1384
+
1385
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1386
+
1387
+ >>> outputs = model(**inputs)
1388
+ >>> text_embeds = outputs.text_embeds
1389
+ ```"""
1390
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1391
+
1392
+ text_outputs = self.text_model(
1393
+ input_ids=input_ids,
1394
+ attention_mask=attention_mask,
1395
+ position_ids=position_ids,
1396
+ output_attentions=output_attentions,
1397
+ output_hidden_states=output_hidden_states,
1398
+ return_dict=return_dict,
1399
+ )
1400
+
1401
+ pooled_output = text_outputs[1]
1402
+
1403
+ text_embeds = self.text_projection(pooled_output)
1404
+
1405
+ if not return_dict:
1406
+ outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
1407
+ return tuple(output for output in outputs if output is not None)
1408
+
1409
+ return CLIPTextModelOutput(
1410
+ text_embeds=text_embeds,
1411
+ last_hidden_state=text_outputs.last_hidden_state,
1412
+ hidden_states=text_outputs.hidden_states,
1413
+ attentions=text_outputs.attentions,
1414
+ )
1415
+
1416
+
1417
+ @add_start_docstrings(
1418
+ """
1419
+ CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
1420
+ """,
1421
+ CLIP_START_DOCSTRING,
1422
+ )
1423
+ class CLIPVisionModelWithProjection(CLIPPreTrainedModel):
1424
+ config_class = CLIPVisionConfig
1425
+ main_input_name = "pixel_values"
1426
+
1427
+ def __init__(self, config: CLIPVisionConfig):
1428
+ super().__init__(config)
1429
+
1430
+ vision_model = CLIPVisionModel._from_config(config, attn_implementation=config._attn_implementation)
1431
+ self.vision_model = vision_model.vision_model
1432
+
1433
+ self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
1434
+
1435
+ # Initialize weights and apply final processing
1436
+ self.post_init()
1437
+
1438
+ def get_input_embeddings(self) -> nn.Module:
1439
+ return self.vision_model.embeddings.patch_embedding
1440
+
1441
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1442
+ @replace_return_docstrings(output_type=CLIPVisionModelOutput, config_class=CLIPVisionConfig)
1443
+ def forward(
1444
+ self,
1445
+ pixel_values: Optional[torch.FloatTensor] = None,
1446
+ output_attentions: Optional[bool] = None,
1447
+ output_hidden_states: Optional[bool] = None,
1448
+ return_dict: Optional[bool] = None,
1449
+ ) -> Union[Tuple, CLIPVisionModelOutput]:
1450
+ r"""
1451
+ Returns:
1452
+
1453
+ Examples:
1454
+
1455
+ ```python
1456
+ >>> from PIL import Image
1457
+ >>> import requests
1458
+ >>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
1459
+
1460
+ >>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
1461
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1462
+
1463
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1464
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1465
+
1466
+ >>> inputs = processor(images=image, return_tensors="pt")
1467
+
1468
+ >>> outputs = model(**inputs)
1469
+ >>> image_embeds = outputs.image_embeds
1470
+ ```"""
1471
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1472
+
1473
+ vision_outputs = self.vision_model(
1474
+ pixel_values=pixel_values,
1475
+ output_attentions=output_attentions,
1476
+ output_hidden_states=output_hidden_states,
1477
+ return_dict=return_dict,
1478
+ )
1479
+
1480
+ pooled_output = vision_outputs[1] # pooled_output
1481
+
1482
+ image_embeds = self.visual_projection(pooled_output)
1483
+
1484
+ if not return_dict:
1485
+ outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
1486
+ return tuple(output for output in outputs if output is not None)
1487
+
1488
+ return CLIPVisionModelOutput(
1489
+ image_embeds=image_embeds,
1490
+ last_hidden_state=vision_outputs.last_hidden_state,
1491
+ hidden_states=vision_outputs.hidden_states,
1492
+ attentions=vision_outputs.attentions,
1493
+ )
1494
+
1495
+
1496
+ @add_start_docstrings(
1497
+ """
1498
+ CLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
1499
+ the patch tokens) e.g. for ImageNet.
1500
+ """,
1501
+ CLIP_START_DOCSTRING,
1502
+ )
1503
+ class CLIPForImageClassification(CLIPPreTrainedModel):
1504
+ main_input_name = "pixel_values"
1505
+
1506
+ def __init__(self, config: CLIPConfig) -> None:
1507
+ super().__init__(config)
1508
+
1509
+ self.num_labels = config.num_labels
1510
+ vision_model = CLIPVisionModel._from_config(
1511
+ config.vision_config, attn_implementation=config._attn_implementation
1512
+ )
1513
+ self.vision_model = vision_model.vision_model
1514
+
1515
+ # Classifier head
1516
+ self.classifier = (
1517
+ nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
1518
+ )
1519
+
1520
+ # Initialize weights and apply final processing
1521
+ self.post_init()
1522
+
1523
+ @add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
1524
+ @add_code_sample_docstrings(
1525
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1526
+ output_type=ImageClassifierOutput,
1527
+ config_class=_CONFIG_FOR_DOC,
1528
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1529
+ )
1530
+ def forward(
1531
+ self,
1532
+ pixel_values: Optional[torch.Tensor] = None,
1533
+ labels: Optional[torch.Tensor] = None,
1534
+ output_attentions: Optional[bool] = None,
1535
+ output_hidden_states: Optional[bool] = None,
1536
+ return_dict: Optional[bool] = None,
1537
+ ) -> Union[tuple, ImageClassifierOutput]:
1538
+ r"""
1539
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1540
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1541
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1542
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1543
+ """
1544
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1545
+ output_hidden_states = (
1546
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1547
+ )
1548
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1549
+
1550
+ outputs = self.vision_model(
1551
+ pixel_values,
1552
+ output_attentions=output_attentions,
1553
+ output_hidden_states=output_hidden_states,
1554
+ return_dict=return_dict,
1555
+ )
1556
+
1557
+ sequence_output = outputs[0]
1558
+
1559
+ # average pool the patch tokens
1560
+ sequence_output = torch.mean(sequence_output[:, 1:, :], dim=1)
1561
+ # apply classifier
1562
+ logits = self.classifier(sequence_output)
1563
+
1564
+ loss = None
1565
+ if labels is not None:
1566
+ # move labels to correct device to enable model parallelism
1567
+ labels = labels.to(logits.device)
1568
+ if self.config.problem_type is None:
1569
+ if self.num_labels == 1:
1570
+ self.config.problem_type = "regression"
1571
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1572
+ self.config.problem_type = "single_label_classification"
1573
+ else:
1574
+ self.config.problem_type = "multi_label_classification"
1575
+
1576
+ if self.config.problem_type == "regression":
1577
+ loss_fct = MSELoss()
1578
+ if self.num_labels == 1:
1579
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1580
+ else:
1581
+ loss = loss_fct(logits, labels)
1582
+ elif self.config.problem_type == "single_label_classification":
1583
+ loss_fct = CrossEntropyLoss()
1584
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1585
+ elif self.config.problem_type == "multi_label_classification":
1586
+ loss_fct = BCEWithLogitsLoss()
1587
+ loss = loss_fct(logits, labels)
1588
+
1589
+ if not return_dict:
1590
+ output = (logits,) + outputs[2:]
1591
+ return ((loss,) + output) if loss is not None else output
1592
+
1593
+ return ImageClassifierOutput(
1594
+ loss=loss,
1595
+ logits=logits,
1596
+ hidden_states=outputs.hidden_states,
1597
+ attentions=outputs.attentions,
1598
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0921e6e15fae7a2a28459008d97c50c7fc099bad0bc57bf1573f28e9354a3cbc
3
+ size 1219403118
teaser.png ADDED