ucsahin commited on
Commit
4a9ac18
1 Parent(s): cf65339

Base model registered and uploaded

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ucsahin/TRaVisionLM-base-final-unregistered",
3
+ "architectures": [
4
+ "TraVisionForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_travisionlm.TraVisionLMConfig",
8
+ "AutoModelForCausalLM": "modeling_travisionlm.TraVisionForCausalLM"
9
+ },
10
+ "hidden_size": 1280,
11
+ "ignore_index": -100,
12
+ "image_token_index": 50257,
13
+ "model_type": "travisionlm",
14
+ "num_image_tokens": 256,
15
+ "projection_dim": 768,
16
+ "text_config": {
17
+ "architectures": [
18
+ "GPT2LMHeadModel"
19
+ ],
20
+ "bos_token_id": 0,
21
+ "eos_token_id": 0,
22
+ "model_type": "gpt2",
23
+ "n_ctx": 1024,
24
+ "n_embd": 1280,
25
+ "n_head": 20,
26
+ "n_layer": 36,
27
+ "pad_token_id": 0,
28
+ "reorder_and_upcast_attn": true,
29
+ "scale_attn_by_inverse_layer_idx": true,
30
+ "task_specific_params": {
31
+ "text-generation": {
32
+ "do_sample": true,
33
+ "max_length": 50
34
+ }
35
+ },
36
+ "torch_dtype": "float32",
37
+ "vocab_size": 51282
38
+ },
39
+ "torch_dtype": "float32",
40
+ "transformers_version": "4.44.0.dev0",
41
+ "vision_config": {
42
+ "image_size": 256,
43
+ "model_type": "siglip_vision_model",
44
+ "projection_dim": 768
45
+ }
46
+ }
configuration_travisionlm.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TraVisionLM configuration"""
2
+
3
+ from transformers import PretrainedConfig
4
+ from transformers import logging, CONFIG_MAPPING
5
+ import warnings
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+ class TraVisionLMConfig(PretrainedConfig):
10
+ model_type = "travisionlm"
11
+ is_composition = False
12
+
13
+ def __init__(
14
+ self,
15
+ vision_config=None,
16
+ text_config=None,
17
+ ignore_index=-100,
18
+ image_token_idx=50257,
19
+ vocab_size=51282,
20
+ projection_dim=768,
21
+ hidden_size=1280,
22
+ **kwargs,
23
+ ):
24
+ self.ignore_index = ignore_index
25
+ self.image_token_index = image_token_idx
26
+ self._vocab_size = vocab_size
27
+ self.projection_dim = projection_dim
28
+ self.hidden_size = hidden_size
29
+ self.vision_config = vision_config
30
+ self.is_encoder_decoder = False
31
+ if isinstance(self.vision_config, dict):
32
+ vision_config["model_type"] = (
33
+ vision_config["model_type"] if "model_type" in vision_config else "siglip_vision_model"
34
+ )
35
+ self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
36
+ elif vision_config is None:
37
+ self.vision_config = CONFIG_MAPPING["siglip_vision_model"](
38
+ attention_dropout=0.0,
39
+ hidden_act="gelu_pytorch_tanh",
40
+ hidden_size=768,
41
+ image_size=256,
42
+ intermediate_size=3072,
43
+ layer_norm_eps=1e-06,
44
+ num_attention_heads=12,
45
+ num_channels=3,
46
+ num_hidden_layers=12,
47
+ patch_size=16,
48
+ )
49
+ self.vocab_size = vocab_size
50
+
51
+ self.text_config = text_config
52
+
53
+ if isinstance(self.text_config, dict):
54
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "gpt2"
55
+ self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
56
+ elif text_config is None:
57
+ self.text_config = CONFIG_MAPPING["gpt2"](
58
+ activation_function="gelu_new",
59
+ attn_pdrop=0.1,
60
+ embd_pdrop=0.1,
61
+ initializer_range=0.02,
62
+ layer_norm_epsilon=1e-05,
63
+ n_ctx=1024,
64
+ n_embd=1280,
65
+ n_head=20,
66
+ n_layer=36,
67
+ n_positions=1024,
68
+ reorder_and_upcast_attn=False,
69
+ resid_pdrop=0.1,
70
+ scale_attn_by_inverse_layer_idx=False,
71
+ scale_attn_weights=True,
72
+ vocab_size=vocab_size
73
+ )
74
+ self.num_image_tokens = (self.vision_config.image_size // self.vision_config.patch_size) ** 2
75
+ self.pad_token_id = self.text_config.pad_token_id
76
+ self.vision_config.projection_dim = projection_dim
77
+ super().__init__(**kwargs)
78
+
79
+ @property
80
+ def vocab_size(self):
81
+ warnings.warn(
82
+ "The `vocab_size` attribute is deprecated and will be removed in v4.44, Please use `text_config.vocab_size` instead.",
83
+ FutureWarning,
84
+ )
85
+ return self._vocab_size
86
+
87
+ @vocab_size.setter
88
+ def vocab_size(self, value):
89
+ self._vocab_size = value
90
+
91
+ def to_dict(self):
92
+ output = super().to_dict()
93
+ output.pop("_vocab_size", None)
94
+ return output
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.44.0.dev0"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84db9d17f7b2db7e2fa107682bf1a214f1d6a2615c2b0b8dd295db0d0d721ff8
3
+ size 3498353344
modeling_travisionlm.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch TraVisionLM"""
2
+ import torch
3
+ from transformers import PreTrainedModel, AutoModel, AutoModelForCausalLM
4
+ from transformers.utils import logging, add_start_docstrings, ModelOutput
5
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask_for_sdpa
6
+ from dataclasses import dataclass
7
+ from typing import List, Optional, Tuple, Union
8
+ from torch import nn
9
+ from transformers.cache_utils import Cache
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+ from .configuration_travisionlm import TraVisionLMConfig
14
+
15
+ _CONFIG_FOR_DOC = "TraVisionLMConfig"
16
+
17
+ @dataclass
18
+ class TraVisionCausalLMOutputWithPast(ModelOutput):
19
+ """
20
+ Base class for TraVision language model (or autoregressive) outputs.
21
+
22
+ Args:
23
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
24
+ Language modeling loss (for next-token prediction).
25
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
26
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
27
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
28
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
29
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
30
+
31
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
32
+ `past_key_values` input) to speed up sequential decoding.
33
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
34
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
35
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
36
+
37
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
38
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
39
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
40
+ sequence_length)`.
41
+
42
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
43
+ heads.
44
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
45
+ Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
46
+ sequence_length, hidden_size)`.
47
+
48
+ image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
49
+ """
50
+ loss: Optional[torch.FloatTensor] = None
51
+ logits: torch.FloatTensor = None
52
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None
53
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
54
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
55
+ image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
56
+
57
+
58
+ class TraVisionMultiModalProjector(nn.Module):
59
+ """
60
+ Multimodal projector that cast the image features into the same dimension space as the language model
61
+ """
62
+ def __init__(self, config: TraVisionLMConfig, dropout=0.1):
63
+ super().__init__()
64
+ self.net = nn.Sequential(
65
+ nn.Linear(config.vision_config.projection_dim, 4*config.vision_config.projection_dim, bias=True),
66
+ nn.GELU(),
67
+ nn.Linear(4*config.vision_config.projection_dim, config.hidden_size, bias=True),
68
+ nn.Dropout(dropout)
69
+ )
70
+
71
+ def forward(self, image_features):
72
+ hidden_states = self.net(image_features).to(image_features.dtype)
73
+ return hidden_states
74
+
75
+
76
+ TRAVISIONLM_START_DOCSTRING = r"""
77
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
78
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
79
+ etc.)
80
+
81
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
82
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
83
+ and behavior.
84
+
85
+ Parameters:
86
+ config ([`TraVisionLMConfig`]):
87
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
88
+ load the weights associated with the model, only the configuration. Check out the
89
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
90
+ """
91
+
92
+ @add_start_docstrings(
93
+ "The bare TraVision Model outputting raw hidden-states without any specific head on top.",
94
+ TRAVISIONLM_START_DOCSTRING,
95
+ )
96
+
97
+ class TraVisionPreTrainedModel(PreTrainedModel):
98
+ config_class = TraVisionLMConfig
99
+ base_model_prefix = "model"
100
+ supports_gradient_checkpointing = True
101
+ _no_split_modules = ["TraVisionMultiModalProjector"]
102
+ _skip_keys_device_placement = "past_key_values"
103
+ _supports_flash_attn_2 = True
104
+ _supports_sdpa = True
105
+
106
+ def _init_weights(self, module):
107
+ # Do NOT init the weights of the model using this class call, this is a ported version,
108
+ # hence not intended to be trained from scratch.
109
+ std = (
110
+ self.config.initializer_range
111
+ if hasattr(self.config, "initializer_range")
112
+ else self.config.text_config.initializer_range
113
+ )
114
+
115
+ if hasattr(module, "class_embedding"):
116
+ module.class_embedding.data.normal_(mean=0.0, std=std)
117
+
118
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
119
+ module.weight.data.normal_(mean=0.0, std=std)
120
+ if module.bias is not None:
121
+ module.bias.data.zero_()
122
+ elif isinstance(module, nn.Embedding):
123
+ module.weight.data.normal_(mean=0.0, std=std)
124
+ if module.padding_idx is not None:
125
+ module.weight.data[module.padding_idx].zero_()
126
+
127
+ @property
128
+ def _supports_sdpa(self):
129
+ """
130
+ Retrieve language_model's attribute to check whether the model supports
131
+ SDPA or not.
132
+ """
133
+ return self.language_model._supports_sdpa
134
+
135
+
136
+ @add_start_docstrings(
137
+ """The TraVisionLM model which consists of a vision backbone and a language model.""",
138
+ TRAVISIONLM_START_DOCSTRING,
139
+ )
140
+ class TraVisionForCausalLM(TraVisionPreTrainedModel):
141
+ def __init__(self, config: TraVisionLMConfig):
142
+ super(TraVisionForCausalLM, self).__init__(config)
143
+ self.vocab_size = config.vocab_size
144
+ self.pad_token_id = -1 if config.pad_token_id == None else config.pad_token_id
145
+ self._attn_implementation = config._attn_implementation
146
+ self.gradient_checkpointing = False
147
+
148
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
149
+ self.vision_projector = TraVisionMultiModalProjector(config)
150
+
151
+ language_model = AutoModelForCausalLM.from_config(
152
+ config=config.text_config, attn_implementation=self._attn_implementation
153
+ )
154
+
155
+ if language_model._tied_weights_keys is not None:
156
+ self._tied_weights_keys = [f"language_model.{k}" for k in language_model._tied_weights_keys]
157
+
158
+ self.language_model = language_model
159
+
160
+ self.post_init()
161
+
162
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_input_embeddings with PaliGemma->TraVisionLM
163
+ def get_input_embeddings(self):
164
+ return self.language_model.get_input_embeddings()
165
+
166
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_input_embeddings with PaliGemma->TraVisionLM
167
+ def set_input_embeddings(self, value):
168
+ self.language_model.set_input_embeddings(value)
169
+
170
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_output_embeddings with PaliGemma->TraVisionLM
171
+ def get_output_embeddings(self):
172
+ return self.language_model.get_output_embeddings()
173
+
174
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_output_embeddings with PaliGemma->TraVisionLM
175
+ def set_output_embeddings(self, new_embeddings):
176
+ self.language_model.set_output_embeddings(new_embeddings)
177
+
178
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_decoder with PaliGemma->TraVisionLM
179
+ def set_decoder(self, decoder):
180
+ self.language_model.set_decoder(decoder)
181
+
182
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_decoder with PaliGemma->TraVisionLM
183
+ def get_decoder(self):
184
+ return self.language_model.get_decoder()
185
+
186
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.tie_weights with PaliGemma->TraVisionLM
187
+ def tie_weights(self):
188
+ return self.language_model.tie_weights()
189
+
190
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
191
+ # TODO: config.vocab_size is deprecated and will be removed in v4.43.
192
+ # `resize_token_embeddings` should work from `modeling_utils.py``
193
+ model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
194
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
195
+ self.config.vocab_size = model_embeds.num_embeddings
196
+ self.vocab_size = model_embeds.num_embeddings
197
+ return model_embeds
198
+
199
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration._merge_input_ids_with_image_features with PaliGemma->TraVisionLM
200
+ """ !!! Two significant modifications are made to the original code:
201
+ ------> 1) The pad and eos tokens are set to be the same in TraVisionProcessor. Hence, only the features corresponding to the padding mask are filtered out
202
+ using the attention mask.
203
+ ------> 2) The features corresponding to both the prompts (called prefixes in PaliGemma) and labels (called suffixes in PaliGemma) are added the final embedding tensor
204
+ and the tokens of both the prompts and labels are applied causal attention mask. All the image tokens are attended using full-attention mask.
205
+ NOTE: In the original PaliGemma implementation, only the suffix tokens are applied causal masking. Check out [PaliGemma arXiv Paper](https://arxiv.org/pdf/2407.07726)
206
+ for the details.
207
+ """
208
+ def _merge_input_ids_with_image_features(
209
+ self, image_features, inputs_embeds, input_ids, attention_mask, labels, token_type_ids, cache_position
210
+ ):
211
+ _, _, embed_dim = image_features.shape
212
+ batch_size, sequence_length = input_ids.shape
213
+ dtype, device = inputs_embeds.dtype, inputs_embeds.device
214
+ min_dtype = torch.finfo(dtype).min
215
+
216
+ scaled_image_features = image_features / (self.config.hidden_size**0.5)
217
+ final_embedding = torch.zeros(
218
+ batch_size, sequence_length, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
219
+ )
220
+
221
+ text_mask = (input_ids != self.config.image_token_index) & (attention_mask | input_ids != self.config.text_config.pad_token_id)
222
+ image_mask = input_ids == self.config.image_token_index
223
+ pad_mask = (attention_mask == 0) & (input_ids == self.config.text_config.pad_token_id)
224
+
225
+ # expand masks to match embedding dimension
226
+ text_mask_expanded = text_mask.unsqueeze(-1).expand(-1, -1, embed_dim).to(inputs_embeds.device)
227
+ pad_mask_expanded = pad_mask.unsqueeze(-1).expand(-1, -1, embed_dim).to(inputs_embeds.device)
228
+ # insert padding and text token embeddings
229
+ final_embedding = torch.where(text_mask_expanded, inputs_embeds, final_embedding)
230
+ final_embedding = torch.where(pad_mask_expanded, torch.zeros_like(final_embedding), final_embedding)
231
+ # insert image embeddings - the image mask is always less or equal to the sentence in length
232
+ final_embedding = final_embedding.masked_scatter(
233
+ image_mask.unsqueeze(-1).expand_as(final_embedding).to(device=final_embedding.device),
234
+ scaled_image_features.to(device=final_embedding.device, dtype=final_embedding.dtype),
235
+ )
236
+ final_embedding = torch.where(pad_mask_expanded, torch.zeros_like(final_embedding), final_embedding)
237
+ if attention_mask is not None:
238
+ position_ids = (attention_mask.cumsum(-1)).masked_fill_((attention_mask == 0), 1)
239
+ else:
240
+ position_ids = None
241
+
242
+ if token_type_ids is not None:
243
+ # we are training thus we need to create a full mask on the image, but causal on prompt and suffix
244
+ target_length = cache_position[-1] + 1
245
+ causal_mask = torch.full(
246
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
247
+ )
248
+ if sequence_length != 1:
249
+ causal_mask = torch.triu(causal_mask, diagonal=1)
250
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
251
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_embeds.shape[0], 1, -1, -1)
252
+ if attention_mask is not None:
253
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
254
+ mask_length = attention_mask.shape[-1]
255
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
256
+ causal_mask.device
257
+ )
258
+ # unmask the prefill
259
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
260
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
261
+ )
262
+ padding_mask = padding_mask == 0
263
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
264
+ padding_mask, min_dtype
265
+ )
266
+
267
+ final_labels = None
268
+ if labels is not None:
269
+ final_labels = torch.full(
270
+ (batch_size, sequence_length), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
271
+ )
272
+ final_labels = torch.where((attention_mask | input_ids != self.config.text_config.pad_token_id), labels, final_labels)
273
+ else:
274
+ causal_mask = attention_mask.unsqueeze(1).unsqueeze(2) * attention_mask.unsqueeze(1).unsqueeze(-1)
275
+ # invert causal mask
276
+ causal_mask = torch.where(causal_mask == 0, min_dtype, 0).to(dtype)
277
+ final_labels = None
278
+
279
+ return final_embedding, causal_mask, final_labels, position_ids
280
+
281
+
282
+ def forward(
283
+ self,
284
+ input_ids: torch.LongTensor = None,
285
+ pixel_values: torch.FloatTensor = None,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
289
+ token_type_ids: Optional[torch.LongTensor] = None,
290
+ cache_position: Optional[torch.LongTensor] = None,
291
+ inputs_embeds: Optional[torch.FloatTensor] = None,
292
+ labels: Optional[torch.LongTensor] = None,
293
+ use_cache: Optional[bool] = None,
294
+ output_attentions: Optional[bool] = None,
295
+ output_hidden_states: Optional[bool] = None,
296
+ return_dict: Optional[bool] = None,
297
+ ) -> Union[Tuple, TraVisionCausalLMOutputWithPast]:
298
+
299
+ if labels is not None:
300
+ use_cache = False
301
+
302
+ if input_ids is not None and inputs_embeds is not None:
303
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
304
+ elif input_ids is not None:
305
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
306
+ input_shape = input_ids.size()
307
+ input_ids = input_ids.view(-1, input_shape[-1])
308
+ batch_size = input_ids.shape[0]
309
+ elif inputs_embeds is not None:
310
+ input_shape = inputs_embeds.size()[:-1]
311
+ batch_size = inputs_embeds.shape[0]
312
+ else:
313
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
314
+
315
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
316
+ output_hidden_states = (
317
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
318
+ )
319
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
320
+
321
+ if past_key_values is None:
322
+ past_length = 0
323
+ past_key_values = tuple([None] * len(self.language_model.transformer.h))
324
+ else:
325
+ past_length = past_key_values[0][0].size(-2)
326
+ if position_ids is None:
327
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=input_ids.device if input_ids is not None else inputs_embeds.device)
328
+ position_ids = position_ids.unsqueeze(0)
329
+
330
+ # the attention mask is turned 4d after, we keep track of the original one
331
+ input_attention_mask = attention_mask
332
+
333
+ if inputs_embeds is None:
334
+ # 1. Extract the input embeddings
335
+ inputs_embeds = self.get_input_embeddings()(input_ids)
336
+
337
+ # 2. Add the absolute positional embeddings to only text token locations in inputs_embeds
338
+ if pixel_values is not None and inputs_embeds.shape[1] != 1:
339
+ # Compute the initial mask for position IDs
340
+ position_ids_mask = torch.where(input_ids != self.config.image_token_index, position_ids, 1)
341
+ # Update the mask for positions where input_ids is not zero
342
+ position_ids_mask[:, :-1] = torch.where(input_ids[:, :-1] != 0, position_ids_mask[:, :-1], 1)
343
+ # Find the first position embedding locations
344
+ first_position_embed_locs = torch.sum(position_ids_mask == 1, dim=1)
345
+ # Adjust the mask by subtracting the first position embedding locations
346
+ position_ids_mask.sub_(first_position_embed_locs[:, None])
347
+ # Ensure all values in the mask are non-negative --> assign values 1 to pad and image token locations
348
+ position_emb_ids = torch.where(position_ids_mask >= 0, position_ids_mask, 1)
349
+ # construct position embeddings using position_emb_ids
350
+ position_embeds = self.language_model.transformer.wpe(position_emb_ids)
351
+ else:
352
+ # In this case, we generate from cache with past_key_values
353
+ pos_emb_ind = position_ids.view(batch_size, -1)
354
+ position_embeds = self.language_model.transformer.wpe(pos_emb_ind)
355
+
356
+ # Directly add position_embeds to inputs_embeds to get hidden_states
357
+ hidden_states = inputs_embeds + position_embeds
358
+
359
+ # 3. Merge text and images
360
+ if pixel_values is not None and input_ids.shape[1] != 1:
361
+ # make sure that pixel values are of 4D dimensions (batch_size, num_channels, width, height)
362
+ if pixel_values.dim() == 3:
363
+ pixel_values = pixel_values.unsqueeze(dim=0)
364
+
365
+ image_outputs = self.vision_tower(pixel_values.to(inputs_embeds.dtype))
366
+ selected_image_feature = image_outputs.last_hidden_state
367
+ image_features = self.vision_projector(selected_image_feature)
368
+
369
+ if cache_position is None:
370
+ cache_position = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
371
+ hidden_states, attention_mask, labels, _ = self._merge_input_ids_with_image_features(
372
+ image_features, hidden_states, input_ids, attention_mask, labels, token_type_ids, cache_position
373
+ )
374
+
375
+ else:
376
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
377
+ # generation with cache, we can use standard causal masking
378
+ if past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
379
+ # Attention mask.
380
+ _use_sdpa = self._attn_implementation == "sdpa" and output_attentions is False
381
+ if attention_mask is not None:
382
+ attention_mask = attention_mask.view(batch_size, -1)
383
+ if self._attn_implementation == "flash_attention_2":
384
+ attention_mask = attention_mask if 0 in attention_mask else None
385
+ elif _use_sdpa:
386
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
387
+ attention_mask=attention_mask,
388
+ input_shape=(batch_size, input_shape[-1]),
389
+ inputs_embeds=inputs_embeds,
390
+ past_key_values_length=past_length,
391
+ )
392
+ else:
393
+ # We create a 3D attention mask from a 2D tensor mask.
394
+ # Sizes are [batch_size, 1, 1, to_seq_length]
395
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
396
+ # this attention mask is more simple than the triangular masking of causal attention
397
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
398
+ attention_mask = attention_mask[:, None, None, :]
399
+
400
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
401
+ # masked positions, this operation will create a tensor which is 0.0 for
402
+ # positions we want to attend and the dtype's smallest value for masked positions.
403
+ # Since we are adding it to the raw scores before the softmax, this is
404
+ # effectively the same as removing these entirely.
405
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
406
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
407
+
408
+ if attention_mask is not None:
409
+ attention_mask = attention_mask.to(inputs_embeds.dtype)
410
+
411
+ hidden_states = self.language_model.transformer.drop(hidden_states)
412
+ output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
413
+
414
+ presents = () if use_cache else None
415
+ all_self_attentions = () if output_attentions else None
416
+ all_hidden_states = () if output_hidden_states else None
417
+ for i, (block, layer_past) in enumerate(zip(self.language_model.transformer.h, past_key_values)):
418
+ if output_hidden_states:
419
+ all_hidden_states = all_hidden_states + (hidden_states,)
420
+ outputs = block(
421
+ hidden_states,
422
+ layer_past=layer_past,
423
+ attention_mask=attention_mask,
424
+ use_cache=use_cache,
425
+ output_attentions=output_attentions,
426
+ )
427
+ hidden_states = outputs[0]
428
+ if use_cache is True:
429
+ presents = presents + (outputs[1],)
430
+
431
+ if output_attentions:
432
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
433
+
434
+ hidden_states = self.language_model.transformer.ln_f(hidden_states)
435
+
436
+ hidden_states = hidden_states.view(output_shape)
437
+ # Add last hidden state
438
+ if output_hidden_states:
439
+ all_hidden_states = all_hidden_states + (hidden_states,)
440
+
441
+ logits = self.language_model.lm_head(hidden_states)
442
+ logits = logits.float()
443
+ loss = None
444
+ if labels is not None:
445
+ shift_logits = logits[..., :-1, :]
446
+ shift_labels = labels[..., 1:] # shift to right
447
+ if input_attention_mask is not None:
448
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
449
+ shift_attention_mask = input_attention_mask[..., 1:]
450
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
451
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
452
+ else:
453
+ shift_logits = shift_logits.contiguous()
454
+ shift_labels = shift_labels.contiguous()
455
+ # Flatten the tokens
456
+ loss_fct = nn.CrossEntropyLoss()
457
+
458
+ flat_logits = shift_logits.view(-1, self.config.vocab_size)
459
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
460
+ loss = loss_fct(flat_logits, flat_labels)
461
+ if not return_dict:
462
+ output = (logits, presents, all_hidden_states, all_self_attentions)
463
+ return (loss,) + output if loss is not None else output
464
+
465
+ return TraVisionCausalLMOutputWithPast(
466
+ loss=loss,
467
+ logits=logits,
468
+ past_key_values=presents,
469
+ hidden_states=all_hidden_states,
470
+ attentions=all_self_attentions,
471
+ )
472
+
473
+ def prepare_inputs_for_generation(
474
+ self,
475
+ input_ids,
476
+ past_key_values=None,
477
+ inputs_embeds=None,
478
+ cache_position=None,
479
+ position_ids=None,
480
+ pixel_values=None,
481
+ attention_mask=None,
482
+ token_type_ids=None,
483
+ use_cache=True,
484
+ **kwargs,
485
+ ):
486
+ # set position inds here: we are going to use absolute position embeddings, hence carefully track the locs of the past position embedding indices
487
+ if attention_mask is not None and position_ids is None:
488
+ if past_key_values:
489
+ position_ids_mask = (input_ids != self.config.image_token_index)
490
+ position_ids_mask[:, :-1] &= (input_ids[:, :-1] != self.config.text_config.pad_token_id)
491
+ last_index = position_ids_mask.sum(dim=1) - 1
492
+ position_ids = torch.stack([torch.arange(start, start+cache_position.shape[0], device=input_ids.device) for start in last_index])
493
+
494
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
495
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
496
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
497
+ if past_key_values is not None:
498
+ if inputs_embeds is not None: # Exception 1
499
+ input_ids = input_ids[:, -cache_position.shape[0] :]
500
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
501
+ input_ids = input_ids[:, cache_position]
502
+
503
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
504
+ if inputs_embeds is not None and cache_position[0] == 0:
505
+ model_inputs = {"inputs_embeds": inputs_embeds}
506
+ else:
507
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
508
+
509
+ model_inputs.update(
510
+ {
511
+ "position_ids": position_ids,
512
+ "past_key_values": past_key_values,
513
+ "cache_position": cache_position,
514
+ "use_cache": use_cache,
515
+ "attention_mask": attention_mask,
516
+ "pixel_values": pixel_values,
517
+ "token_type_ids": token_type_ids,
518
+ }
519
+ )
520
+ return model_inputs