Chengxu Zhuang commited on
Commit
dbddb9a
·
1 Parent(s): 50e357d

model upload

Browse files
config.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": "58597eee6783b5d4405df333573fe4b4368bce29",
3
+ "architectures": [
4
+ "GitForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_git.GitConfig",
8
+ "AutoModelForCausalLM": "modeling_git.GitForCausalLM"
9
+ },
10
+ "attention_probs_dropout_prob": 0.1,
11
+ "bos_token_id": 101,
12
+ "classifier_dropout": null,
13
+ "eos_token_id": 102,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 768,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 3072,
19
+ "layer_norm_eps": 1e-12,
20
+ "max_position_embeddings": 1024,
21
+ "model_type": "git",
22
+ "num_attention_heads": 12,
23
+ "num_hidden_layers": 12,
24
+ "num_image_with_embedding": null,
25
+ "pad_token_id": 0,
26
+ "position_embedding_type": "absolute",
27
+ "tie_word_embeddings": true,
28
+ "torch_dtype": "float32",
29
+ "transformers_version": null,
30
+ "use_cache": true,
31
+ "vision_config": {
32
+ "_name_or_path": "",
33
+ "add_cross_attention": false,
34
+ "architectures": null,
35
+ "attention_dropout": 0.0,
36
+ "bad_words_ids": null,
37
+ "begin_suppress_tokens": null,
38
+ "bos_token_id": null,
39
+ "chunk_size_feed_forward": 0,
40
+ "cross_attention_hidden_size": null,
41
+ "decoder_start_token_id": null,
42
+ "diversity_penalty": 0.0,
43
+ "do_sample": false,
44
+ "dropout": 0.0,
45
+ "early_stopping": false,
46
+ "encoder_no_repeat_ngram_size": 0,
47
+ "eos_token_id": null,
48
+ "exponential_decay_length_penalty": null,
49
+ "finetuning_task": null,
50
+ "forced_bos_token_id": null,
51
+ "forced_eos_token_id": null,
52
+ "hidden_act": "quick_gelu",
53
+ "hidden_size": 768,
54
+ "id2label": {
55
+ "0": "LABEL_0",
56
+ "1": "LABEL_1"
57
+ },
58
+ "image_size": 224,
59
+ "initializer_factor": 1.0,
60
+ "initializer_range": 0.02,
61
+ "intermediate_size": 4096,
62
+ "is_decoder": false,
63
+ "is_encoder_decoder": false,
64
+ "label2id": {
65
+ "LABEL_0": 0,
66
+ "LABEL_1": 1
67
+ },
68
+ "layer_norm_eps": 1e-05,
69
+ "length_penalty": 1.0,
70
+ "max_length": 20,
71
+ "min_length": 0,
72
+ "model_type": "git_vision_model",
73
+ "no_repeat_ngram_size": 0,
74
+ "num_attention_heads": 16,
75
+ "num_beam_groups": 1,
76
+ "num_beams": 1,
77
+ "num_channels": 3,
78
+ "num_hidden_layers": 24,
79
+ "num_return_sequences": 1,
80
+ "output_attentions": false,
81
+ "output_hidden_states": false,
82
+ "output_scores": false,
83
+ "pad_token_id": null,
84
+ "patch_size": 14,
85
+ "prefix": null,
86
+ "problem_type": null,
87
+ "projection_dim": 512,
88
+ "pruned_heads": {},
89
+ "remove_invalid_values": false,
90
+ "repetition_penalty": 1.0,
91
+ "return_dict": true,
92
+ "return_dict_in_generate": false,
93
+ "sep_token_id": null,
94
+ "suppress_tokens": null,
95
+ "task_specific_params": null,
96
+ "temperature": 1.0,
97
+ "tf_legacy_loss": false,
98
+ "tie_encoder_decoder": false,
99
+ "tie_word_embeddings": true,
100
+ "tokenizer_class": null,
101
+ "top_k": 50,
102
+ "top_p": 1.0,
103
+ "torch_dtype": null,
104
+ "torchscript": false,
105
+ "transformers_version": "4.29.0",
106
+ "typical_p": 1.0,
107
+ "use_bfloat16": false
108
+ },
109
+ "vocab_size": 32778
110
+ }
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,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+
19
+
20
+ class GitForCausalLM(modeling_git.GitForCausalLM):
21
+ def __init__(self, *args, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+
24
+ del self.output
25
+ self.output = nn.Linear(
26
+ self.config.hidden_size,
27
+ self.config.vocab_size,
28
+ bias=False)
29
+ self.post_init()
30
+
31
+ del self.git.image_encoder
32
+ self.git.image_encoder = ViTModel.from_pretrained('facebook/dino-vitb16')
33
+ dino_cfg = self.git.image_encoder.config
34
+ config = self.git.config
35
+ config.vision_config.hidden_size = dino_cfg.hidden_size
36
+
37
+ del self.git.visual_projection
38
+ self.git.visual_projection = modeling_git.GitProjection(config)
39
+ num_tks = (dino_cfg.image_size // dino_cfg.patch_size) ** 2 + 1
40
+ self.git.encoder.layer[0].attention.self.image_patch_tokens = num_tks
41
+
42
+ def forward(
43
+ self,
44
+ input_ids: Optional[torch.Tensor] = None,
45
+ attention_mask: Optional[torch.Tensor] = None,
46
+ position_ids: Optional[torch.Tensor] = None,
47
+ pixel_values: Optional[torch.Tensor] = None,
48
+ head_mask: Optional[torch.Tensor] = None,
49
+ inputs_embeds: Optional[torch.Tensor] = None,
50
+ labels: Optional[torch.Tensor] = None,
51
+ past_key_values: Optional[List[torch.Tensor]] = None,
52
+ use_cache: Optional[bool] = None,
53
+ output_attentions: Optional[bool] = None,
54
+ output_hidden_states: Optional[bool] = None,
55
+ return_dict: Optional[bool] = None,
56
+ ) -> Union[Tuple[torch.Tensor], modeling_git.CausalLMOutputWithPast]:
57
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
58
+ if labels is not None:
59
+ use_cache = False
60
+
61
+ outputs = self.git(
62
+ input_ids,
63
+ attention_mask=attention_mask,
64
+ position_ids=position_ids,
65
+ pixel_values=pixel_values,
66
+ head_mask=head_mask,
67
+ inputs_embeds=inputs_embeds,
68
+ past_key_values=past_key_values,
69
+ use_cache=use_cache,
70
+ output_attentions=output_attentions,
71
+ output_hidden_states=output_hidden_states,
72
+ return_dict=return_dict,
73
+ )
74
+
75
+ sequence_output = outputs[0]
76
+ logits = self.output(sequence_output)
77
+
78
+ loss = None
79
+ if labels is not None:
80
+ # we are doing next-token prediction; shift prediction scores and input ids by one
81
+ if pixel_values is not None:
82
+ num_image_tokens = self.git.encoder.layer[0].attention.self.image_patch_tokens
83
+ else:
84
+ num_image_tokens = 0
85
+ shifted_logits = logits[:, num_image_tokens:-1, :].contiguous()
86
+ labels = labels[:, 1:].contiguous()
87
+ loss_fct = CrossEntropyLoss()
88
+ loss = loss_fct(shifted_logits.view(-1, self.config.vocab_size), labels.view(-1))
89
+
90
+ if not return_dict:
91
+ output = (logits,) + outputs[1:]
92
+ return ((loss,) + output) if loss is not None else output
93
+
94
+ return modeling_git.CausalLMOutputWithPast(
95
+ loss=loss,
96
+ logits=logits,
97
+ past_key_values=outputs.past_key_values,
98
+ hidden_states=outputs.hidden_states,
99
+ attentions=outputs.attentions,
100
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36e0e3312c8f6380c48894eec9d4f20ad0ae4b27167695bab3395e38e269df2f
3
+ size 792134047
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
+ }