simpleParadox
commited on
Upload 10 files
Browse files- config.json +43 -0
- configuration_git.py +164 -0
- generation_config.json +7 -0
- model.safetensors +3 -0
- modeling_git.py +252 -0
- preprocessor_config.json +23 -0
- special_tokens_map.json +37 -0
- tokenizer.json +0 -0
- tokenizer_config.json +60 -0
- vocab.txt +0 -0
config.json
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"manual_seed": 0,
|
22 |
+
"max_position_embeddings": 1024,
|
23 |
+
"model_type": "git",
|
24 |
+
"num_attention_heads": 12,
|
25 |
+
"num_hidden_layers": 12,
|
26 |
+
"num_image_with_embedding": null,
|
27 |
+
"pad_token_id": 0,
|
28 |
+
"position_embedding_type": "absolute",
|
29 |
+
"torch_dtype": "float32",
|
30 |
+
"transformers_version": "4.38.2",
|
31 |
+
"use_cache": true,
|
32 |
+
"vision_config": {
|
33 |
+
"dropout": 0.0,
|
34 |
+
"initializer_factor": 1.0,
|
35 |
+
"intermediate_size": 4096,
|
36 |
+
"model_type": "git_vision_model",
|
37 |
+
"num_attention_heads": 16,
|
38 |
+
"num_hidden_layers": 24,
|
39 |
+
"patch_size": 14,
|
40 |
+
"projection_dim": 512
|
41 |
+
},
|
42 |
+
"vocab_size": 32778
|
43 |
+
}
|
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.38.2"
|
7 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9aa0781f89d7ce8a6568d7f330fdcbb0985517ef5ebc3e0a1465afd6e5450342
|
3 |
+
size 792038744
|
modeling_git.py
ADDED
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from .configuration_git import GitConfig
|
21 |
+
|
22 |
+
import random
|
23 |
+
|
24 |
+
|
25 |
+
class GitForCausalLM(modeling_git.GitForCausalLM):
|
26 |
+
config_class = GitConfig
|
27 |
+
|
28 |
+
def __init__(self, *args, **kwargs):
|
29 |
+
super().__init__(*args, **kwargs)
|
30 |
+
|
31 |
+
torch.backends.cudnn.deterministic = True
|
32 |
+
torch.backends.cudnn.benchmark = True
|
33 |
+
torch.use_deterministic_algorithms(True)
|
34 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
35 |
+
torch.backends.cudnn.allow_tf32 = True
|
36 |
+
|
37 |
+
random.seed(0)
|
38 |
+
np.random.seed(0)
|
39 |
+
torch.manual_seed(0)
|
40 |
+
torch.cuda.manual_seed_all(0)
|
41 |
+
|
42 |
+
|
43 |
+
del self.output
|
44 |
+
self.output = nn.Linear(
|
45 |
+
self.config.hidden_size,
|
46 |
+
self.config.vocab_size,
|
47 |
+
bias=False)
|
48 |
+
self.post_init()
|
49 |
+
|
50 |
+
del self.git.image_encoder
|
51 |
+
self.git.image_encoder = ViTModel.from_pretrained('facebook/dino-vitb16')
|
52 |
+
dino_cfg = self.git.image_encoder.config
|
53 |
+
config = self.git.config
|
54 |
+
config.vision_config.hidden_size = dino_cfg.hidden_size
|
55 |
+
|
56 |
+
del self.git.visual_projection
|
57 |
+
self.git.visual_projection = modeling_git.GitProjection(config)
|
58 |
+
num_tks = (dino_cfg.image_size // dino_cfg.patch_size) ** 2 + 1
|
59 |
+
self.git.encoder.layer[0].attention.self.image_patch_tokens = num_tks
|
60 |
+
|
61 |
+
def forward(
|
62 |
+
self,
|
63 |
+
input_ids: Optional[torch.Tensor] = None,
|
64 |
+
attention_mask: Optional[torch.Tensor] = None,
|
65 |
+
position_ids: Optional[torch.Tensor] = None,
|
66 |
+
pixel_values: Optional[torch.Tensor] = None,
|
67 |
+
head_mask: Optional[torch.Tensor] = None,
|
68 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
69 |
+
labels: Optional[torch.Tensor] = None,
|
70 |
+
past_key_values: Optional[List[torch.Tensor]] = None,
|
71 |
+
use_cache: Optional[bool] = None,
|
72 |
+
output_attentions: Optional[bool] = None,
|
73 |
+
output_hidden_states: Optional[bool] = None,
|
74 |
+
return_dict: Optional[bool] = None,
|
75 |
+
) -> Union[Tuple[torch.Tensor], modeling_git.CausalLMOutputWithPast]:
|
76 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
77 |
+
if labels is not None:
|
78 |
+
use_cache = False
|
79 |
+
|
80 |
+
outputs = self.git(
|
81 |
+
input_ids,
|
82 |
+
attention_mask=attention_mask,
|
83 |
+
position_ids=position_ids,
|
84 |
+
pixel_values=pixel_values,
|
85 |
+
head_mask=head_mask,
|
86 |
+
inputs_embeds=inputs_embeds,
|
87 |
+
past_key_values=past_key_values,
|
88 |
+
use_cache=use_cache,
|
89 |
+
output_attentions=output_attentions,
|
90 |
+
output_hidden_states=output_hidden_states,
|
91 |
+
return_dict=return_dict,
|
92 |
+
)
|
93 |
+
|
94 |
+
sequence_output = outputs[0]
|
95 |
+
logits = self.output(sequence_output)
|
96 |
+
|
97 |
+
loss = None
|
98 |
+
if labels is not None:
|
99 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
100 |
+
if pixel_values is not None:
|
101 |
+
num_image_tokens = self.git.encoder.layer[0].attention.self.image_patch_tokens
|
102 |
+
else:
|
103 |
+
num_image_tokens = 0
|
104 |
+
shifted_logits = logits[:, num_image_tokens:-1, :].contiguous()
|
105 |
+
labels = labels[:, 1:].contiguous()
|
106 |
+
loss_fct = CrossEntropyLoss()
|
107 |
+
loss = loss_fct(shifted_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
108 |
+
|
109 |
+
if not return_dict:
|
110 |
+
output = (logits,) + outputs[1:]
|
111 |
+
return ((loss,) + output) if loss is not None else output
|
112 |
+
|
113 |
+
return modeling_git.CausalLMOutputWithPast(
|
114 |
+
loss=loss,
|
115 |
+
logits=logits,
|
116 |
+
past_key_values=outputs.past_key_values,
|
117 |
+
hidden_states=outputs.hidden_states,
|
118 |
+
attentions=outputs.attentions,
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
class GitForSequenceClassification(modeling_git.GitPreTrainedModel):
|
123 |
+
def __init__(self, *args, **kwargs):
|
124 |
+
super().__init__(*args, **kwargs)
|
125 |
+
self.num_labels = self.config.num_labels
|
126 |
+
|
127 |
+
torch.backends.cudnn.deterministic = True
|
128 |
+
torch.backends.cudnn.benchmark = True
|
129 |
+
torch.use_deterministic_algorithms(True)
|
130 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
131 |
+
torch.backends.cudnn.allow_tf32 = True
|
132 |
+
|
133 |
+
random.seed(0)
|
134 |
+
np.random.seed(0)
|
135 |
+
torch.manual_seed(0)
|
136 |
+
torch.cuda.manual_seed_all(0)
|
137 |
+
|
138 |
+
self.classifier = nn.Linear(
|
139 |
+
self.config.hidden_size,
|
140 |
+
self.config.num_labels,
|
141 |
+
bias=False)
|
142 |
+
self.post_init()
|
143 |
+
self.git = modeling_git.GitModel(self.config)
|
144 |
+
|
145 |
+
del self.git.image_encoder
|
146 |
+
self.git.image_encoder = ViTModel.from_pretrained('facebook/dino-vitb16')
|
147 |
+
dino_cfg = self.git.image_encoder.config
|
148 |
+
config = self.git.config
|
149 |
+
config.vision_config.hidden_size = dino_cfg.hidden_size
|
150 |
+
|
151 |
+
del self.git.visual_projection
|
152 |
+
self.git.visual_projection = modeling_git.GitProjection(config)
|
153 |
+
num_tks = (dino_cfg.image_size // dino_cfg.patch_size) ** 2 + 1
|
154 |
+
self.git.encoder.layer[0].attention.self.image_patch_tokens = num_tks
|
155 |
+
|
156 |
+
def forward(
|
157 |
+
self,
|
158 |
+
input_ids: Optional[torch.LongTensor] = None,
|
159 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
160 |
+
position_ids: Optional[torch.Tensor] = None,
|
161 |
+
pixel_values: Optional[torch.Tensor] = None,
|
162 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
163 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
164 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
165 |
+
labels: Optional[torch.LongTensor] = None,
|
166 |
+
use_cache: Optional[bool] = None,
|
167 |
+
output_attentions: Optional[bool] = None,
|
168 |
+
output_hidden_states: Optional[bool] = None,
|
169 |
+
return_dict: Optional[bool] = None,
|
170 |
+
*args, **kwargs) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
171 |
+
r"""
|
172 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
173 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
174 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
175 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
176 |
+
"""
|
177 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
178 |
+
|
179 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
180 |
+
outputs = self.git(
|
181 |
+
input_ids,
|
182 |
+
attention_mask=attention_mask,
|
183 |
+
position_ids=position_ids,
|
184 |
+
pixel_values=pixel_values,
|
185 |
+
head_mask=head_mask,
|
186 |
+
inputs_embeds=inputs_embeds,
|
187 |
+
past_key_values=past_key_values,
|
188 |
+
use_cache=use_cache,
|
189 |
+
output_attentions=output_attentions,
|
190 |
+
output_hidden_states=output_hidden_states,
|
191 |
+
return_dict=return_dict,
|
192 |
+
*args, **kwargs)
|
193 |
+
|
194 |
+
hidden_states = outputs[0]
|
195 |
+
logits = self.classifier(hidden_states)
|
196 |
+
|
197 |
+
if input_ids is not None:
|
198 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
199 |
+
else:
|
200 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
201 |
+
|
202 |
+
if self.config.pad_token_id is None:
|
203 |
+
sequence_lengths = -1
|
204 |
+
else:
|
205 |
+
if input_ids is not None:
|
206 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
207 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
208 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
209 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
210 |
+
else:
|
211 |
+
sequence_lengths = -1
|
212 |
+
# logger.warning(
|
213 |
+
# f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
214 |
+
# "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
215 |
+
# )
|
216 |
+
|
217 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
218 |
+
|
219 |
+
loss = None
|
220 |
+
if labels is not None:
|
221 |
+
if self.config.problem_type is None:
|
222 |
+
if self.num_labels == 1:
|
223 |
+
self.config.problem_type = "regression"
|
224 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
225 |
+
self.config.problem_type = "single_label_classification"
|
226 |
+
else:
|
227 |
+
self.config.problem_type = "multi_label_classification"
|
228 |
+
|
229 |
+
if self.config.problem_type == "regression":
|
230 |
+
loss_fct = MSELoss()
|
231 |
+
if self.num_labels == 1:
|
232 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
233 |
+
else:
|
234 |
+
loss = loss_fct(pooled_logits, labels)
|
235 |
+
elif self.config.problem_type == "single_label_classification":
|
236 |
+
loss_fct = CrossEntropyLoss()
|
237 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
238 |
+
elif self.config.problem_type == "multi_label_classification":
|
239 |
+
loss_fct = BCEWithLogitsLoss()
|
240 |
+
loss = loss_fct(pooled_logits, labels)
|
241 |
+
|
242 |
+
if not return_dict:
|
243 |
+
output = (pooled_logits,) + outputs[1:]
|
244 |
+
return ((loss,) + output) if loss is not None else output
|
245 |
+
|
246 |
+
return SequenceClassifierOutputWithPast(
|
247 |
+
loss=loss,
|
248 |
+
logits=pooled_logits,
|
249 |
+
past_key_values=outputs.past_key_values,
|
250 |
+
hidden_states=outputs.hidden_states,
|
251 |
+
attentions=outputs.attentions,
|
252 |
+
)
|
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 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cls_token": {
|
3 |
+
"content": "[CLS]",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"mask_token": {
|
10 |
+
"content": "[MASK]",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "[PAD]",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"sep_token": {
|
24 |
+
"content": "[SEP]",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
},
|
30 |
+
"unk_token": {
|
31 |
+
"content": "[UNK]",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": false,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false
|
36 |
+
}
|
37 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "[PAD]",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"100": {
|
12 |
+
"content": "[UNK]",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"101": {
|
20 |
+
"content": "[CLS]",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"102": {
|
28 |
+
"content": "[SEP]",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"103": {
|
36 |
+
"content": "[MASK]",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
}
|
43 |
+
},
|
44 |
+
"clean_up_tokenization_spaces": true,
|
45 |
+
"cls_token": "[CLS]",
|
46 |
+
"do_lower_case": true,
|
47 |
+
"mask_token": "[MASK]",
|
48 |
+
"model_input_names": [
|
49 |
+
"input_ids",
|
50 |
+
"attention_mask"
|
51 |
+
],
|
52 |
+
"model_max_length": 512,
|
53 |
+
"pad_token": "[PAD]",
|
54 |
+
"processor_class": "GitProcessor",
|
55 |
+
"sep_token": "[SEP]",
|
56 |
+
"strip_accents": null,
|
57 |
+
"tokenize_chinese_chars": true,
|
58 |
+
"tokenizer_class": "BertTokenizer",
|
59 |
+
"unk_token": "[UNK]"
|
60 |
+
}
|
vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|