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