Upload VisionPixtralEncoderDecoder
Browse files- README.md +199 -0
- config.json +61 -0
- generation_config.json +9 -0
- model.safetensors +3 -0
- modeling.py +261 -0
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,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"VisionPixtralEncoderDecoder"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoModel": "modeling.VisionPixtralEncoderDecoder"
|
7 |
+
},
|
8 |
+
"decoder": {
|
9 |
+
"_attn_implementation_autoset": true,
|
10 |
+
"activation_dropout": 0.0,
|
11 |
+
"activation_function": "relu",
|
12 |
+
"add_cross_attention": true,
|
13 |
+
"attention_dropout": 0.0,
|
14 |
+
"classifier_dropout": 0.0,
|
15 |
+
"cross_attention_hidden_size": 1024,
|
16 |
+
"d_model": 1024,
|
17 |
+
"decoder_attention_heads": 16,
|
18 |
+
"decoder_ffn_dim": 4096,
|
19 |
+
"decoder_layerdrop": 0.0,
|
20 |
+
"decoder_layers": 12,
|
21 |
+
"dropout": 0.1,
|
22 |
+
"init_std": 0.02,
|
23 |
+
"is_decoder": true,
|
24 |
+
"layernorm_embedding": false,
|
25 |
+
"max_position_embeddings": 1024,
|
26 |
+
"model_type": "trocr",
|
27 |
+
"scale_embedding": true,
|
28 |
+
"tie_word_embeddings": false,
|
29 |
+
"torch_dtype": "float32",
|
30 |
+
"use_cache": false,
|
31 |
+
"use_learned_position_embeddings": false,
|
32 |
+
"vocab_size": 50265
|
33 |
+
},
|
34 |
+
"encoder": {
|
35 |
+
"_attn_implementation_autoset": true,
|
36 |
+
"architectures": [
|
37 |
+
"PixtralVisionModelBatch"
|
38 |
+
],
|
39 |
+
"attention_dropout": 0.0,
|
40 |
+
"head_dim": 64,
|
41 |
+
"hidden_act": "silu",
|
42 |
+
"hidden_size": 1024,
|
43 |
+
"image_size": 1024,
|
44 |
+
"initializer_range": 0.02,
|
45 |
+
"intermediate_size": 4096,
|
46 |
+
"is_composition": true,
|
47 |
+
"model_type": "pixtral_batch",
|
48 |
+
"num_attention_heads": 16,
|
49 |
+
"num_channels": 3,
|
50 |
+
"num_hidden_layers": 24,
|
51 |
+
"patch_size": 16,
|
52 |
+
"rope_theta": 10000.0,
|
53 |
+
"tie_word_embeddings": false,
|
54 |
+
"torch_dtype": "float32"
|
55 |
+
},
|
56 |
+
"is_encoder_decoder": true,
|
57 |
+
"model_type": "vision-encoder-decoder",
|
58 |
+
"tie_word_embeddings": false,
|
59 |
+
"torch_dtype": "float32",
|
60 |
+
"transformers_version": "4.51.3"
|
61 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 0,
|
4 |
+
"decoder_start_token_id": 2,
|
5 |
+
"eos_token_id": 2,
|
6 |
+
"pad_token_id": 1,
|
7 |
+
"transformers_version": "4.51.3",
|
8 |
+
"use_cache": false
|
9 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5e5153c6c3b48b4b6b75b5bbf7f2b0f0e413cced9f0d213525f23f6323f1c3dd
|
3 |
+
size 2832038364
|
modeling.py
ADDED
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from typing import Optional, Union, Tuple
|
5 |
+
|
6 |
+
from transformers.models.vision_encoder_decoder.modeling_vision_encoder_decoder import (
|
7 |
+
shift_tokens_right,
|
8 |
+
VisionEncoderDecoderModel
|
9 |
+
)
|
10 |
+
from transformers.modeling_outputs import Seq2SeqLMOutput
|
11 |
+
from transformers import PreTrainedModel
|
12 |
+
from transformers.models.pixtral.modeling_pixtral import apply_rotary_pos_emb, PixtralAttention, PixtralVisionModel
|
13 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
14 |
+
from transformers.modeling_outputs import BaseModelOutput
|
15 |
+
|
16 |
+
from pixtral_encoder_decoder.config import PixtralVisionModelBatchConfig, VisionPixtralEncoderDecoderConfig
|
17 |
+
|
18 |
+
|
19 |
+
def position_ids_in_meshgrid_batch(patch_embeds, max_width):
|
20 |
+
"""get the position ids of the batch. """
|
21 |
+
# unlike flattened patch_embeds, we use the padded ones, which mean each entry has the same w/h and thus the same ids
|
22 |
+
height, width = patch_embeds.shape[-2:]
|
23 |
+
mesh = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
|
24 |
+
h_grid, v_grid = torch.stack(mesh, dim=-1).reshape(-1, 2).chunk(2, -1)
|
25 |
+
ids = h_grid * max_width + v_grid
|
26 |
+
# expand ids to batch size
|
27 |
+
ids = ids.reshape(1, -1).repeat(patch_embeds.shape[0], 1)
|
28 |
+
return ids
|
29 |
+
|
30 |
+
|
31 |
+
def create_attention_mask_batch(w, h, image_sizes, patch_size):
|
32 |
+
def foo(i, j):
|
33 |
+
return ((torch.arange(h).unsqueeze(1) < i) & (torch.arange(w).unsqueeze(0) < j)).float()
|
34 |
+
|
35 |
+
mask = [foo(size[0] // patch_size, size[1] // patch_size) for size in image_sizes]
|
36 |
+
return torch.stack(mask, dim=0)
|
37 |
+
|
38 |
+
|
39 |
+
def pixtral_attention_fix_forward(
|
40 |
+
self,
|
41 |
+
hidden_states: torch.Tensor,
|
42 |
+
attention_mask: Optional[torch.Tensor] = None,
|
43 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
44 |
+
output_attentions: Optional[bool] = False,
|
45 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
46 |
+
"""Input shape: Batch x Time x Channel"""
|
47 |
+
|
48 |
+
batch_size, patches, _ = hidden_states.size()
|
49 |
+
|
50 |
+
query_states = self.q_proj(hidden_states)
|
51 |
+
key_states = self.k_proj(hidden_states)
|
52 |
+
value_states = self.v_proj(hidden_states)
|
53 |
+
|
54 |
+
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
55 |
+
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
56 |
+
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
57 |
+
|
58 |
+
cos, sin = position_embeddings
|
59 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, unsqueeze_dim=1)
|
60 |
+
|
61 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
|
62 |
+
|
63 |
+
if attention_mask is not None:
|
64 |
+
attn_weights = attn_weights + attention_mask
|
65 |
+
|
66 |
+
# upcast attention to fp32
|
67 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
68 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
69 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
70 |
+
|
71 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
72 |
+
attn_output = attn_output.reshape(batch_size, patches, -1)
|
73 |
+
|
74 |
+
attn_output = self.o_proj(attn_output)
|
75 |
+
|
76 |
+
return attn_output, attn_weights
|
77 |
+
|
78 |
+
|
79 |
+
# monkey patch a fix for unsqueeze dim for position embedds (since our input is batched and the old one is not)
|
80 |
+
PixtralAttention.forward = pixtral_attention_fix_forward
|
81 |
+
|
82 |
+
|
83 |
+
class PixtralVisionModelBatch(PixtralVisionModel):
|
84 |
+
config_class = PixtralVisionModelBatchConfig
|
85 |
+
|
86 |
+
def __init__(self, config):
|
87 |
+
super().__init__(config)
|
88 |
+
|
89 |
+
def forward(
|
90 |
+
self,
|
91 |
+
pixel_values: torch.Tensor,
|
92 |
+
image_sizes: Optional[torch.Tensor] = None,
|
93 |
+
attention_mask: Optional[torch.Tensor] = None,
|
94 |
+
output_hidden_states: Optional[bool] = None,
|
95 |
+
output_attentions: Optional[bool] = None,
|
96 |
+
return_dict: Optional[bool] = None,
|
97 |
+
*args,
|
98 |
+
**kwargs,
|
99 |
+
) -> Union[Tuple, BaseModelOutput]:
|
100 |
+
"""
|
101 |
+
Returns:
|
102 |
+
pixel_values: tensor of token features for
|
103 |
+
all tokens of all images of shape (N_toks, D)
|
104 |
+
"""
|
105 |
+
if attention_mask is None and image_sizes is None:
|
106 |
+
raise ValueError("Either `attention_mask` or `image_sizes` must be defined")
|
107 |
+
# pass images through initial convolution independently
|
108 |
+
patch_embeds = self.patch_conv(pixel_values)
|
109 |
+
# build attention mask based on image_sizes if not provided
|
110 |
+
if attention_mask is None:
|
111 |
+
h, w = patch_embeds.shape[-2:]
|
112 |
+
attention_mask = create_attention_mask_batch(w, h, image_sizes, self.patch_size).to(patch_embeds.device)
|
113 |
+
attention_mask = attention_mask.flatten(start_dim=-2)
|
114 |
+
|
115 |
+
# positional embeddings
|
116 |
+
position_ids = position_ids_in_meshgrid_batch(
|
117 |
+
patch_embeds, max_width=self.config.image_size // self.config.patch_size
|
118 |
+
)
|
119 |
+
position_embeddings = self.patch_positional_embedding(patch_embeds, position_ids)
|
120 |
+
|
121 |
+
# flatten patch_embeds
|
122 |
+
# seq_len = (h*w); hidden x seq_len -> seq_len x hidden.
|
123 |
+
patch_embeds = patch_embeds.flatten(start_dim=-2).transpose(-1, -2)
|
124 |
+
|
125 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, torch.float)
|
126 |
+
|
127 |
+
patch_embeds = self.ln_pre(patch_embeds)
|
128 |
+
|
129 |
+
out = self.transformer(
|
130 |
+
patch_embeds,
|
131 |
+
attention_mask=attention_mask,
|
132 |
+
position_embeddings=position_embeddings,
|
133 |
+
output_hidden_states=output_hidden_states,
|
134 |
+
output_attentions=output_attentions,
|
135 |
+
return_dict=return_dict,
|
136 |
+
)
|
137 |
+
return out
|
138 |
+
|
139 |
+
|
140 |
+
class VisionPixtralEncoderDecoder(VisionEncoderDecoderModel):
|
141 |
+
config_class = VisionPixtralEncoderDecoderConfig
|
142 |
+
|
143 |
+
def __init__(self, config,
|
144 |
+
encoder: Optional[PixtralVisionModelBatch] = None,
|
145 |
+
decoder: Optional[PreTrainedModel] = None):
|
146 |
+
super().__init__(config, encoder, decoder)
|
147 |
+
|
148 |
+
def forward(
|
149 |
+
self,
|
150 |
+
pixel_values: Optional[torch.Tensor] = None,
|
151 |
+
image_sizes: Optional[torch.Tensor] = None,
|
152 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
153 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
154 |
+
decoder_attention_mask: Optional[torch.BoolTensor] = None,
|
155 |
+
encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
|
156 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
157 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
158 |
+
labels: Optional[torch.LongTensor] = None,
|
159 |
+
use_cache: Optional[bool] = None,
|
160 |
+
output_attentions: Optional[bool] = None,
|
161 |
+
output_hidden_states: Optional[bool] = None,
|
162 |
+
return_dict: Optional[bool] = None,
|
163 |
+
**kwargs,
|
164 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
165 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
166 |
+
|
167 |
+
# num_items_in_batch is only needed for loss computation
|
168 |
+
num_items_in_batch = kwargs.pop("num_items_in_batch", None)
|
169 |
+
|
170 |
+
kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")}
|
171 |
+
|
172 |
+
kwargs_decoder = {
|
173 |
+
argument[len("decoder_"):]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
|
174 |
+
}
|
175 |
+
|
176 |
+
if encoder_outputs is None:
|
177 |
+
if pixel_values is None:
|
178 |
+
raise ValueError("You have to specify pixel_values")
|
179 |
+
if encoder_attention_mask is None and image_sizes is None:
|
180 |
+
raise ValueError("Either `encoder_attention_mask` or `image_sizes` must be defined")
|
181 |
+
if encoder_attention_mask is None:
|
182 |
+
h, w = pixel_values.shape[-2:]
|
183 |
+
h = h // self.encoder.patch_size # simulate convolution to get num_patches
|
184 |
+
w = w // self.encoder.patch_size # simulate convolution to get num_patches
|
185 |
+
encoder_attention_mask = create_attention_mask_batch(w, h, image_sizes, self.encoder.patch_size)
|
186 |
+
encoder_attention_mask = encoder_attention_mask.to(pixel_values.device)
|
187 |
+
encoder_attention_mask = encoder_attention_mask.flatten(start_dim=-2)
|
188 |
+
|
189 |
+
encoder_outputs = self.encoder(
|
190 |
+
pixel_values=pixel_values,
|
191 |
+
image_sizes=image_sizes,
|
192 |
+
attention_mask=encoder_attention_mask,
|
193 |
+
output_attentions=output_attentions,
|
194 |
+
output_hidden_states=output_hidden_states,
|
195 |
+
return_dict=return_dict,
|
196 |
+
**kwargs_encoder,
|
197 |
+
)
|
198 |
+
elif isinstance(encoder_outputs, tuple):
|
199 |
+
encoder_outputs = BaseModelOutput(*encoder_outputs)
|
200 |
+
|
201 |
+
encoder_hidden_states = encoder_outputs[0]
|
202 |
+
|
203 |
+
# optionally project encoder_hidden_states
|
204 |
+
if (
|
205 |
+
self.encoder.config.hidden_size != self.decoder.config.hidden_size
|
206 |
+
and self.decoder.config.cross_attention_hidden_size is None
|
207 |
+
):
|
208 |
+
encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
|
209 |
+
|
210 |
+
# else:
|
211 |
+
# encoder_attention_mask = None
|
212 |
+
|
213 |
+
if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):
|
214 |
+
decoder_input_ids = shift_tokens_right(
|
215 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
216 |
+
)
|
217 |
+
|
218 |
+
# Decode
|
219 |
+
decoder_outputs = self.decoder(
|
220 |
+
input_ids=decoder_input_ids,
|
221 |
+
attention_mask=decoder_attention_mask,
|
222 |
+
encoder_hidden_states=encoder_hidden_states,
|
223 |
+
encoder_attention_mask=encoder_attention_mask,
|
224 |
+
inputs_embeds=decoder_inputs_embeds,
|
225 |
+
output_attentions=output_attentions,
|
226 |
+
output_hidden_states=output_hidden_states,
|
227 |
+
use_cache=use_cache,
|
228 |
+
past_key_values=past_key_values,
|
229 |
+
return_dict=return_dict,
|
230 |
+
**kwargs_decoder,
|
231 |
+
)
|
232 |
+
|
233 |
+
# Compute loss independent from decoder (as some shift the logits inside them)
|
234 |
+
loss = None
|
235 |
+
if labels is not None:
|
236 |
+
logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
|
237 |
+
|
238 |
+
loss = self.loss_function(
|
239 |
+
logits=logits,
|
240 |
+
labels=labels,
|
241 |
+
vocab_size=self.decoder.config.vocab_size,
|
242 |
+
num_items_in_batch=num_items_in_batch,
|
243 |
+
)
|
244 |
+
|
245 |
+
if not return_dict:
|
246 |
+
if loss is not None:
|
247 |
+
return (loss,) + decoder_outputs + encoder_outputs
|
248 |
+
else:
|
249 |
+
return decoder_outputs + encoder_outputs
|
250 |
+
|
251 |
+
return Seq2SeqLMOutput(
|
252 |
+
loss=loss,
|
253 |
+
logits=decoder_outputs.logits,
|
254 |
+
past_key_values=decoder_outputs.past_key_values,
|
255 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
256 |
+
decoder_attentions=decoder_outputs.attentions,
|
257 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
258 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
259 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
260 |
+
encoder_attentions=encoder_outputs.attentions,
|
261 |
+
)
|