Upload 10 files
Browse filesinitial model upload
- LICENSE +21 -0
- config.json +111 -0
- configuration_git.py +164 -0
- generation_config.json +7 -0
- modeling_git.py +222 -0
- preprocessor_config.json +23 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +7 -0
- tokenizer.json +0 -0
- tokenizer_config.json +5 -0
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) [2024] [Chengxu Zhuang]
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
config.json
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "babylm/git-2024",
|
3 |
+
"architectures": [
|
4 |
+
"GitForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_git.GitConfig",
|
9 |
+
"AutoModelForCausalLM": "modeling_git.GitForCausalLM",
|
10 |
+
"AutoModelForSequenceClassification": "modeling_git.GitForSequenceClassification"
|
11 |
+
},
|
12 |
+
"bos_token_id": 101,
|
13 |
+
"classifier_dropout": null,
|
14 |
+
"eos_token_id": 102,
|
15 |
+
"hidden_act": "gelu",
|
16 |
+
"hidden_dropout_prob": 0.1,
|
17 |
+
"hidden_size": 768,
|
18 |
+
"initializer_range": 0.02,
|
19 |
+
"intermediate_size": 3072,
|
20 |
+
"layer_norm_eps": 1e-12,
|
21 |
+
"max_position_embeddings": 1024,
|
22 |
+
"model_type": "git",
|
23 |
+
"num_attention_heads": 12,
|
24 |
+
"num_hidden_layers": 12,
|
25 |
+
"num_image_with_embedding": null,
|
26 |
+
"pad_token_id": 0,
|
27 |
+
"position_embedding_type": "absolute",
|
28 |
+
"torch_dtype": "float32",
|
29 |
+
"transformers_version": "4.26.0",
|
30 |
+
"use_cache": true,
|
31 |
+
"vision_config": {
|
32 |
+
"_commit_hash": null,
|
33 |
+
"_name_or_path": "",
|
34 |
+
"add_cross_attention": false,
|
35 |
+
"architectures": null,
|
36 |
+
"attention_dropout": 0.0,
|
37 |
+
"bad_words_ids": null,
|
38 |
+
"begin_suppress_tokens": null,
|
39 |
+
"bos_token_id": null,
|
40 |
+
"chunk_size_feed_forward": 0,
|
41 |
+
"cross_attention_hidden_size": null,
|
42 |
+
"decoder_start_token_id": null,
|
43 |
+
"diversity_penalty": 0.0,
|
44 |
+
"do_sample": false,
|
45 |
+
"dropout": 0.0,
|
46 |
+
"early_stopping": false,
|
47 |
+
"encoder_no_repeat_ngram_size": 0,
|
48 |
+
"eos_token_id": null,
|
49 |
+
"exponential_decay_length_penalty": null,
|
50 |
+
"finetuning_task": null,
|
51 |
+
"forced_bos_token_id": null,
|
52 |
+
"forced_eos_token_id": null,
|
53 |
+
"hidden_act": "quick_gelu",
|
54 |
+
"hidden_size": 768,
|
55 |
+
"id2label": {
|
56 |
+
"0": "LABEL_0",
|
57 |
+
"1": "LABEL_1"
|
58 |
+
},
|
59 |
+
"image_size": 224,
|
60 |
+
"initializer_factor": 1.0,
|
61 |
+
"initializer_range": 0.02,
|
62 |
+
"intermediate_size": 4096,
|
63 |
+
"is_decoder": false,
|
64 |
+
"is_encoder_decoder": false,
|
65 |
+
"label2id": {
|
66 |
+
"LABEL_0": 0,
|
67 |
+
"LABEL_1": 1
|
68 |
+
},
|
69 |
+
"layer_norm_eps": 1e-05,
|
70 |
+
"length_penalty": 1.0,
|
71 |
+
"max_length": 20,
|
72 |
+
"min_length": 0,
|
73 |
+
"model_type": "git_vision_model",
|
74 |
+
"no_repeat_ngram_size": 0,
|
75 |
+
"num_attention_heads": 16,
|
76 |
+
"num_beam_groups": 1,
|
77 |
+
"num_beams": 1,
|
78 |
+
"num_channels": 3,
|
79 |
+
"num_hidden_layers": 24,
|
80 |
+
"num_return_sequences": 1,
|
81 |
+
"output_attentions": false,
|
82 |
+
"output_hidden_states": false,
|
83 |
+
"output_scores": false,
|
84 |
+
"pad_token_id": null,
|
85 |
+
"patch_size": 14,
|
86 |
+
"prefix": null,
|
87 |
+
"problem_type": null,
|
88 |
+
"projection_dim": 512,
|
89 |
+
"pruned_heads": {},
|
90 |
+
"remove_invalid_values": false,
|
91 |
+
"repetition_penalty": 1.0,
|
92 |
+
"return_dict": true,
|
93 |
+
"return_dict_in_generate": false,
|
94 |
+
"sep_token_id": null,
|
95 |
+
"suppress_tokens": null,
|
96 |
+
"task_specific_params": null,
|
97 |
+
"temperature": 1.0,
|
98 |
+
"tf_legacy_loss": false,
|
99 |
+
"tie_encoder_decoder": false,
|
100 |
+
"tie_word_embeddings": true,
|
101 |
+
"tokenizer_class": null,
|
102 |
+
"top_k": 50,
|
103 |
+
"top_p": 1.0,
|
104 |
+
"torch_dtype": null,
|
105 |
+
"torchscript": false,
|
106 |
+
"transformers_version": "4.29.0",
|
107 |
+
"typical_p": 1.0,
|
108 |
+
"use_bfloat16": false
|
109 |
+
},
|
110 |
+
"vocab_size": 32778
|
111 |
+
}
|
configuration_git.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 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 |
+
import os
|
17 |
+
from typing import Union
|
18 |
+
|
19 |
+
from transformers.configuration_utils import PretrainedConfig
|
20 |
+
import transformers.models.git.configuration_git as configuration_git
|
21 |
+
|
22 |
+
|
23 |
+
GIT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
24 |
+
"microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json",
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
class GitVisionConfig(configuration_git.GitVisionConfig, dict):
|
29 |
+
def __init__(self, *args, **kwargs):
|
30 |
+
configuration_git.GitVisionConfig.__init__(
|
31 |
+
self, *args, **kwargs)
|
32 |
+
dict.__init__(self, **self.__dict__)
|
33 |
+
|
34 |
+
def toJSON(self):
|
35 |
+
return json.dumps(
|
36 |
+
self,
|
37 |
+
default=lambda o: o.__dict__,
|
38 |
+
sort_keys=True,
|
39 |
+
indent=4)
|
40 |
+
|
41 |
+
|
42 |
+
class GitConfig(PretrainedConfig, dict):
|
43 |
+
r"""
|
44 |
+
This is the configuration class to store the configuration of a [`GitModel`]. It is used to instantiate a GIT model
|
45 |
+
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
46 |
+
defaults will yield a similar configuration to that of the GIT
|
47 |
+
[microsoft/git-base](https://huggingface.co/microsoft/git-base) architecture.
|
48 |
+
|
49 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
50 |
+
documentation from [`PretrainedConfig`] for more information.
|
51 |
+
|
52 |
+
Args:
|
53 |
+
vision_config (`dict`, *optional*):
|
54 |
+
Dictionary of configuration options used to initialize [`GitVisionConfig`].
|
55 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
56 |
+
Vocabulary size of the GIT model. Defines the number of different tokens that can be represented by the
|
57 |
+
`inputs_ids` passed when calling [`GitModel`].
|
58 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
59 |
+
Dimensionality of the encoder layers and the pooler layer.
|
60 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
61 |
+
Number of hidden layers in the Transformer encoder.
|
62 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
63 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
64 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
65 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
66 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
67 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
68 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
69 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
70 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
71 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
72 |
+
The dropout ratio for the attention probabilities.
|
73 |
+
max_position_embeddings (`int`, *optional*, defaults to 1024):
|
74 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
75 |
+
just in case (e.g., 512 or 1024 or 2048).
|
76 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
78 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
79 |
+
The epsilon used by the layer normalization layers.
|
80 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
81 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
82 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
83 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
84 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
85 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
86 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
87 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
88 |
+
num_image_with_embedding (`int`, *optional*):
|
89 |
+
The number of temporal embeddings to add, in case the model is used for video captioning/VQA.
|
90 |
+
|
91 |
+
Examples:
|
92 |
+
|
93 |
+
```python
|
94 |
+
>>> from transformers import GitConfig, GitModel
|
95 |
+
|
96 |
+
>>> # Initializing a GIT microsoft/git-base style configuration
|
97 |
+
>>> configuration = GitConfig()
|
98 |
+
|
99 |
+
>>> # Initializing a model (with random weights) from the microsoft/git-base style configuration
|
100 |
+
>>> model = GitModel(configuration)
|
101 |
+
|
102 |
+
>>> # Accessing the model configuration
|
103 |
+
>>> configuration = model.config
|
104 |
+
```"""
|
105 |
+
|
106 |
+
model_type = "git"
|
107 |
+
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
vision_config=None,
|
111 |
+
vocab_size=32778,
|
112 |
+
hidden_size=768,
|
113 |
+
num_hidden_layers=6,
|
114 |
+
num_attention_heads=12,
|
115 |
+
intermediate_size=3072,
|
116 |
+
hidden_act="gelu",
|
117 |
+
hidden_dropout_prob=0.1,
|
118 |
+
attention_probs_dropout_prob=0.1,
|
119 |
+
max_position_embeddings=1024,
|
120 |
+
initializer_range=0.02,
|
121 |
+
layer_norm_eps=1e-12,
|
122 |
+
pad_token_id=0,
|
123 |
+
position_embedding_type="absolute",
|
124 |
+
use_cache=True,
|
125 |
+
tie_word_embeddings=True,
|
126 |
+
bos_token_id=101,
|
127 |
+
eos_token_id=102,
|
128 |
+
num_image_with_embedding=None,
|
129 |
+
**kwargs,
|
130 |
+
):
|
131 |
+
PretrainedConfig.__init__(
|
132 |
+
self,
|
133 |
+
bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs)
|
134 |
+
|
135 |
+
if vision_config is None:
|
136 |
+
vision_config = {}
|
137 |
+
self.vision_config = GitVisionConfig(**vision_config)
|
138 |
+
self.vocab_size = vocab_size
|
139 |
+
self.hidden_size = hidden_size
|
140 |
+
self.num_hidden_layers = num_hidden_layers
|
141 |
+
self.num_attention_heads = num_attention_heads
|
142 |
+
self.hidden_act = hidden_act
|
143 |
+
self.intermediate_size = intermediate_size
|
144 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
145 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
146 |
+
self.max_position_embeddings = max_position_embeddings
|
147 |
+
self.initializer_range = initializer_range
|
148 |
+
self.layer_norm_eps = layer_norm_eps
|
149 |
+
self.position_embedding_type = position_embedding_type
|
150 |
+
self.use_cache = use_cache
|
151 |
+
self.tie_word_embeddings = tie_word_embeddings
|
152 |
+
self.num_image_with_embedding = num_image_with_embedding
|
153 |
+
|
154 |
+
self.bos_token_id = bos_token_id
|
155 |
+
self.eos_token_id = eos_token_id
|
156 |
+
|
157 |
+
dict.__init__(self, **self.__dict__)
|
158 |
+
|
159 |
+
def toJSON(self):
|
160 |
+
return json.dumps(
|
161 |
+
self,
|
162 |
+
default=lambda o: o.__dict__,
|
163 |
+
sort_keys=True,
|
164 |
+
indent=4)
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 101,
|
4 |
+
"eos_token_id": 102,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"transformers_version": "4.29.0"
|
7 |
+
}
|
modeling_git.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import transformers
|
2 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
3 |
+
from transformers import ViTFeatureExtractor, ViTModel, ViTConfig
|
4 |
+
from typing import List, Optional, Tuple, Union
|
5 |
+
import warnings
|
6 |
+
import ipdb
|
7 |
+
import os
|
8 |
+
import torch
|
9 |
+
from torch import nn
|
10 |
+
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss, MSELoss
|
11 |
+
from itertools import product
|
12 |
+
import numpy as np
|
13 |
+
import transformers.models.git.modeling_git as modeling_git
|
14 |
+
import transformers.models.vit.modeling_vit as modeling_vit
|
15 |
+
from transformers.models.opt.modeling_opt import OPTConfig
|
16 |
+
import transformers.models.opt.modeling_opt as hg_opt
|
17 |
+
import transformers.models.clip.modeling_clip as modeling_clip
|
18 |
+
from transformers.modeling_outputs import SequenceClassifierOutputWithPast
|
19 |
+
|
20 |
+
|
21 |
+
class GitForCausalLM(modeling_git.GitForCausalLM):
|
22 |
+
def __init__(self, *args, **kwargs):
|
23 |
+
super().__init__(*args, **kwargs)
|
24 |
+
|
25 |
+
del self.output
|
26 |
+
self.output = nn.Linear(
|
27 |
+
self.config.hidden_size,
|
28 |
+
self.config.vocab_size,
|
29 |
+
bias=False)
|
30 |
+
self.post_init()
|
31 |
+
|
32 |
+
del self.git.image_encoder
|
33 |
+
self.git.image_encoder = ViTModel.from_pretrained('facebook/dino-vitb16')
|
34 |
+
dino_cfg = self.git.image_encoder.config
|
35 |
+
config = self.git.config
|
36 |
+
config.vision_config.hidden_size = dino_cfg.hidden_size
|
37 |
+
|
38 |
+
del self.git.visual_projection
|
39 |
+
self.git.visual_projection = modeling_git.GitProjection(config)
|
40 |
+
num_tks = (dino_cfg.image_size // dino_cfg.patch_size) ** 2 + 1
|
41 |
+
self.git.encoder.layer[0].attention.self.image_patch_tokens = num_tks
|
42 |
+
|
43 |
+
def forward(
|
44 |
+
self,
|
45 |
+
input_ids: Optional[torch.Tensor] = None,
|
46 |
+
attention_mask: Optional[torch.Tensor] = None,
|
47 |
+
position_ids: Optional[torch.Tensor] = None,
|
48 |
+
pixel_values: Optional[torch.Tensor] = None,
|
49 |
+
head_mask: Optional[torch.Tensor] = None,
|
50 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
51 |
+
labels: Optional[torch.Tensor] = None,
|
52 |
+
past_key_values: Optional[List[torch.Tensor]] = None,
|
53 |
+
use_cache: Optional[bool] = None,
|
54 |
+
output_attentions: Optional[bool] = None,
|
55 |
+
output_hidden_states: Optional[bool] = None,
|
56 |
+
return_dict: Optional[bool] = None,
|
57 |
+
) -> Union[Tuple[torch.Tensor], modeling_git.CausalLMOutputWithPast]:
|
58 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
59 |
+
if labels is not None:
|
60 |
+
use_cache = False
|
61 |
+
|
62 |
+
outputs = self.git(
|
63 |
+
input_ids,
|
64 |
+
attention_mask=attention_mask,
|
65 |
+
position_ids=position_ids,
|
66 |
+
pixel_values=pixel_values,
|
67 |
+
head_mask=head_mask,
|
68 |
+
inputs_embeds=inputs_embeds,
|
69 |
+
past_key_values=past_key_values,
|
70 |
+
use_cache=use_cache,
|
71 |
+
output_attentions=output_attentions,
|
72 |
+
output_hidden_states=output_hidden_states,
|
73 |
+
return_dict=return_dict,
|
74 |
+
)
|
75 |
+
|
76 |
+
sequence_output = outputs[0]
|
77 |
+
logits = self.output(sequence_output)
|
78 |
+
|
79 |
+
loss = None
|
80 |
+
if labels is not None:
|
81 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
82 |
+
if pixel_values is not None:
|
83 |
+
num_image_tokens = self.git.encoder.layer[0].attention.self.image_patch_tokens
|
84 |
+
else:
|
85 |
+
num_image_tokens = 0
|
86 |
+
shifted_logits = logits[:, num_image_tokens:-1, :].contiguous()
|
87 |
+
labels = labels[:, 1:].contiguous()
|
88 |
+
loss_fct = CrossEntropyLoss()
|
89 |
+
loss = loss_fct(shifted_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
90 |
+
|
91 |
+
if not return_dict:
|
92 |
+
output = (logits,) + outputs[1:]
|
93 |
+
return ((loss,) + output) if loss is not None else output
|
94 |
+
|
95 |
+
return modeling_git.CausalLMOutputWithPast(
|
96 |
+
loss=loss,
|
97 |
+
logits=logits,
|
98 |
+
past_key_values=outputs.past_key_values,
|
99 |
+
hidden_states=outputs.hidden_states,
|
100 |
+
attentions=outputs.attentions,
|
101 |
+
)
|
102 |
+
|
103 |
+
|
104 |
+
class GitForSequenceClassification(modeling_git.GitPreTrainedModel):
|
105 |
+
def __init__(self, *args, **kwargs):
|
106 |
+
super().__init__(*args, **kwargs)
|
107 |
+
self.num_labels = self.config.num_labels
|
108 |
+
self.classifier = nn.Linear(
|
109 |
+
self.config.hidden_size,
|
110 |
+
self.config.num_labels,
|
111 |
+
bias=False)
|
112 |
+
self.post_init()
|
113 |
+
self.git = modeling_git.GitModel(self.config)
|
114 |
+
|
115 |
+
del self.git.image_encoder
|
116 |
+
self.git.image_encoder = ViTModel.from_pretrained('facebook/dino-vitb16')
|
117 |
+
dino_cfg = self.git.image_encoder.config
|
118 |
+
config = self.git.config
|
119 |
+
config.vision_config.hidden_size = dino_cfg.hidden_size
|
120 |
+
|
121 |
+
del self.git.visual_projection
|
122 |
+
self.git.visual_projection = modeling_git.GitProjection(config)
|
123 |
+
num_tks = (dino_cfg.image_size // dino_cfg.patch_size) ** 2 + 1
|
124 |
+
self.git.encoder.layer[0].attention.self.image_patch_tokens = num_tks
|
125 |
+
|
126 |
+
def forward(
|
127 |
+
self,
|
128 |
+
input_ids: Optional[torch.LongTensor] = None,
|
129 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
130 |
+
position_ids: Optional[torch.Tensor] = None,
|
131 |
+
pixel_values: Optional[torch.Tensor] = None,
|
132 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
133 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
134 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
135 |
+
labels: Optional[torch.LongTensor] = None,
|
136 |
+
use_cache: Optional[bool] = None,
|
137 |
+
output_attentions: Optional[bool] = None,
|
138 |
+
output_hidden_states: Optional[bool] = None,
|
139 |
+
return_dict: Optional[bool] = None,
|
140 |
+
*args, **kwargs) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
141 |
+
r"""
|
142 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
143 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
144 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
145 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
146 |
+
"""
|
147 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
148 |
+
|
149 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
150 |
+
outputs = self.git(
|
151 |
+
input_ids,
|
152 |
+
attention_mask=attention_mask,
|
153 |
+
position_ids=position_ids,
|
154 |
+
pixel_values=pixel_values,
|
155 |
+
head_mask=head_mask,
|
156 |
+
inputs_embeds=inputs_embeds,
|
157 |
+
past_key_values=past_key_values,
|
158 |
+
use_cache=use_cache,
|
159 |
+
output_attentions=output_attentions,
|
160 |
+
output_hidden_states=output_hidden_states,
|
161 |
+
return_dict=return_dict,
|
162 |
+
*args, **kwargs)
|
163 |
+
|
164 |
+
hidden_states = outputs[0]
|
165 |
+
logits = self.classifier(hidden_states)
|
166 |
+
|
167 |
+
if input_ids is not None:
|
168 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
169 |
+
else:
|
170 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
171 |
+
|
172 |
+
if self.config.pad_token_id is None:
|
173 |
+
sequence_lengths = -1
|
174 |
+
else:
|
175 |
+
if input_ids is not None:
|
176 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
177 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
178 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
179 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
180 |
+
else:
|
181 |
+
sequence_lengths = -1
|
182 |
+
# logger.warning(
|
183 |
+
# f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
184 |
+
# "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
185 |
+
# )
|
186 |
+
|
187 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
188 |
+
|
189 |
+
loss = None
|
190 |
+
if labels is not None:
|
191 |
+
if self.config.problem_type is None:
|
192 |
+
if self.num_labels == 1:
|
193 |
+
self.config.problem_type = "regression"
|
194 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
195 |
+
self.config.problem_type = "single_label_classification"
|
196 |
+
else:
|
197 |
+
self.config.problem_type = "multi_label_classification"
|
198 |
+
|
199 |
+
if self.config.problem_type == "regression":
|
200 |
+
loss_fct = MSELoss()
|
201 |
+
if self.num_labels == 1:
|
202 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
203 |
+
else:
|
204 |
+
loss = loss_fct(pooled_logits, labels)
|
205 |
+
elif self.config.problem_type == "single_label_classification":
|
206 |
+
loss_fct = CrossEntropyLoss()
|
207 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
208 |
+
elif self.config.problem_type == "multi_label_classification":
|
209 |
+
loss_fct = BCEWithLogitsLoss()
|
210 |
+
loss = loss_fct(pooled_logits, labels)
|
211 |
+
|
212 |
+
if not return_dict:
|
213 |
+
output = (pooled_logits,) + outputs[1:]
|
214 |
+
return ((loss,) + output) if loss is not None else output
|
215 |
+
|
216 |
+
return SequenceClassifierOutputWithPast(
|
217 |
+
loss=loss,
|
218 |
+
logits=pooled_logits,
|
219 |
+
past_key_values=outputs.past_key_values,
|
220 |
+
hidden_states=outputs.hidden_states,
|
221 |
+
attentions=outputs.attentions,
|
222 |
+
)
|
preprocessor_config.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_normalize": true,
|
3 |
+
"do_rescale": true,
|
4 |
+
"do_resize": true,
|
5 |
+
"feature_extractor_type": "ViTFeatureExtractor",
|
6 |
+
"image_mean": [
|
7 |
+
0.485,
|
8 |
+
0.456,
|
9 |
+
0.406
|
10 |
+
],
|
11 |
+
"image_processor_type": "ViTFeatureExtractor",
|
12 |
+
"image_std": [
|
13 |
+
0.229,
|
14 |
+
0.224,
|
15 |
+
0.225
|
16 |
+
],
|
17 |
+
"resample": 2,
|
18 |
+
"rescale_factor": 0.00392156862745098,
|
19 |
+
"size": {
|
20 |
+
"height": 224,
|
21 |
+
"width": 224
|
22 |
+
}
|
23 |
+
}
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:25fee1e657ff31aca979697af1523a1de5d5468319c50fe6d5dff386c6bfa44b
|
3 |
+
size 792131918
|
special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<image>",
|
4 |
+
"<PERSON>"
|
5 |
+
],
|
6 |
+
"pad_token": "<pad>"
|
7 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"clean_up_tokenization_spaces": true,
|
3 |
+
"model_max_length": 1000000000000000019884624838656,
|
4 |
+
"tokenizer_class": "PreTrainedTokenizerFast"
|
5 |
+
}
|