Upload 9 files (#2)
Browse files- Upload 9 files (119b2e667414a547bb29c918989920f35e6b7557)
Co-authored-by: Leo Tronchon <Leyo@users.noreply.huggingface.co>
- EVA02-CLIP-bigE-14-plus_s9B/CLIP.png +0 -0
- EVA02-CLIP-bigE-14-plus_s9B/config.json +180 -0
- EVA02-CLIP-bigE-14-plus_s9B/configuration_evaclip.py +421 -0
- EVA02-CLIP-bigE-14-plus_s9B/convert_evaclip_pytorch_to_hf.py +181 -0
- EVA02-CLIP-bigE-14-plus_s9B/merges.txt +0 -0
- EVA02-CLIP-bigE-14-plus_s9B/modeling_evaclip.py +1428 -0
- EVA02-CLIP-bigE-14-plus_s9B/special_tokens_map.json +24 -0
- EVA02-CLIP-bigE-14-plus_s9B/tokenizer_config.json +31 -0
- EVA02-CLIP-bigE-14-plus_s9B/vocab.json +0 -0
EVA02-CLIP-bigE-14-plus_s9B/CLIP.png
ADDED
EVA02-CLIP-bigE-14-plus_s9B/config.json
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_commit_hash": null,
|
3 |
+
"_name_or_path": "HuggingfaceM4/EVA02-CLIP-bigE-14-plus_s9B_M4",
|
4 |
+
"architectures": [
|
5 |
+
"EvaCLIPModel"
|
6 |
+
],
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_evaclip.EvaCLIPConfig",
|
9 |
+
"AutoModel": "modeling_evaclip.EvaCLIPModel"
|
10 |
+
},
|
11 |
+
"initializer_factor": 1.0,
|
12 |
+
"logit_scale_init_value": 2.659260036932778,
|
13 |
+
"model_type": "clip",
|
14 |
+
"projection_dim": 1024,
|
15 |
+
"text_config": {
|
16 |
+
"_name_or_path": "",
|
17 |
+
"add_cross_attention": false,
|
18 |
+
"architectures": null,
|
19 |
+
"attention_dropout": 0.0,
|
20 |
+
"bad_words_ids": null,
|
21 |
+
"begin_suppress_tokens": null,
|
22 |
+
"bos_token_id": 0,
|
23 |
+
"chunk_size_feed_forward": 0,
|
24 |
+
"cross_attention_hidden_size": null,
|
25 |
+
"decoder_start_token_id": null,
|
26 |
+
"diversity_penalty": 0.0,
|
27 |
+
"do_sample": false,
|
28 |
+
"dropout": 0.0,
|
29 |
+
"early_stopping": false,
|
30 |
+
"encoder_no_repeat_ngram_size": 0,
|
31 |
+
"eos_token_id": 2,
|
32 |
+
"exponential_decay_length_penalty": null,
|
33 |
+
"finetuning_task": null,
|
34 |
+
"forced_bos_token_id": null,
|
35 |
+
"forced_eos_token_id": null,
|
36 |
+
"hidden_act": "gelu",
|
37 |
+
"hidden_size": 1280,
|
38 |
+
"id2label": {
|
39 |
+
"0": "LABEL_0",
|
40 |
+
"1": "LABEL_1"
|
41 |
+
},
|
42 |
+
"initializer_factor": 1.0,
|
43 |
+
"initializer_range": 0.02,
|
44 |
+
"intermediate_size": 5120,
|
45 |
+
"is_decoder": false,
|
46 |
+
"is_encoder_decoder": false,
|
47 |
+
"k_bias": true,
|
48 |
+
"label2id": {
|
49 |
+
"LABEL_0": 0,
|
50 |
+
"LABEL_1": 1
|
51 |
+
},
|
52 |
+
"layer_norm_eps": 1e-05,
|
53 |
+
"length_penalty": 1.0,
|
54 |
+
"max_length": 20,
|
55 |
+
"max_position_embeddings": 77,
|
56 |
+
"min_length": 0,
|
57 |
+
"model_type": "clip_text_model",
|
58 |
+
"no_repeat_ngram_size": 0,
|
59 |
+
"num_attention_heads": 20,
|
60 |
+
"num_beam_groups": 1,
|
61 |
+
"num_beams": 1,
|
62 |
+
"num_hidden_layers": 32,
|
63 |
+
"num_return_sequences": 1,
|
64 |
+
"output_attentions": false,
|
65 |
+
"output_hidden_states": false,
|
66 |
+
"output_scores": false,
|
67 |
+
"pad_token_id": 1,
|
68 |
+
"post_layernorm": false,
|
69 |
+
"prefix": null,
|
70 |
+
"problem_type": null,
|
71 |
+
"projection_dim": 1024,
|
72 |
+
"pruned_heads": {},
|
73 |
+
"q_bias": true,
|
74 |
+
"remove_invalid_values": false,
|
75 |
+
"repetition_penalty": 1.0,
|
76 |
+
"return_dict": true,
|
77 |
+
"return_dict_in_generate": false,
|
78 |
+
"sep_token_id": null,
|
79 |
+
"suppress_tokens": null,
|
80 |
+
"task_specific_params": null,
|
81 |
+
"temperature": 1.0,
|
82 |
+
"tf_legacy_loss": false,
|
83 |
+
"tie_encoder_decoder": false,
|
84 |
+
"tie_word_embeddings": true,
|
85 |
+
"tokenizer_class": null,
|
86 |
+
"top_k": 50,
|
87 |
+
"top_p": 1.0,
|
88 |
+
"torch_dtype": null,
|
89 |
+
"torchscript": false,
|
90 |
+
"transformers_version": "4.28.0.dev0",
|
91 |
+
"typical_p": 1.0,
|
92 |
+
"use_bfloat16": false,
|
93 |
+
"v_bias": true,
|
94 |
+
"vocab_size": 49408
|
95 |
+
},
|
96 |
+
"torch_dtype": "float32",
|
97 |
+
"transformers_version": null,
|
98 |
+
"vision_config": {
|
99 |
+
"_name_or_path": "",
|
100 |
+
"add_cross_attention": false,
|
101 |
+
"architectures": null,
|
102 |
+
"attention_dropout": 0.0,
|
103 |
+
"bad_words_ids": null,
|
104 |
+
"begin_suppress_tokens": null,
|
105 |
+
"bos_token_id": null,
|
106 |
+
"chunk_size_feed_forward": 0,
|
107 |
+
"cross_attention_hidden_size": null,
|
108 |
+
"decoder_start_token_id": null,
|
109 |
+
"diversity_penalty": 0.0,
|
110 |
+
"do_sample": false,
|
111 |
+
"dropout": 0.0,
|
112 |
+
"early_stopping": false,
|
113 |
+
"encoder_no_repeat_ngram_size": 0,
|
114 |
+
"eos_token_id": null,
|
115 |
+
"exponential_decay_length_penalty": null,
|
116 |
+
"finetuning_task": null,
|
117 |
+
"forced_bos_token_id": null,
|
118 |
+
"forced_eos_token_id": null,
|
119 |
+
"hidden_act": "gelu",
|
120 |
+
"hidden_size": 1792,
|
121 |
+
"id2label": {
|
122 |
+
"0": "LABEL_0",
|
123 |
+
"1": "LABEL_1"
|
124 |
+
},
|
125 |
+
"image_size": 224,
|
126 |
+
"initializer_factor": 1.0,
|
127 |
+
"initializer_range": 0.02,
|
128 |
+
"intermediate_size": 15360,
|
129 |
+
"is_decoder": false,
|
130 |
+
"is_encoder_decoder": false,
|
131 |
+
"k_bias": false,
|
132 |
+
"label2id": {
|
133 |
+
"LABEL_0": 0,
|
134 |
+
"LABEL_1": 1
|
135 |
+
},
|
136 |
+
"layer_norm_eps": 1e-06,
|
137 |
+
"length_penalty": 1.0,
|
138 |
+
"max_length": 20,
|
139 |
+
"min_length": 0,
|
140 |
+
"model_type": "clip_vision_model",
|
141 |
+
"no_repeat_ngram_size": 0,
|
142 |
+
"num_attention_heads": 16,
|
143 |
+
"num_beam_groups": 1,
|
144 |
+
"num_beams": 1,
|
145 |
+
"num_channels": 3,
|
146 |
+
"num_hidden_layers": 64,
|
147 |
+
"num_return_sequences": 1,
|
148 |
+
"output_attentions": false,
|
149 |
+
"output_hidden_states": false,
|
150 |
+
"output_scores": false,
|
151 |
+
"pad_token_id": null,
|
152 |
+
"patch_size": 14,
|
153 |
+
"post_layernorm": true,
|
154 |
+
"prefix": null,
|
155 |
+
"problem_type": null,
|
156 |
+
"projection_dim": 1024,
|
157 |
+
"pruned_heads": {},
|
158 |
+
"q_bias": true,
|
159 |
+
"remove_invalid_values": false,
|
160 |
+
"repetition_penalty": 1.0,
|
161 |
+
"return_dict": true,
|
162 |
+
"return_dict_in_generate": false,
|
163 |
+
"sep_token_id": null,
|
164 |
+
"suppress_tokens": null,
|
165 |
+
"task_specific_params": null,
|
166 |
+
"temperature": 1.0,
|
167 |
+
"tf_legacy_loss": false,
|
168 |
+
"tie_encoder_decoder": false,
|
169 |
+
"tie_word_embeddings": true,
|
170 |
+
"tokenizer_class": null,
|
171 |
+
"top_k": 50,
|
172 |
+
"top_p": 1.0,
|
173 |
+
"torch_dtype": null,
|
174 |
+
"torchscript": false,
|
175 |
+
"transformers_version": "4.28.0.dev0",
|
176 |
+
"typical_p": 1.0,
|
177 |
+
"use_bfloat16": false,
|
178 |
+
"v_bias": true
|
179 |
+
}
|
180 |
+
}
|
EVA02-CLIP-bigE-14-plus_s9B/configuration_evaclip.py
ADDED
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
""" EvaCLIP model configuration"""
|
16 |
+
# Code mainly copied here: https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/configuration_clip.py
|
17 |
+
# and adjusted for evaclip
|
18 |
+
|
19 |
+
import copy
|
20 |
+
import os
|
21 |
+
from collections import OrderedDict
|
22 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
23 |
+
|
24 |
+
|
25 |
+
if TYPE_CHECKING:
|
26 |
+
from transformers.processing_utils import ProcessorMixin
|
27 |
+
from transformers.utils import TensorType
|
28 |
+
|
29 |
+
from transformers.configuration_utils import PretrainedConfig
|
30 |
+
from transformers.utils import logging
|
31 |
+
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
|
35 |
+
|
36 |
+
class EvaCLIPTextConfig(PretrainedConfig):
|
37 |
+
r"""
|
38 |
+
This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
|
39 |
+
text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
|
40 |
+
with the defaults will yield a similar configuration to that of the text encoder of the CLIP
|
41 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
42 |
+
|
43 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
44 |
+
documentation from [`PretrainedConfig`] for more information.
|
45 |
+
|
46 |
+
Args:
|
47 |
+
vocab_size (`int`, *optional*, defaults to 49408):
|
48 |
+
Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
|
49 |
+
the `inputs_ids` passed when calling [`CLIPModel`].
|
50 |
+
hidden_size (`int`, *optional*, defaults to 512):
|
51 |
+
Dimensionality of the encoder layers and the pooler layer.
|
52 |
+
intermediate_size (`int`, *optional*, defaults to 2048):
|
53 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
54 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
55 |
+
Number of hidden layers in the Transformer encoder.
|
56 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
57 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 77):
|
59 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
60 |
+
just in case (e.g., 512 or 1024 or 2048).
|
61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
63 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
64 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
65 |
+
The epsilon used by the layer normalization layers.
|
66 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
67 |
+
The dropout ratio for the attention probabilities.
|
68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
69 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
70 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
71 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
72 |
+
testing).
|
73 |
+
|
74 |
+
Example:
|
75 |
+
|
76 |
+
```python
|
77 |
+
>>> from transformers import CLIPTextConfig, CLIPTextModel
|
78 |
+
|
79 |
+
>>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
|
80 |
+
>>> configuration = CLIPTextConfig()
|
81 |
+
|
82 |
+
>>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
83 |
+
>>> model = CLIPTextModel(configuration)
|
84 |
+
|
85 |
+
>>> # Accessing the model configuration
|
86 |
+
>>> configuration = model.config
|
87 |
+
```"""
|
88 |
+
model_type = "clip_text_model"
|
89 |
+
|
90 |
+
def __init__(
|
91 |
+
self,
|
92 |
+
vocab_size=49408,
|
93 |
+
hidden_size=512,
|
94 |
+
intermediate_size=2048,
|
95 |
+
projection_dim=512,
|
96 |
+
num_hidden_layers=12,
|
97 |
+
num_attention_heads=8,
|
98 |
+
max_position_embeddings=77,
|
99 |
+
hidden_act="gelu",
|
100 |
+
layer_norm_eps=1e-5,
|
101 |
+
attention_dropout=0.0,
|
102 |
+
initializer_range=0.02,
|
103 |
+
initializer_factor=1.0,
|
104 |
+
q_bias=True,
|
105 |
+
k_bias=True,
|
106 |
+
v_bias=True,
|
107 |
+
post_layernorm=False,
|
108 |
+
pad_token_id=1,
|
109 |
+
bos_token_id=0,
|
110 |
+
eos_token_id=2,
|
111 |
+
**kwargs,
|
112 |
+
):
|
113 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
114 |
+
|
115 |
+
self.vocab_size = vocab_size
|
116 |
+
self.hidden_size = hidden_size
|
117 |
+
self.intermediate_size = intermediate_size
|
118 |
+
self.projection_dim = projection_dim
|
119 |
+
self.num_hidden_layers = num_hidden_layers
|
120 |
+
self.num_attention_heads = num_attention_heads
|
121 |
+
self.max_position_embeddings = max_position_embeddings
|
122 |
+
self.layer_norm_eps = layer_norm_eps
|
123 |
+
self.hidden_act = hidden_act
|
124 |
+
self.initializer_range = initializer_range
|
125 |
+
self.initializer_factor = initializer_factor
|
126 |
+
self.q_bias=q_bias
|
127 |
+
self.k_bias=k_bias
|
128 |
+
self.v_bias=v_bias
|
129 |
+
self.post_layernorm = post_layernorm
|
130 |
+
self.attention_dropout = attention_dropout
|
131 |
+
|
132 |
+
@classmethod
|
133 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
134 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
135 |
+
|
136 |
+
# get the text config dict if we are loading from CLIPConfig
|
137 |
+
if config_dict.get("model_type") == "clip":
|
138 |
+
config_dict = config_dict["text_config"]
|
139 |
+
|
140 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
141 |
+
logger.warning(
|
142 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
143 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
144 |
+
)
|
145 |
+
|
146 |
+
return cls.from_dict(config_dict, **kwargs)
|
147 |
+
|
148 |
+
|
149 |
+
class EvaCLIPVisionConfig(PretrainedConfig):
|
150 |
+
r"""
|
151 |
+
This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
|
152 |
+
CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
153 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
|
154 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
155 |
+
|
156 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
157 |
+
documentation from [`PretrainedConfig`] for more information.
|
158 |
+
|
159 |
+
Args:
|
160 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
161 |
+
Dimensionality of the encoder layers and the pooler layer.
|
162 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
163 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
164 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
165 |
+
Number of hidden layers in the Transformer encoder.
|
166 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
167 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
168 |
+
image_size (`int`, *optional*, defaults to 224):
|
169 |
+
The size (resolution) of each image.
|
170 |
+
patch_size (`int`, *optional*, defaults to 32):
|
171 |
+
The size (resolution) of each patch.
|
172 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
173 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
174 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
175 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
176 |
+
The epsilon used by the layer normalization layers.
|
177 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
178 |
+
The dropout ratio for the attention probabilities.
|
179 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
180 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
181 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
182 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
183 |
+
testing).
|
184 |
+
|
185 |
+
Example:
|
186 |
+
|
187 |
+
```python
|
188 |
+
>>> from transformers import CLIPVisionConfig, CLIPVisionModel
|
189 |
+
|
190 |
+
>>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
|
191 |
+
>>> configuration = CLIPVisionConfig()
|
192 |
+
|
193 |
+
>>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
194 |
+
>>> model = CLIPVisionModel(configuration)
|
195 |
+
|
196 |
+
>>> # Accessing the model configuration
|
197 |
+
>>> configuration = model.config
|
198 |
+
```"""
|
199 |
+
|
200 |
+
model_type = "clip_vision_model"
|
201 |
+
|
202 |
+
def __init__(
|
203 |
+
self,
|
204 |
+
hidden_size=768,
|
205 |
+
intermediate_size=3072,
|
206 |
+
projection_dim=512,
|
207 |
+
num_hidden_layers=12,
|
208 |
+
num_attention_heads=12,
|
209 |
+
num_channels=3,
|
210 |
+
image_size=224,
|
211 |
+
patch_size=32,
|
212 |
+
hidden_act="gelu",
|
213 |
+
layer_norm_eps=1e-5,
|
214 |
+
attention_dropout=0.0,
|
215 |
+
initializer_range=0.02,
|
216 |
+
initializer_factor=1.0,
|
217 |
+
q_bias=True,
|
218 |
+
k_bias=True,
|
219 |
+
v_bias=True,
|
220 |
+
post_layernorm=False,
|
221 |
+
**kwargs,
|
222 |
+
):
|
223 |
+
super().__init__(**kwargs)
|
224 |
+
|
225 |
+
self.hidden_size = hidden_size
|
226 |
+
self.intermediate_size = intermediate_size
|
227 |
+
self.projection_dim = projection_dim
|
228 |
+
self.num_hidden_layers = num_hidden_layers
|
229 |
+
self.num_attention_heads = num_attention_heads
|
230 |
+
self.num_channels = num_channels
|
231 |
+
self.patch_size = patch_size
|
232 |
+
self.image_size = image_size
|
233 |
+
self.initializer_range = initializer_range
|
234 |
+
self.initializer_factor = initializer_factor
|
235 |
+
self.q_bias=q_bias
|
236 |
+
self.k_bias=k_bias
|
237 |
+
self.v_bias=v_bias
|
238 |
+
self.post_layernorm = post_layernorm
|
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 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
246 |
+
|
247 |
+
# get the vision config dict if we are loading from CLIPConfig
|
248 |
+
if config_dict.get("model_type") == "clip":
|
249 |
+
config_dict = config_dict["vision_config"]
|
250 |
+
|
251 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
252 |
+
logger.warning(
|
253 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
254 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
255 |
+
)
|
256 |
+
|
257 |
+
return cls.from_dict(config_dict, **kwargs)
|
258 |
+
|
259 |
+
|
260 |
+
class EvaCLIPConfig(PretrainedConfig):
|
261 |
+
r"""
|
262 |
+
[`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
|
263 |
+
a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
|
264 |
+
a configuration with the defaults will yield a similar configuration to that of the CLIP
|
265 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
266 |
+
|
267 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
268 |
+
documentation from [`PretrainedConfig`] for more information.
|
269 |
+
|
270 |
+
Args:
|
271 |
+
text_config (`dict`, *optional*):
|
272 |
+
Dictionary of configuration options used to initialize [`CLIPTextConfig`].
|
273 |
+
vision_config (`dict`, *optional*):
|
274 |
+
Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
|
275 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
276 |
+
Dimentionality of text and vision projection layers.
|
277 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
278 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
|
279 |
+
kwargs (*optional*):
|
280 |
+
Dictionary of keyword arguments.
|
281 |
+
|
282 |
+
Example:
|
283 |
+
|
284 |
+
```python
|
285 |
+
>>> from transformers import CLIPConfig, CLIPModel
|
286 |
+
|
287 |
+
>>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
|
288 |
+
>>> configuration = CLIPConfig()
|
289 |
+
|
290 |
+
>>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
291 |
+
>>> model = CLIPModel(configuration)
|
292 |
+
|
293 |
+
>>> # Accessing the model configuration
|
294 |
+
>>> configuration = model.config
|
295 |
+
|
296 |
+
>>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
|
297 |
+
>>> from transformers import CLIPTextConfig, CLIPVisionConfig
|
298 |
+
|
299 |
+
>>> # Initializing a CLIPText and CLIPVision configuration
|
300 |
+
>>> config_text = CLIPTextConfig()
|
301 |
+
>>> config_vision = CLIPVisionConfig()
|
302 |
+
|
303 |
+
>>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
|
304 |
+
```"""
|
305 |
+
|
306 |
+
model_type = "clip"
|
307 |
+
is_composition = True
|
308 |
+
|
309 |
+
def __init__(
|
310 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
311 |
+
):
|
312 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
313 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
314 |
+
# of confusion!).
|
315 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
316 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
317 |
+
|
318 |
+
super().__init__(**kwargs)
|
319 |
+
|
320 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
321 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
322 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
323 |
+
if text_config_dict is not None:
|
324 |
+
if text_config is None:
|
325 |
+
text_config = {}
|
326 |
+
|
327 |
+
# This is the complete result when using `text_config_dict`.
|
328 |
+
_text_config_dict = EvaCLIPTextConfig(**text_config_dict).to_dict()
|
329 |
+
|
330 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
331 |
+
for key, value in _text_config_dict.items():
|
332 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
333 |
+
# If specified in `text_config_dict`
|
334 |
+
if key in text_config_dict:
|
335 |
+
message = (
|
336 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
337 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
338 |
+
)
|
339 |
+
# If inferred from default argument values (just to be super careful)
|
340 |
+
else:
|
341 |
+
message = (
|
342 |
+
f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
|
343 |
+
f'value `text_config["{key}"]` will be overriden.'
|
344 |
+
)
|
345 |
+
logger.warning(message)
|
346 |
+
|
347 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
348 |
+
text_config.update(_text_config_dict)
|
349 |
+
|
350 |
+
if vision_config_dict is not None:
|
351 |
+
if vision_config is None:
|
352 |
+
vision_config = {}
|
353 |
+
|
354 |
+
# This is the complete result when using `vision_config_dict`.
|
355 |
+
_vision_config_dict = EvaCLIPVisionConfig(**vision_config_dict).to_dict()
|
356 |
+
# convert keys to string instead of integer
|
357 |
+
if "id2label" in _vision_config_dict:
|
358 |
+
_vision_config_dict["id2label"] = {
|
359 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
360 |
+
}
|
361 |
+
|
362 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
363 |
+
for key, value in _vision_config_dict.items():
|
364 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
365 |
+
# If specified in `vision_config_dict`
|
366 |
+
if key in vision_config_dict:
|
367 |
+
message = (
|
368 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
369 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
370 |
+
)
|
371 |
+
# If inferred from default argument values (just to be super careful)
|
372 |
+
else:
|
373 |
+
message = (
|
374 |
+
f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
|
375 |
+
f'The value `vision_config["{key}"]` will be overriden.'
|
376 |
+
)
|
377 |
+
logger.warning(message)
|
378 |
+
|
379 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
380 |
+
vision_config.update(_vision_config_dict)
|
381 |
+
|
382 |
+
if text_config is None:
|
383 |
+
text_config = {}
|
384 |
+
logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
|
385 |
+
|
386 |
+
if vision_config is None:
|
387 |
+
vision_config = {}
|
388 |
+
logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
|
389 |
+
|
390 |
+
self.text_config = EvaCLIPTextConfig(**text_config)
|
391 |
+
self.vision_config = EvaCLIPVisionConfig(**vision_config)
|
392 |
+
|
393 |
+
self.projection_dim = projection_dim
|
394 |
+
self.logit_scale_init_value = logit_scale_init_value
|
395 |
+
self.initializer_factor = 1.0
|
396 |
+
|
397 |
+
@classmethod
|
398 |
+
def from_text_vision_configs(cls, text_config: EvaCLIPTextConfig, vision_config: EvaCLIPVisionConfig, **kwargs):
|
399 |
+
r"""
|
400 |
+
Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
|
401 |
+
configuration.
|
402 |
+
|
403 |
+
Returns:
|
404 |
+
[`CLIPConfig`]: An instance of a configuration object
|
405 |
+
"""
|
406 |
+
|
407 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
408 |
+
|
409 |
+
def to_dict(self):
|
410 |
+
"""
|
411 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
412 |
+
|
413 |
+
Returns:
|
414 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
415 |
+
"""
|
416 |
+
output = copy.deepcopy(self.__dict__)
|
417 |
+
output["text_config"] = self.text_config.to_dict()
|
418 |
+
output["vision_config"] = self.vision_config.to_dict()
|
419 |
+
output["model_type"] = self.__class__.model_type
|
420 |
+
return output
|
421 |
+
|
EVA02-CLIP-bigE-14-plus_s9B/convert_evaclip_pytorch_to_hf.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
# Part of the code was taken from:
|
17 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py
|
18 |
+
|
19 |
+
import argparse
|
20 |
+
|
21 |
+
import torch
|
22 |
+
from PIL import Image
|
23 |
+
from transformers import AutoModel, AutoConfig
|
24 |
+
from transformers import CLIPImageProcessor, pipeline, CLIPTokenizer
|
25 |
+
from configuration_evaclip import EvaCLIPConfig
|
26 |
+
from modeling_evaclip import EvaCLIPModel
|
27 |
+
|
28 |
+
|
29 |
+
KEYS_TO_MODIFY_MAPPING = {
|
30 |
+
"cls_token":"embeddings.class_embedding",
|
31 |
+
"pos_embed":"embeddings.position_embedding.weight",
|
32 |
+
"patch_embed.proj":"embeddings.patch_embedding",
|
33 |
+
".positional_embedding":".embeddings.position_embedding.weight",
|
34 |
+
".token_embedding":".embeddings.token_embedding",
|
35 |
+
"text.text_projection":"text_projection.weight",
|
36 |
+
"mlp.c_fc":"mlp.fc1",
|
37 |
+
"mlp.c_proj":"mlp.fc2",
|
38 |
+
".proj.":".out_proj.",
|
39 |
+
"q_bias":"q_proj.bias",
|
40 |
+
"v_bias":"v_proj.bias",
|
41 |
+
"out.":"out_proj.",
|
42 |
+
"norm1":"layer_norm1",
|
43 |
+
"norm2":"layer_norm2",
|
44 |
+
"ln_1":"layer_norm1",
|
45 |
+
"ln_2":"layer_norm2",
|
46 |
+
"attn":"self_attn",
|
47 |
+
"norm.":"post_layernorm.",
|
48 |
+
"ln_final":"final_layer_norm",
|
49 |
+
"visual.blocks":"vision_model.encoder.layers",
|
50 |
+
"text.transformer.resblocks":"text_model.encoder.layers",
|
51 |
+
"visual.head":"visual_projection",
|
52 |
+
"visual.":"vision_model.",
|
53 |
+
"text.":"text_model.",
|
54 |
+
|
55 |
+
}
|
56 |
+
|
57 |
+
def rename_state_dict(state_dict):
|
58 |
+
model_state_dict = {}
|
59 |
+
|
60 |
+
for key, value in state_dict.items():
|
61 |
+
# check if any key needs to be modified
|
62 |
+
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
|
63 |
+
if key_to_modify in key:
|
64 |
+
key = key.replace(key_to_modify, new_key)
|
65 |
+
if "text_projection" in key:
|
66 |
+
model_state_dict[key] = value.T
|
67 |
+
elif "attn.qkv" in key:
|
68 |
+
# split qkv into query key and value
|
69 |
+
mixed_qkv = value
|
70 |
+
qkv_dim = mixed_qkv.size(0) // 3
|
71 |
+
|
72 |
+
query_layer = mixed_qkv[:qkv_dim]
|
73 |
+
key_layer = mixed_qkv[qkv_dim : qkv_dim * 2]
|
74 |
+
value_layer = mixed_qkv[qkv_dim * 2 :]
|
75 |
+
|
76 |
+
model_state_dict[key.replace("qkv", "q_proj")] = query_layer
|
77 |
+
model_state_dict[key.replace("qkv", "k_proj")] = key_layer
|
78 |
+
model_state_dict[key.replace("qkv", "v_proj")] = value_layer
|
79 |
+
|
80 |
+
elif "attn.in_proj" in key:
|
81 |
+
# split qkv into query key and value
|
82 |
+
mixed_qkv = value
|
83 |
+
qkv_dim = mixed_qkv.size(0) // 3
|
84 |
+
|
85 |
+
query_layer = mixed_qkv[:qkv_dim]
|
86 |
+
key_layer = mixed_qkv[qkv_dim : qkv_dim * 2]
|
87 |
+
value_layer = mixed_qkv[qkv_dim * 2 :]
|
88 |
+
|
89 |
+
model_state_dict[key.replace("in_proj_", "q_proj.")] = query_layer
|
90 |
+
model_state_dict[key.replace("in_proj_", "k_proj.")] = key_layer
|
91 |
+
model_state_dict[key.replace("in_proj_", "v_proj.")] = value_layer
|
92 |
+
|
93 |
+
elif "class_embedding" in key:
|
94 |
+
model_state_dict[key] = value[0,0,:]
|
95 |
+
elif "vision_model.embeddings.position_embedding" in key:
|
96 |
+
model_state_dict[key] = value[0,:,:]
|
97 |
+
|
98 |
+
else:
|
99 |
+
model_state_dict[key] = value
|
100 |
+
|
101 |
+
return model_state_dict
|
102 |
+
|
103 |
+
# This requires having a clone of https://github.com/baaivision/EVA/tree/master/EVA-CLIP as well as the right conda env
|
104 |
+
# Part of the code is copied from https://github.com/baaivision/EVA/blob/master/EVA-CLIP/README.md "Usage" section
|
105 |
+
def getevaclip(checkpoint_path, input_pixels, captions):
|
106 |
+
from eva_clip import create_model_and_transforms, get_tokenizer
|
107 |
+
model_name = "EVA02-CLIP-bigE-14-plus"
|
108 |
+
model, _, _ = create_model_and_transforms(model_name, checkpoint_path, force_custom_clip=True)
|
109 |
+
tokenizer = get_tokenizer(model_name)
|
110 |
+
text = tokenizer(captions)
|
111 |
+
|
112 |
+
with torch.no_grad():
|
113 |
+
text_features = model.encode_text(text)
|
114 |
+
image_features = model.encode_image(input_pixels)
|
115 |
+
image_features_normed = image_features / image_features.norm(dim=-1, keepdim=True)
|
116 |
+
text_features_normed = text_features / text_features.norm(dim=-1, keepdim=True)
|
117 |
+
|
118 |
+
label_probs = (100.0 * image_features_normed @ text_features_normed.T).softmax(dim=-1)
|
119 |
+
|
120 |
+
return label_probs
|
121 |
+
|
122 |
+
def save_model_and_config(pytorch_dump_folder_path, hf_model, transformers_config):
|
123 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
124 |
+
transformers_config.save_pretrained(pytorch_dump_folder_path)
|
125 |
+
|
126 |
+
def check_loaded_model(pytorch_dump_folder_path, tokenizer, processor, image, captions):
|
127 |
+
hf_config = AutoConfig.from_pretrained(pytorch_dump_folder_path, trust_remote_code=True)
|
128 |
+
hf_model = AutoModel.from_pretrained(pytorch_dump_folder_path, config=hf_config, trust_remote_code=True)
|
129 |
+
detector = pipeline(model=hf_model, task="zero-shot-image-classification", tokenizer = tokenizer, image_processor=processor)
|
130 |
+
detector_probs = detector(image, candidate_labels=captions)
|
131 |
+
print(f"text_probs loaded hf_model using pipeline: {detector_probs}")
|
132 |
+
|
133 |
+
def convert_evaclip_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path, image_path, save=False):
|
134 |
+
processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
|
135 |
+
image = Image.open(image_path)
|
136 |
+
captions = ["a diagram", "a dog", "a cat"]
|
137 |
+
tokenizer = CLIPTokenizer.from_pretrained(pytorch_dump_folder_path)
|
138 |
+
input_ids = tokenizer(captions, return_tensors="pt", padding=True).input_ids
|
139 |
+
input_pixels = processor( images=image, return_tensors="pt", padding=True).pixel_values
|
140 |
+
|
141 |
+
# This requires having a clone of https://github.com/baaivision/EVA/tree/master/EVA-CLIP as well as the right conda env
|
142 |
+
# original_evaclip_probs = getevaclip(checkpoint_path, input_pixels, captions)
|
143 |
+
# print(f"original_evaclip label probs: {original_evaclip_probs}")
|
144 |
+
|
145 |
+
transformers_config = EvaCLIPConfig.from_pretrained(config_path)
|
146 |
+
hf_model = EvaCLIPModel(transformers_config)
|
147 |
+
pt_model_state_dict = torch.load(checkpoint_path)
|
148 |
+
state_dict = rename_state_dict(pt_model_state_dict)
|
149 |
+
|
150 |
+
hf_model.load_state_dict(state_dict, strict=True)
|
151 |
+
|
152 |
+
with torch.no_grad():
|
153 |
+
image_features = hf_model.get_image_features(input_pixels)
|
154 |
+
text_features = hf_model.get_text_features(input_ids)
|
155 |
+
image_features /= image_features.norm(dim=-1, keepdim=True)
|
156 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
157 |
+
|
158 |
+
label_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)
|
159 |
+
print(f"hf_model label probs: {label_probs}")
|
160 |
+
|
161 |
+
if save:
|
162 |
+
save_model_and_config(pytorch_dump_folder_path, hf_model, transformers_config)
|
163 |
+
|
164 |
+
check_loaded_model(pytorch_dump_folder_path, tokenizer, processor, image, captions)
|
165 |
+
|
166 |
+
# hf_model.push_to_hub("ORGANIZATION_NAME/EVA02_CLIP_E_psz14_plus_s9B")
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
if __name__ == "__main__":
|
172 |
+
parser = argparse.ArgumentParser()
|
173 |
+
parser.add_argument("--pytorch_dump_folder_path", default="EVA-CLIP/EVA02-CLIP-bigE-14-plus_s9B" ,type=str, help="Path to the output PyTorch model.")
|
174 |
+
parser.add_argument("--checkpoint_path", default="EVA02_CLIP_E_psz14_plus_s9B.pt", type=str, help="Path to fairseq checkpoint" )
|
175 |
+
parser.add_argument("--config_path", default='EVA-CLIP/EVA02-CLIP-bigE-14-plus_s9B', type=str, help="Path to hf config.json of model to convert")
|
176 |
+
parser.add_argument("--image_path", default='EVA-CLIP/EVA02-CLIP-bigE-14-plus_s9B/CLIP.png', type=str, help="Path to image")
|
177 |
+
parser.add_argument("--save", default=False, type=str, help="Path to image")
|
178 |
+
|
179 |
+
args = parser.parse_args()
|
180 |
+
|
181 |
+
convert_evaclip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.image_path, args.save)
|
EVA02-CLIP-bigE-14-plus_s9B/merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
EVA02-CLIP-bigE-14-plus_s9B/modeling_evaclip.py
ADDED
@@ -0,0 +1,1428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 EvaCLIP model."""
|
16 |
+
# Code mainly taken from https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/modeling_clip.py#L943
|
17 |
+
# and adjusteed for EvaClip
|
18 |
+
|
19 |
+
|
20 |
+
from dataclasses import dataclass
|
21 |
+
from typing import Any, Optional, Tuple, Union
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import torch.utils.checkpoint
|
25 |
+
from torch import nn
|
26 |
+
|
27 |
+
from transformers.activations import ACT2FN
|
28 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
29 |
+
from transformers.modeling_utils import PreTrainedModel
|
30 |
+
from transformers.utils import (
|
31 |
+
ModelOutput,
|
32 |
+
add_start_docstrings,
|
33 |
+
add_start_docstrings_to_model_forward,
|
34 |
+
logging,
|
35 |
+
replace_return_docstrings,
|
36 |
+
)
|
37 |
+
from configuration_evaclip import EvaCLIPConfig, EvaCLIPTextConfig, EvaCLIPVisionConfig
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
_CHECKPOINT_FOR_DOC = "HuggingFaceM4/Eva02-CLIP-bigE-14-plus_s9B"
|
42 |
+
|
43 |
+
Eva_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
44 |
+
"Eva02-CLIP-bigE-14-plus_s9B",
|
45 |
+
]
|
46 |
+
|
47 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
48 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
49 |
+
"""
|
50 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
51 |
+
"""
|
52 |
+
bsz, src_len = mask.size()
|
53 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
54 |
+
|
55 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
56 |
+
|
57 |
+
inverted_mask = 1.0 - expanded_mask
|
58 |
+
|
59 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
60 |
+
|
61 |
+
|
62 |
+
# contrastive loss function, adapted from
|
63 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
64 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
65 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
66 |
+
|
67 |
+
|
68 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
69 |
+
caption_loss = contrastive_loss(similarity)
|
70 |
+
image_loss = contrastive_loss(similarity.t())
|
71 |
+
return (caption_loss + image_loss) / 2.0
|
72 |
+
|
73 |
+
|
74 |
+
@dataclass
|
75 |
+
class EvaCLIPVisionModelOutput(ModelOutput):
|
76 |
+
"""
|
77 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
78 |
+
|
79 |
+
Args:
|
80 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
81 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
82 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
83 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
84 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
85 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
86 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
87 |
+
|
88 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
89 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
90 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
91 |
+
sequence_length)`.
|
92 |
+
|
93 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
94 |
+
heads.
|
95 |
+
"""
|
96 |
+
|
97 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
98 |
+
last_hidden_state: torch.FloatTensor = None
|
99 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
100 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
101 |
+
|
102 |
+
|
103 |
+
@dataclass
|
104 |
+
class EvaCLIPTextModelOutput(ModelOutput):
|
105 |
+
"""
|
106 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
107 |
+
|
108 |
+
Args:
|
109 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
110 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
111 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
112 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
113 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
114 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
115 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
116 |
+
|
117 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
118 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
119 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
120 |
+
sequence_length)`.
|
121 |
+
|
122 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
123 |
+
heads.
|
124 |
+
"""
|
125 |
+
|
126 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
127 |
+
last_hidden_state: torch.FloatTensor = None
|
128 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
129 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
130 |
+
|
131 |
+
|
132 |
+
@dataclass
|
133 |
+
class EvaCLIPOutput(ModelOutput):
|
134 |
+
"""
|
135 |
+
Args:
|
136 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
137 |
+
Contrastive loss for image-text similarity.
|
138 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
139 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
140 |
+
similarity scores.
|
141 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
142 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
143 |
+
similarity scores.
|
144 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
145 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`EvaCLIPTextModel`].
|
146 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
147 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`EvaCLIPVisionModel`].
|
148 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
149 |
+
The output of the [`EvaCLIPTextModel`].
|
150 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
151 |
+
The output of the [`EvaCLIPVisionModel`].
|
152 |
+
"""
|
153 |
+
|
154 |
+
loss: Optional[torch.FloatTensor] = None
|
155 |
+
logits_per_image: torch.FloatTensor = None
|
156 |
+
logits_per_text: torch.FloatTensor = None
|
157 |
+
text_embeds: torch.FloatTensor = None
|
158 |
+
image_embeds: torch.FloatTensor = None
|
159 |
+
text_model_output: BaseModelOutputWithPooling = None
|
160 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
161 |
+
|
162 |
+
def to_tuple(self) -> Tuple[Any]:
|
163 |
+
return tuple(
|
164 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
165 |
+
for k in self.keys()
|
166 |
+
)
|
167 |
+
|
168 |
+
|
169 |
+
class EvaCLIPVisionEmbeddings(nn.Module):
|
170 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
171 |
+
super().__init__()
|
172 |
+
self.config = config
|
173 |
+
self.embed_dim = config.hidden_size
|
174 |
+
self.image_size = config.image_size
|
175 |
+
self.patch_size = config.patch_size
|
176 |
+
|
177 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
178 |
+
|
179 |
+
self.patch_embedding = nn.Conv2d(
|
180 |
+
in_channels=config.num_channels,
|
181 |
+
out_channels=self.embed_dim,
|
182 |
+
kernel_size=self.patch_size,
|
183 |
+
stride=self.patch_size,
|
184 |
+
bias=True,
|
185 |
+
)
|
186 |
+
|
187 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
188 |
+
self.num_positions = self.num_patches + 1
|
189 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
190 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent = False)
|
191 |
+
|
192 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
193 |
+
batch_size = pixel_values.shape[0]
|
194 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
195 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
196 |
+
|
197 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
198 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
199 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
200 |
+
return embeddings
|
201 |
+
|
202 |
+
|
203 |
+
class EvaCLIPTextEmbeddings(nn.Module):
|
204 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
205 |
+
super().__init__()
|
206 |
+
embed_dim = config.hidden_size
|
207 |
+
|
208 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
209 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
210 |
+
|
211 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
212 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
213 |
+
|
214 |
+
def forward(
|
215 |
+
self,
|
216 |
+
input_ids: Optional[torch.LongTensor] = None,
|
217 |
+
position_ids: Optional[torch.LongTensor] = None,
|
218 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
219 |
+
) -> torch.Tensor:
|
220 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
221 |
+
|
222 |
+
if position_ids is None:
|
223 |
+
position_ids = self.position_ids[:, :seq_length]
|
224 |
+
|
225 |
+
if inputs_embeds is None:
|
226 |
+
inputs_embeds = self.token_embedding(input_ids)
|
227 |
+
|
228 |
+
position_embeddings = self.position_embedding(position_ids)
|
229 |
+
embeddings = inputs_embeds + position_embeddings
|
230 |
+
|
231 |
+
return embeddings
|
232 |
+
|
233 |
+
|
234 |
+
class EvaCLIPAttention(nn.Module):
|
235 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
236 |
+
|
237 |
+
def __init__(self, config):
|
238 |
+
super().__init__()
|
239 |
+
self.config = config
|
240 |
+
self.embed_dim = config.hidden_size
|
241 |
+
self.num_heads = config.num_attention_heads
|
242 |
+
self.head_dim = self.embed_dim // self.num_heads
|
243 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
244 |
+
raise ValueError(
|
245 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
246 |
+
f" {self.num_heads})."
|
247 |
+
)
|
248 |
+
self.scale = self.head_dim**-0.5
|
249 |
+
self.dropout = config.attention_dropout
|
250 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.k_bias)
|
251 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.v_bias)
|
252 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.q_bias)
|
253 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
254 |
+
|
255 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
256 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
257 |
+
|
258 |
+
def forward(
|
259 |
+
self,
|
260 |
+
hidden_states: torch.Tensor,
|
261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
262 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
263 |
+
output_attentions: Optional[bool] = False,
|
264 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
265 |
+
"""Input shape: Batch x Time x Channel"""
|
266 |
+
|
267 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
268 |
+
|
269 |
+
# get query proj
|
270 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
271 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
272 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
273 |
+
|
274 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
275 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
276 |
+
key_states = key_states.view(*proj_shape)
|
277 |
+
value_states = value_states.view(*proj_shape)
|
278 |
+
|
279 |
+
src_len = key_states.size(1)
|
280 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
281 |
+
|
282 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
283 |
+
raise ValueError(
|
284 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
285 |
+
f" {attn_weights.size()}"
|
286 |
+
)
|
287 |
+
|
288 |
+
# apply the causal_attention_mask first
|
289 |
+
if causal_attention_mask is not None:
|
290 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
291 |
+
raise ValueError(
|
292 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
293 |
+
f" {causal_attention_mask.size()}"
|
294 |
+
)
|
295 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
296 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
297 |
+
|
298 |
+
if attention_mask is not None:
|
299 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
300 |
+
raise ValueError(
|
301 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
302 |
+
)
|
303 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
304 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
305 |
+
|
306 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
307 |
+
|
308 |
+
if output_attentions:
|
309 |
+
# this operation is a bit akward, but it's required to
|
310 |
+
# make sure that attn_weights keeps its gradient.
|
311 |
+
# In order to do so, attn_weights have to reshaped
|
312 |
+
# twice and have to be reused in the following
|
313 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
314 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
315 |
+
else:
|
316 |
+
attn_weights_reshaped = None
|
317 |
+
|
318 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
319 |
+
|
320 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
321 |
+
|
322 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
323 |
+
raise ValueError(
|
324 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
325 |
+
f" {attn_output.size()}"
|
326 |
+
)
|
327 |
+
|
328 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
329 |
+
attn_output = attn_output.transpose(1, 2)
|
330 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
331 |
+
|
332 |
+
attn_output = self.out_proj(attn_output)
|
333 |
+
|
334 |
+
return attn_output, attn_weights_reshaped
|
335 |
+
|
336 |
+
class EvaCLIPTextAttention(nn.Module):
|
337 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
338 |
+
|
339 |
+
def __init__(self, config):
|
340 |
+
super().__init__()
|
341 |
+
self.config = config
|
342 |
+
self.embed_dim = config.hidden_size
|
343 |
+
self.num_heads = config.num_attention_heads
|
344 |
+
self.head_dim = self.embed_dim // self.num_heads
|
345 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
346 |
+
raise ValueError(
|
347 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
348 |
+
f" {self.num_heads})."
|
349 |
+
)
|
350 |
+
self.scale = self.head_dim**-0.5
|
351 |
+
self.dropout = config.attention_dropout
|
352 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.k_bias)
|
353 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.v_bias)
|
354 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.q_bias)
|
355 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
356 |
+
|
357 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
358 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
359 |
+
|
360 |
+
def forward(
|
361 |
+
self,
|
362 |
+
hidden_states: torch.Tensor,
|
363 |
+
attention_mask: Optional[torch.Tensor] = None,
|
364 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
365 |
+
output_attentions: Optional[bool] = False,
|
366 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
367 |
+
"""Input shape: Batch x Time x Channel"""
|
368 |
+
|
369 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
370 |
+
|
371 |
+
# get query proj
|
372 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
373 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
374 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
375 |
+
|
376 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
377 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
378 |
+
key_states = key_states.view(*proj_shape)
|
379 |
+
value_states = value_states.view(*proj_shape)
|
380 |
+
|
381 |
+
src_len = key_states.size(1)
|
382 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
383 |
+
|
384 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
385 |
+
raise ValueError(
|
386 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
387 |
+
f" {attn_weights.size()}"
|
388 |
+
)
|
389 |
+
|
390 |
+
# apply the causal_attention_mask first
|
391 |
+
if causal_attention_mask is not None:
|
392 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
393 |
+
raise ValueError(
|
394 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
395 |
+
f" {causal_attention_mask.size()}"
|
396 |
+
)
|
397 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
398 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
399 |
+
|
400 |
+
if attention_mask is not None:
|
401 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
402 |
+
raise ValueError(
|
403 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
404 |
+
)
|
405 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
406 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
407 |
+
|
408 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
409 |
+
|
410 |
+
if output_attentions:
|
411 |
+
# this operation is a bit akward, but it's required to
|
412 |
+
# make sure that attn_weights keeps its gradient.
|
413 |
+
# In order to do so, attn_weights have to reshaped
|
414 |
+
# twice and have to be reused in the following
|
415 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
416 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
417 |
+
else:
|
418 |
+
attn_weights_reshaped = None
|
419 |
+
|
420 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
421 |
+
|
422 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
423 |
+
|
424 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
425 |
+
raise ValueError(
|
426 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
427 |
+
f" {attn_output.size()}"
|
428 |
+
)
|
429 |
+
|
430 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
431 |
+
attn_output = attn_output.transpose(1, 2)
|
432 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
433 |
+
|
434 |
+
attn_output = self.out_proj(attn_output)
|
435 |
+
|
436 |
+
return attn_output, attn_weights_reshaped
|
437 |
+
|
438 |
+
class EvaCLIPMLP(nn.Module):
|
439 |
+
def __init__(self, config):
|
440 |
+
super().__init__()
|
441 |
+
self.config = config
|
442 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
443 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
444 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
445 |
+
|
446 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
447 |
+
hidden_states = self.fc1(hidden_states)
|
448 |
+
hidden_states = self.activation_fn(hidden_states)
|
449 |
+
hidden_states = self.fc2(hidden_states)
|
450 |
+
return hidden_states
|
451 |
+
|
452 |
+
|
453 |
+
class EvaCLIPEncoderLayer(nn.Module):
|
454 |
+
def __init__(self, config: EvaCLIPConfig):
|
455 |
+
super().__init__()
|
456 |
+
self.config = config
|
457 |
+
self.embed_dim = config.hidden_size
|
458 |
+
self.post_layernorm = config.post_layernorm if config.post_layernorm is not None else False
|
459 |
+
self.self_attn = EvaCLIPAttention(config)
|
460 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
461 |
+
self.mlp = EvaCLIPMLP(config)
|
462 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
463 |
+
|
464 |
+
def forward(
|
465 |
+
self,
|
466 |
+
hidden_states: torch.Tensor,
|
467 |
+
attention_mask: torch.Tensor,
|
468 |
+
causal_attention_mask: torch.Tensor,
|
469 |
+
output_attentions: Optional[bool] = False,
|
470 |
+
) -> Tuple[torch.FloatTensor]:
|
471 |
+
"""
|
472 |
+
Args:
|
473 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
474 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
475 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
476 |
+
`(config.encoder_attention_heads,)`.
|
477 |
+
output_attentions (`bool`, *optional*):
|
478 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
479 |
+
returned tensors for more detail.
|
480 |
+
"""
|
481 |
+
residual = hidden_states
|
482 |
+
|
483 |
+
if not self.post_layernorm:
|
484 |
+
hidden_states = self.layer_norm1(hidden_states)
|
485 |
+
hidden_states, attn_weights = self.self_attn(
|
486 |
+
hidden_states=hidden_states,
|
487 |
+
attention_mask=attention_mask,
|
488 |
+
causal_attention_mask=causal_attention_mask,
|
489 |
+
output_attentions=output_attentions,
|
490 |
+
)
|
491 |
+
if self.post_layernorm:
|
492 |
+
hidden_states = self.layer_norm1(hidden_states)
|
493 |
+
hidden_states = residual + hidden_states
|
494 |
+
residual = hidden_states
|
495 |
+
if not self.post_layernorm:
|
496 |
+
hidden_states = self.layer_norm2(hidden_states)
|
497 |
+
hidden_states = self.mlp(hidden_states)
|
498 |
+
if self.post_layernorm:
|
499 |
+
hidden_states = self.layer_norm2(hidden_states)
|
500 |
+
hidden_states = residual + hidden_states
|
501 |
+
|
502 |
+
outputs = (hidden_states,)
|
503 |
+
|
504 |
+
if output_attentions:
|
505 |
+
outputs += (attn_weights,)
|
506 |
+
|
507 |
+
return outputs
|
508 |
+
|
509 |
+
|
510 |
+
class EvaCLIPPreTrainedModel(PreTrainedModel):
|
511 |
+
"""
|
512 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
513 |
+
models.
|
514 |
+
"""
|
515 |
+
|
516 |
+
config_class = EvaCLIPConfig
|
517 |
+
base_model_prefix = "clip"
|
518 |
+
supports_gradient_checkpointing = True
|
519 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
520 |
+
|
521 |
+
def _init_weights(self, module):
|
522 |
+
"""Initialize the weights"""
|
523 |
+
factor = self.config.initializer_factor
|
524 |
+
if isinstance(module, EvaCLIPTextEmbeddings):
|
525 |
+
module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
526 |
+
module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
527 |
+
elif isinstance(module, EvaCLIPVisionEmbeddings):
|
528 |
+
factor = self.config.initializer_factor
|
529 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
530 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
531 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
532 |
+
elif isinstance(module, EvaCLIPAttention):
|
533 |
+
factor = self.config.initializer_factor
|
534 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
535 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
536 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
537 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
538 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
539 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
540 |
+
elif isinstance(module, EvaCLIPMLP):
|
541 |
+
factor = self.config.initializer_factor
|
542 |
+
in_proj_std = (
|
543 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
544 |
+
)
|
545 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
546 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
547 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
548 |
+
elif isinstance(module, EvaCLIPModel):
|
549 |
+
nn.init.normal_(
|
550 |
+
module.text_projection.weight,
|
551 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
552 |
+
)
|
553 |
+
nn.init.normal_(
|
554 |
+
module.visual_projection.weight,
|
555 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
556 |
+
)
|
557 |
+
elif isinstance(module, EvaCLIPVisionModelWithProjection):
|
558 |
+
nn.init.normal_(
|
559 |
+
module.visual_projection.weight,
|
560 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
561 |
+
)
|
562 |
+
elif isinstance(module, EvaCLIPTextModelWithProjection):
|
563 |
+
nn.init.normal_(
|
564 |
+
module.text_projection.weight,
|
565 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
566 |
+
)
|
567 |
+
|
568 |
+
if isinstance(module, nn.LayerNorm):
|
569 |
+
module.bias.data.zero_()
|
570 |
+
module.weight.data.fill_(1.0)
|
571 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
572 |
+
module.bias.data.zero_()
|
573 |
+
|
574 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
575 |
+
if isinstance(module, EvaCLIPEncoder):
|
576 |
+
module.gradient_checkpointing = value
|
577 |
+
|
578 |
+
|
579 |
+
EvaCLIP_START_DOCSTRING = r"""
|
580 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
581 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
582 |
+
etc.)
|
583 |
+
|
584 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
585 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
586 |
+
and behavior.
|
587 |
+
|
588 |
+
Parameters:
|
589 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
590 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
591 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
592 |
+
"""
|
593 |
+
|
594 |
+
EvaCLIP_TEXT_INPUTS_DOCSTRING = r"""
|
595 |
+
Args:
|
596 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
597 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
598 |
+
it.
|
599 |
+
|
600 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
601 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
602 |
+
|
603 |
+
[What are input IDs?](../glossary#input-ids)
|
604 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
605 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
606 |
+
|
607 |
+
- 1 for tokens that are **not masked**,
|
608 |
+
- 0 for tokens that are **masked**.
|
609 |
+
|
610 |
+
[What are attention masks?](../glossary#attention-mask)
|
611 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
612 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
613 |
+
config.max_position_embeddings - 1]`.
|
614 |
+
|
615 |
+
[What are position IDs?](../glossary#position-ids)
|
616 |
+
output_attentions (`bool`, *optional*):
|
617 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
618 |
+
tensors for more detail.
|
619 |
+
output_hidden_states (`bool`, *optional*):
|
620 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
621 |
+
more detail.
|
622 |
+
return_dict (`bool`, *optional*):
|
623 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
624 |
+
"""
|
625 |
+
|
626 |
+
EvaCLIP_VISION_INPUTS_DOCSTRING = r"""
|
627 |
+
Args:
|
628 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
629 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
630 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
631 |
+
output_attentions (`bool`, *optional*):
|
632 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
633 |
+
tensors for more detail.
|
634 |
+
output_hidden_states (`bool`, *optional*):
|
635 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
636 |
+
more detail.
|
637 |
+
return_dict (`bool`, *optional*):
|
638 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
639 |
+
"""
|
640 |
+
|
641 |
+
EvaCLIP_INPUTS_DOCSTRING = r"""
|
642 |
+
Args:
|
643 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
644 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
645 |
+
it.
|
646 |
+
|
647 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
648 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
649 |
+
|
650 |
+
[What are input IDs?](../glossary#input-ids)
|
651 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
652 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
653 |
+
|
654 |
+
- 1 for tokens that are **not masked**,
|
655 |
+
- 0 for tokens that are **masked**.
|
656 |
+
|
657 |
+
[What are attention masks?](../glossary#attention-mask)
|
658 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
659 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
660 |
+
config.max_position_embeddings - 1]`.
|
661 |
+
|
662 |
+
[What are position IDs?](../glossary#position-ids)
|
663 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
664 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
665 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
666 |
+
return_loss (`bool`, *optional*):
|
667 |
+
Whether or not to return the contrastive loss.
|
668 |
+
output_attentions (`bool`, *optional*):
|
669 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
670 |
+
tensors for more detail.
|
671 |
+
output_hidden_states (`bool`, *optional*):
|
672 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
673 |
+
more detail.
|
674 |
+
return_dict (`bool`, *optional*):
|
675 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
676 |
+
"""
|
677 |
+
|
678 |
+
|
679 |
+
class EvaCLIPEncoder(nn.Module):
|
680 |
+
"""
|
681 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
682 |
+
[`CLIPEncoderLayer`].
|
683 |
+
|
684 |
+
Args:
|
685 |
+
config: CLIPConfig
|
686 |
+
"""
|
687 |
+
|
688 |
+
def __init__(self, config: EvaCLIPConfig):
|
689 |
+
super().__init__()
|
690 |
+
self.config = config
|
691 |
+
self.layers = nn.ModuleList([EvaCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
692 |
+
self.gradient_checkpointing = False
|
693 |
+
|
694 |
+
def forward(
|
695 |
+
self,
|
696 |
+
inputs_embeds,
|
697 |
+
attention_mask: Optional[torch.Tensor] = None,
|
698 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
699 |
+
output_attentions: Optional[bool] = None,
|
700 |
+
output_hidden_states: Optional[bool] = None,
|
701 |
+
return_dict: Optional[bool] = None,
|
702 |
+
) -> Union[Tuple, BaseModelOutput]:
|
703 |
+
r"""
|
704 |
+
Args:
|
705 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
706 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
707 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
708 |
+
than the model's internal embedding lookup matrix.
|
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 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
717 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
718 |
+
|
719 |
+
- 1 for tokens that are **not masked**,
|
720 |
+
- 0 for tokens that are **masked**.
|
721 |
+
|
722 |
+
[What are attention masks?](../glossary#attention-mask)
|
723 |
+
output_attentions (`bool`, *optional*):
|
724 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
725 |
+
returned tensors for more detail.
|
726 |
+
output_hidden_states (`bool`, *optional*):
|
727 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
728 |
+
for more detail.
|
729 |
+
return_dict (`bool`, *optional*):
|
730 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
731 |
+
"""
|
732 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
733 |
+
output_hidden_states = (
|
734 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
735 |
+
)
|
736 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
737 |
+
|
738 |
+
encoder_states = () if output_hidden_states else None
|
739 |
+
all_attentions = () if output_attentions else None
|
740 |
+
|
741 |
+
hidden_states = inputs_embeds
|
742 |
+
for idx, encoder_layer in enumerate(self.layers):
|
743 |
+
if output_hidden_states:
|
744 |
+
encoder_states = encoder_states + (hidden_states,)
|
745 |
+
if self.gradient_checkpointing and self.training:
|
746 |
+
|
747 |
+
def create_custom_forward(module):
|
748 |
+
def custom_forward(*inputs):
|
749 |
+
return module(*inputs, output_attentions)
|
750 |
+
|
751 |
+
return custom_forward
|
752 |
+
|
753 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
754 |
+
create_custom_forward(encoder_layer),
|
755 |
+
hidden_states,
|
756 |
+
attention_mask,
|
757 |
+
causal_attention_mask,
|
758 |
+
)
|
759 |
+
else:
|
760 |
+
layer_outputs = encoder_layer(
|
761 |
+
hidden_states,
|
762 |
+
attention_mask,
|
763 |
+
causal_attention_mask,
|
764 |
+
output_attentions=output_attentions,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = layer_outputs[0]
|
768 |
+
|
769 |
+
if output_attentions:
|
770 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
771 |
+
|
772 |
+
if output_hidden_states:
|
773 |
+
encoder_states = encoder_states + (hidden_states,)
|
774 |
+
|
775 |
+
if not return_dict:
|
776 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
777 |
+
return BaseModelOutput(
|
778 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
779 |
+
)
|
780 |
+
|
781 |
+
|
782 |
+
class EvaCLIPTextTransformer(nn.Module):
|
783 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
784 |
+
super().__init__()
|
785 |
+
self.config = config
|
786 |
+
embed_dim = config.hidden_size
|
787 |
+
self.embeddings = EvaCLIPTextEmbeddings(config)
|
788 |
+
self.encoder = EvaCLIPEncoder(config)
|
789 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
790 |
+
|
791 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
792 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPTextConfig)
|
793 |
+
def forward(
|
794 |
+
self,
|
795 |
+
input_ids: Optional[torch.Tensor] = None,
|
796 |
+
attention_mask: Optional[torch.Tensor] = None,
|
797 |
+
position_ids: Optional[torch.Tensor] = None,
|
798 |
+
output_attentions: Optional[bool] = None,
|
799 |
+
output_hidden_states: Optional[bool] = None,
|
800 |
+
return_dict: Optional[bool] = None,
|
801 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
802 |
+
r"""
|
803 |
+
Returns:
|
804 |
+
|
805 |
+
"""
|
806 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
807 |
+
output_hidden_states = (
|
808 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
809 |
+
)
|
810 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
811 |
+
|
812 |
+
if input_ids is None:
|
813 |
+
raise ValueError("You have to specify input_ids")
|
814 |
+
|
815 |
+
input_shape = input_ids.size()
|
816 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
817 |
+
|
818 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
819 |
+
|
820 |
+
bsz, seq_len = input_shape
|
821 |
+
# CLIP's text model uses causal mask, prepare it here.
|
822 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
823 |
+
causal_attention_mask = self._build_causal_attention_mask(bsz, seq_len, hidden_states.dtype).to(
|
824 |
+
hidden_states.device
|
825 |
+
)
|
826 |
+
# expand attention_mask
|
827 |
+
if attention_mask is not None:
|
828 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
829 |
+
attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
|
830 |
+
|
831 |
+
encoder_outputs = self.encoder(
|
832 |
+
inputs_embeds=hidden_states,
|
833 |
+
attention_mask=attention_mask,
|
834 |
+
causal_attention_mask=causal_attention_mask,
|
835 |
+
output_attentions=output_attentions,
|
836 |
+
output_hidden_states=output_hidden_states,
|
837 |
+
return_dict=return_dict,
|
838 |
+
)
|
839 |
+
|
840 |
+
last_hidden_state = encoder_outputs[0]
|
841 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
842 |
+
|
843 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
844 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
845 |
+
# casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
|
846 |
+
pooled_output = last_hidden_state[
|
847 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
848 |
+
input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
|
849 |
+
]
|
850 |
+
|
851 |
+
if not return_dict:
|
852 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
853 |
+
|
854 |
+
return BaseModelOutputWithPooling(
|
855 |
+
last_hidden_state=last_hidden_state,
|
856 |
+
pooler_output=pooled_output,
|
857 |
+
hidden_states=encoder_outputs.hidden_states,
|
858 |
+
attentions=encoder_outputs.attentions,
|
859 |
+
)
|
860 |
+
|
861 |
+
def _build_causal_attention_mask(self, bsz, seq_len, dtype):
|
862 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
863 |
+
# pytorch uses additive attention mask; fill with -inf
|
864 |
+
mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
|
865 |
+
mask.fill_(torch.tensor(torch.finfo(dtype).min))
|
866 |
+
mask.triu_(1) # zero out the lower diagonal
|
867 |
+
mask = mask.unsqueeze(1) # expand mask
|
868 |
+
return mask
|
869 |
+
|
870 |
+
|
871 |
+
@add_start_docstrings(
|
872 |
+
"""The text model from EvaCLIP without any head or projection on top.""",
|
873 |
+
EvaCLIP_START_DOCSTRING,
|
874 |
+
)
|
875 |
+
class EvaCLIPTextModel(EvaCLIPPreTrainedModel):
|
876 |
+
config_class = EvaCLIPTextConfig
|
877 |
+
|
878 |
+
_no_split_modules = ["EvaCLIPEncoderLayer"]
|
879 |
+
|
880 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
881 |
+
super().__init__(config)
|
882 |
+
self.text_model = EvaCLIPTextTransformer(config)
|
883 |
+
# Initialize weights and apply final processing
|
884 |
+
self.post_init()
|
885 |
+
|
886 |
+
def get_input_embeddings(self) -> nn.Module:
|
887 |
+
return self.text_model.embeddings.token_embedding
|
888 |
+
|
889 |
+
def set_input_embeddings(self, value):
|
890 |
+
self.text_model.embeddings.token_embedding = value
|
891 |
+
|
892 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
893 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPTextConfig)
|
894 |
+
def forward(
|
895 |
+
self,
|
896 |
+
input_ids: Optional[torch.Tensor] = None,
|
897 |
+
attention_mask: Optional[torch.Tensor] = None,
|
898 |
+
position_ids: Optional[torch.Tensor] = None,
|
899 |
+
output_attentions: Optional[bool] = None,
|
900 |
+
output_hidden_states: Optional[bool] = None,
|
901 |
+
return_dict: Optional[bool] = None,
|
902 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
903 |
+
r"""
|
904 |
+
Returns:
|
905 |
+
|
906 |
+
Examples:
|
907 |
+
|
908 |
+
```python
|
909 |
+
>>> from transformers import AutoTokenizer, CLIPTextModel
|
910 |
+
|
911 |
+
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
912 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
913 |
+
|
914 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
915 |
+
|
916 |
+
>>> outputs = model(**inputs)
|
917 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
918 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
919 |
+
```"""
|
920 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
921 |
+
|
922 |
+
return self.text_model(
|
923 |
+
input_ids=input_ids,
|
924 |
+
attention_mask=attention_mask,
|
925 |
+
position_ids=position_ids,
|
926 |
+
output_attentions=output_attentions,
|
927 |
+
output_hidden_states=output_hidden_states,
|
928 |
+
return_dict=return_dict,
|
929 |
+
)
|
930 |
+
|
931 |
+
|
932 |
+
class EvaCLIPVisionTransformer(nn.Module):
|
933 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
934 |
+
super().__init__()
|
935 |
+
self.config = config
|
936 |
+
embed_dim = config.hidden_size
|
937 |
+
|
938 |
+
self.embeddings = EvaCLIPVisionEmbeddings(config)
|
939 |
+
self.encoder = EvaCLIPEncoder(config)
|
940 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
941 |
+
|
942 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
943 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPVisionConfig)
|
944 |
+
def forward(
|
945 |
+
self,
|
946 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
947 |
+
output_attentions: Optional[bool] = None,
|
948 |
+
output_hidden_states: Optional[bool] = None,
|
949 |
+
return_dict: Optional[bool] = None,
|
950 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
951 |
+
r"""
|
952 |
+
Returns:
|
953 |
+
|
954 |
+
"""
|
955 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
956 |
+
output_hidden_states = (
|
957 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
958 |
+
)
|
959 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
960 |
+
|
961 |
+
if pixel_values is None:
|
962 |
+
raise ValueError("You have to specify pixel_values")
|
963 |
+
|
964 |
+
hidden_states = self.embeddings(pixel_values)
|
965 |
+
|
966 |
+
encoder_outputs = self.encoder(
|
967 |
+
inputs_embeds=hidden_states,
|
968 |
+
output_attentions=output_attentions,
|
969 |
+
output_hidden_states=output_hidden_states,
|
970 |
+
return_dict=return_dict,
|
971 |
+
)
|
972 |
+
|
973 |
+
last_hidden_state = encoder_outputs[0]
|
974 |
+
pooled_output = last_hidden_state[:, 0, :]
|
975 |
+
pooled_output = self.post_layernorm(pooled_output)
|
976 |
+
|
977 |
+
if not return_dict:
|
978 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
979 |
+
|
980 |
+
return BaseModelOutputWithPooling(
|
981 |
+
last_hidden_state=last_hidden_state,
|
982 |
+
pooler_output=pooled_output,
|
983 |
+
hidden_states=encoder_outputs.hidden_states,
|
984 |
+
attentions=encoder_outputs.attentions,
|
985 |
+
)
|
986 |
+
|
987 |
+
|
988 |
+
@add_start_docstrings(
|
989 |
+
"""The vision model from EvaCLIP without any head or projection on top.""",
|
990 |
+
EvaCLIP_START_DOCSTRING,
|
991 |
+
)
|
992 |
+
class EvaCLIPVisionModel(EvaCLIPPreTrainedModel):
|
993 |
+
config_class = EvaCLIPVisionConfig
|
994 |
+
main_input_name = "pixel_values"
|
995 |
+
|
996 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
997 |
+
super().__init__(config)
|
998 |
+
self.vision_model = EvaCLIPVisionTransformer(config)
|
999 |
+
# Initialize weights and apply final processing
|
1000 |
+
self.post_init()
|
1001 |
+
|
1002 |
+
def get_input_embeddings(self) -> nn.Module:
|
1003 |
+
return self.vision_model.embeddings.patch_embedding
|
1004 |
+
|
1005 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
1006 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPVisionConfig)
|
1007 |
+
def forward(
|
1008 |
+
self,
|
1009 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1010 |
+
output_attentions: Optional[bool] = None,
|
1011 |
+
output_hidden_states: Optional[bool] = None,
|
1012 |
+
return_dict: Optional[bool] = None,
|
1013 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
1014 |
+
r"""
|
1015 |
+
Returns:
|
1016 |
+
|
1017 |
+
Examples:
|
1018 |
+
|
1019 |
+
```python
|
1020 |
+
>>> from PIL import Image
|
1021 |
+
>>> import requests
|
1022 |
+
>>> from transformers import AutoProcessor, CLIPVisionModel
|
1023 |
+
|
1024 |
+
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
1025 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1026 |
+
|
1027 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1028 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1029 |
+
|
1030 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1031 |
+
|
1032 |
+
>>> outputs = model(**inputs)
|
1033 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1034 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
1035 |
+
```"""
|
1036 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1037 |
+
|
1038 |
+
return self.vision_model(
|
1039 |
+
pixel_values=pixel_values,
|
1040 |
+
output_attentions=output_attentions,
|
1041 |
+
output_hidden_states=output_hidden_states,
|
1042 |
+
return_dict=return_dict,
|
1043 |
+
)
|
1044 |
+
|
1045 |
+
|
1046 |
+
@add_start_docstrings(EvaCLIP_START_DOCSTRING)
|
1047 |
+
class EvaCLIPModel(EvaCLIPPreTrainedModel):
|
1048 |
+
config_class = EvaCLIPConfig
|
1049 |
+
|
1050 |
+
def __init__(self, config: EvaCLIPConfig):
|
1051 |
+
super().__init__(config)
|
1052 |
+
|
1053 |
+
if not (type(config.text_config).__name__ == "EvaCLIPTextConfig"):
|
1054 |
+
raise ValueError(
|
1055 |
+
"config.text_config is expected to be of type EvaCLIPTextConfig but is of type"
|
1056 |
+
f" {type(config.text_config)}."
|
1057 |
+
)
|
1058 |
+
|
1059 |
+
if not (type(config.vision_config).__name__ == "EvaCLIPVisionConfig"):
|
1060 |
+
raise ValueError(
|
1061 |
+
"config.vision_config is expected to be of type EvaCLIPVisionConfig but is of type"
|
1062 |
+
f" {type(config.vision_config)}."
|
1063 |
+
)
|
1064 |
+
|
1065 |
+
text_config = config.text_config
|
1066 |
+
vision_config = config.vision_config
|
1067 |
+
|
1068 |
+
self.projection_dim = config.projection_dim
|
1069 |
+
self.text_embed_dim = text_config.hidden_size
|
1070 |
+
self.vision_embed_dim = vision_config.hidden_size
|
1071 |
+
|
1072 |
+
self.text_model = EvaCLIPTextTransformer(text_config)
|
1073 |
+
self.vision_model = EvaCLIPVisionTransformer(vision_config)
|
1074 |
+
|
1075 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=True)
|
1076 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
1077 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * self.config.logit_scale_init_value)
|
1078 |
+
|
1079 |
+
# Initialize weights and apply final processing
|
1080 |
+
self.post_init()
|
1081 |
+
|
1082 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
1083 |
+
def get_text_features(
|
1084 |
+
self,
|
1085 |
+
input_ids: Optional[torch.Tensor] = None,
|
1086 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1087 |
+
position_ids: Optional[torch.Tensor] = None,
|
1088 |
+
output_attentions: Optional[bool] = None,
|
1089 |
+
output_hidden_states: Optional[bool] = None,
|
1090 |
+
return_dict: Optional[bool] = None,
|
1091 |
+
) -> torch.FloatTensor:
|
1092 |
+
r"""
|
1093 |
+
Returns:
|
1094 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
1095 |
+
applying the projection layer to the pooled output of [`CLIPTextModel`].
|
1096 |
+
|
1097 |
+
Examples:
|
1098 |
+
|
1099 |
+
```python
|
1100 |
+
>>> from transformers import AutoTokenizer, CLIPModel
|
1101 |
+
|
1102 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1103 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1104 |
+
|
1105 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
1106 |
+
>>> text_features = model.get_text_features(**inputs)
|
1107 |
+
```"""
|
1108 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1109 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1110 |
+
output_hidden_states = (
|
1111 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1112 |
+
)
|
1113 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1114 |
+
|
1115 |
+
text_outputs = self.text_model(
|
1116 |
+
input_ids=input_ids,
|
1117 |
+
attention_mask=attention_mask,
|
1118 |
+
position_ids=position_ids,
|
1119 |
+
output_attentions=output_attentions,
|
1120 |
+
output_hidden_states=output_hidden_states,
|
1121 |
+
return_dict=return_dict,
|
1122 |
+
)
|
1123 |
+
|
1124 |
+
pooled_output = text_outputs[1]
|
1125 |
+
text_features = self.text_projection(pooled_output)
|
1126 |
+
|
1127 |
+
return text_features
|
1128 |
+
|
1129 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
1130 |
+
def get_image_features(
|
1131 |
+
self,
|
1132 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1133 |
+
output_attentions: Optional[bool] = None,
|
1134 |
+
output_hidden_states: Optional[bool] = None,
|
1135 |
+
return_dict: Optional[bool] = None,
|
1136 |
+
) -> torch.FloatTensor:
|
1137 |
+
r"""
|
1138 |
+
Returns:
|
1139 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
1140 |
+
applying the projection layer to the pooled output of [`EvaCLIPVisionModel`].
|
1141 |
+
|
1142 |
+
Examples:
|
1143 |
+
|
1144 |
+
```python
|
1145 |
+
>>> from PIL import Image
|
1146 |
+
>>> import requests
|
1147 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
1148 |
+
|
1149 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1150 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1151 |
+
|
1152 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1153 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1154 |
+
|
1155 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1156 |
+
|
1157 |
+
>>> image_features = model.get_image_features(**inputs)
|
1158 |
+
```"""
|
1159 |
+
# Use EvaCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1160 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1161 |
+
output_hidden_states = (
|
1162 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1163 |
+
)
|
1164 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1165 |
+
|
1166 |
+
vision_outputs = self.vision_model(
|
1167 |
+
pixel_values=pixel_values,
|
1168 |
+
output_attentions=output_attentions,
|
1169 |
+
output_hidden_states=output_hidden_states,
|
1170 |
+
return_dict=return_dict,
|
1171 |
+
)
|
1172 |
+
|
1173 |
+
pooled_output = vision_outputs[1] # pooled_output
|
1174 |
+
image_features = self.visual_projection(pooled_output)
|
1175 |
+
|
1176 |
+
return image_features
|
1177 |
+
|
1178 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_INPUTS_DOCSTRING)
|
1179 |
+
@replace_return_docstrings(output_type=EvaCLIPOutput, config_class=EvaCLIPConfig)
|
1180 |
+
def forward(
|
1181 |
+
self,
|
1182 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1183 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1184 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1185 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1186 |
+
return_loss: Optional[bool] = None,
|
1187 |
+
output_attentions: Optional[bool] = None,
|
1188 |
+
output_hidden_states: Optional[bool] = None,
|
1189 |
+
return_dict: Optional[bool] = None,
|
1190 |
+
) -> Union[Tuple, EvaCLIPOutput]:
|
1191 |
+
r"""
|
1192 |
+
Returns:
|
1193 |
+
|
1194 |
+
Examples:
|
1195 |
+
|
1196 |
+
```python
|
1197 |
+
>>> from PIL import Image
|
1198 |
+
>>> import requests
|
1199 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
1200 |
+
|
1201 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1202 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1203 |
+
|
1204 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1205 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1206 |
+
|
1207 |
+
>>> inputs = processor(
|
1208 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
1209 |
+
... )
|
1210 |
+
|
1211 |
+
>>> outputs = model(**inputs)
|
1212 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
1213 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
1214 |
+
```"""
|
1215 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1216 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1217 |
+
output_hidden_states = (
|
1218 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1219 |
+
)
|
1220 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1221 |
+
|
1222 |
+
vision_outputs = self.vision_model(
|
1223 |
+
pixel_values=pixel_values,
|
1224 |
+
output_attentions=output_attentions,
|
1225 |
+
output_hidden_states=output_hidden_states,
|
1226 |
+
return_dict=return_dict,
|
1227 |
+
)
|
1228 |
+
|
1229 |
+
text_outputs = self.text_model(
|
1230 |
+
input_ids=input_ids,
|
1231 |
+
attention_mask=attention_mask,
|
1232 |
+
position_ids=position_ids,
|
1233 |
+
output_attentions=output_attentions,
|
1234 |
+
output_hidden_states=output_hidden_states,
|
1235 |
+
return_dict=return_dict,
|
1236 |
+
)
|
1237 |
+
|
1238 |
+
image_embeds = vision_outputs[1]
|
1239 |
+
image_embeds = self.visual_projection(image_embeds)
|
1240 |
+
|
1241 |
+
text_embeds = text_outputs[1]
|
1242 |
+
text_embeds = self.text_projection(text_embeds)
|
1243 |
+
|
1244 |
+
# normalized features
|
1245 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
1246 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
1247 |
+
|
1248 |
+
# cosine similarity as logits
|
1249 |
+
logit_scale = self.logit_scale.exp()
|
1250 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
1251 |
+
logits_per_image = logits_per_text.t()
|
1252 |
+
|
1253 |
+
loss = None
|
1254 |
+
if return_loss:
|
1255 |
+
loss = clip_loss(logits_per_text)
|
1256 |
+
|
1257 |
+
if not return_dict:
|
1258 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
1259 |
+
return ((loss,) + output) if loss is not None else output
|
1260 |
+
|
1261 |
+
return EvaCLIPOutput(
|
1262 |
+
loss=loss,
|
1263 |
+
logits_per_image=logits_per_image,
|
1264 |
+
logits_per_text=logits_per_text,
|
1265 |
+
text_embeds=text_embeds,
|
1266 |
+
image_embeds=image_embeds,
|
1267 |
+
text_model_output=text_outputs,
|
1268 |
+
vision_model_output=vision_outputs,
|
1269 |
+
)
|
1270 |
+
|
1271 |
+
|
1272 |
+
@add_start_docstrings(
|
1273 |
+
"""
|
1274 |
+
EvaCLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
|
1275 |
+
""",
|
1276 |
+
EvaCLIP_START_DOCSTRING,
|
1277 |
+
)
|
1278 |
+
class EvaCLIPTextModelWithProjection(EvaCLIPPreTrainedModel):
|
1279 |
+
config_class = EvaCLIPTextConfig
|
1280 |
+
|
1281 |
+
_no_split_modules = ["EvaCLIPEncoderLayer"]
|
1282 |
+
|
1283 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
1284 |
+
super().__init__(config)
|
1285 |
+
|
1286 |
+
self.text_model = EvaCLIPTextTransformer(config)
|
1287 |
+
|
1288 |
+
self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
1289 |
+
|
1290 |
+
# Initialize weights and apply final processing
|
1291 |
+
self.posxt_init()
|
1292 |
+
|
1293 |
+
def get_input_embeddings(self) -> nn.Module:
|
1294 |
+
return self.text_model.embeddings.token_embedding
|
1295 |
+
|
1296 |
+
def set_input_embeddings(self, value):
|
1297 |
+
self.text_model.embeddings.token_embedding = value
|
1298 |
+
|
1299 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
1300 |
+
@replace_return_docstrings(output_type=EvaCLIPTextModelOutput, config_class=EvaCLIPTextConfig)
|
1301 |
+
def forward(
|
1302 |
+
self,
|
1303 |
+
input_ids: Optional[torch.Tensor] = None,
|
1304 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1305 |
+
position_ids: Optional[torch.Tensor] = None,
|
1306 |
+
output_attentions: Optional[bool] = None,
|
1307 |
+
output_hidden_states: Optional[bool] = None,
|
1308 |
+
return_dict: Optional[bool] = None,
|
1309 |
+
) -> Union[Tuple, EvaCLIPTextModelOutput]:
|
1310 |
+
r"""
|
1311 |
+
Returns:
|
1312 |
+
|
1313 |
+
Examples:
|
1314 |
+
|
1315 |
+
```python
|
1316 |
+
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
|
1317 |
+
|
1318 |
+
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
1319 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1320 |
+
|
1321 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
1322 |
+
|
1323 |
+
>>> outputs = model(**inputs)
|
1324 |
+
>>> text_embeds = outputs.text_embeds
|
1325 |
+
```"""
|
1326 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1327 |
+
|
1328 |
+
text_outputs = self.text_model(
|
1329 |
+
input_ids=input_ids,
|
1330 |
+
attention_mask=attention_mask,
|
1331 |
+
position_ids=position_ids,
|
1332 |
+
output_attentions=output_attentions,
|
1333 |
+
output_hidden_states=output_hidden_states,
|
1334 |
+
return_dict=return_dict,
|
1335 |
+
)
|
1336 |
+
|
1337 |
+
pooled_output = text_outputs[1]
|
1338 |
+
|
1339 |
+
text_embeds = self.text_projection(pooled_output)
|
1340 |
+
|
1341 |
+
if not return_dict:
|
1342 |
+
outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
|
1343 |
+
return tuple(output for output in outputs if output is not None)
|
1344 |
+
|
1345 |
+
return EvaCLIPTextModelOutput(
|
1346 |
+
text_embeds=text_embeds,
|
1347 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
1348 |
+
hidden_states=text_outputs.hidden_states,
|
1349 |
+
attentions=text_outputs.attentions,
|
1350 |
+
)
|
1351 |
+
|
1352 |
+
|
1353 |
+
@add_start_docstrings(
|
1354 |
+
"""
|
1355 |
+
EvaCLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
|
1356 |
+
""",
|
1357 |
+
EvaCLIP_START_DOCSTRING,
|
1358 |
+
)
|
1359 |
+
class EvaCLIPVisionModelWithProjection(EvaCLIPPreTrainedModel):
|
1360 |
+
config_class = EvaCLIPVisionConfig
|
1361 |
+
main_input_name = "pixel_values"
|
1362 |
+
|
1363 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
1364 |
+
super().__init__(config)
|
1365 |
+
|
1366 |
+
self.vision_model = EvaCLIPVisionTransformer(config)
|
1367 |
+
|
1368 |
+
self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
1369 |
+
|
1370 |
+
# Initialize weights and apply final processing
|
1371 |
+
self.post_init()
|
1372 |
+
|
1373 |
+
def get_input_embeddings(self) -> nn.Module:
|
1374 |
+
return self.vision_model.embeddings.patch_embedding
|
1375 |
+
|
1376 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
1377 |
+
@replace_return_docstrings(output_type=EvaCLIPVisionModelOutput, config_class=EvaCLIPVisionConfig)
|
1378 |
+
def forward(
|
1379 |
+
self,
|
1380 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1381 |
+
output_attentions: Optional[bool] = None,
|
1382 |
+
output_hidden_states: Optional[bool] = None,
|
1383 |
+
return_dict: Optional[bool] = None,
|
1384 |
+
) -> Union[Tuple, EvaCLIPVisionModelOutput]:
|
1385 |
+
r"""
|
1386 |
+
Returns:
|
1387 |
+
|
1388 |
+
Examples:
|
1389 |
+
|
1390 |
+
```python
|
1391 |
+
>>> from PIL import Image
|
1392 |
+
>>> import requests
|
1393 |
+
>>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
|
1394 |
+
|
1395 |
+
>>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
1396 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1397 |
+
|
1398 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1399 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1400 |
+
|
1401 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1402 |
+
|
1403 |
+
>>> outputs = model(**inputs)
|
1404 |
+
>>> image_embeds = outputs.image_embeds
|
1405 |
+
```"""
|
1406 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1407 |
+
|
1408 |
+
vision_outputs = self.vision_model(
|
1409 |
+
pixel_values=pixel_values,
|
1410 |
+
output_attentions=output_attentions,
|
1411 |
+
output_hidden_states=output_hidden_states,
|
1412 |
+
return_dict=return_dict,
|
1413 |
+
)
|
1414 |
+
|
1415 |
+
pooled_output = vision_outputs[1] # pooled_output
|
1416 |
+
|
1417 |
+
image_embeds = self.visual_projection(pooled_output)
|
1418 |
+
|
1419 |
+
if not return_dict:
|
1420 |
+
outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
1421 |
+
return tuple(output for output in outputs if output is not None)
|
1422 |
+
|
1423 |
+
return EvaCLIPVisionModelOutput(
|
1424 |
+
image_embeds=image_embeds,
|
1425 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
1426 |
+
hidden_states=vision_outputs.hidden_states,
|
1427 |
+
attentions=vision_outputs.attentions,
|
1428 |
+
)
|
EVA02-CLIP-bigE-14-plus_s9B/special_tokens_map.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|startoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": "<|endoftext|>",
|
17 |
+
"unk_token": {
|
18 |
+
"content": "<|endoftext|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": true,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
}
|
24 |
+
}
|
EVA02-CLIP-bigE-14-plus_s9B/tokenizer_config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"__type": "AddedToken",
|
4 |
+
"content": "<|startoftext|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": true,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
},
|
10 |
+
"eos_token": {
|
11 |
+
"__type": "AddedToken",
|
12 |
+
"content": "<|endoftext|>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": true,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false
|
17 |
+
},
|
18 |
+
"errors": "replace",
|
19 |
+
"model_max_length": 1000000000000000019884624838656,
|
20 |
+
"pad_token": "<|endoftext|>",
|
21 |
+
"special_tokens_map_file": null,
|
22 |
+
"tokenizer_class": "CLIPTokenizer",
|
23 |
+
"unk_token": {
|
24 |
+
"__type": "AddedToken",
|
25 |
+
"content": "<|endoftext|>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": true,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
}
|
31 |
+
}
|
EVA02-CLIP-bigE-14-plus_s9B/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|