VictorSanh
commited on
Commit
•
5b86ca4
1
Parent(s):
2bb004c
there you go
Browse files- README.md +164 -0
- added_tokens.json +4 -0
- common.py +224 -0
- config.json +62 -0
- configuration_idefics2.py +299 -0
- generation_config.json +7 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +776 -0
- modeling_idefics2.py +1542 -0
- perceiver.py +585 -0
- preprocessor_config.json +20 -0
- special_tokens_map.json +46 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +61 -0
- vision.py +634 -0
README.md
CHANGED
@@ -1,3 +1,167 @@
|
|
1 |
---
|
2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
license: apache-2.0
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
datasets:
|
6 |
+
- HuggingFaceM4/WebSight
|
7 |
+
tags:
|
8 |
+
- code
|
9 |
---
|
10 |
+
|
11 |
+
|
12 |
+
# Model Description
|
13 |
+
|
14 |
+
This model converts screenshots of website components into HTML/Tailwind CSS codes.
|
15 |
+
|
16 |
+
It is based on an early checkpoint of our forthcoming vision-language foundation model, which has been further fine-tuned with DoRA using the [Websight-v1](https://huggingface.co/datasets/HuggingFaceM4/Websight) dataset.
|
17 |
+
|
18 |
+
The base model is built upon Mistral-7B and SigLIP-SO400M, and uses the Patch n’ Pack strategy to preserve the original aspect ratio of the input images, with a resolution of up to 980 pixels for each side.
|
19 |
+
Further insights into the model’s architecture and its training process will be detailed upon its release.
|
20 |
+
|
21 |
+
The goal of open-sourcing the WebSight dataset along with the model Sightseer is to kick off an effort to develop improved models capable of converting a website screenshot into actual code.
|
22 |
+
|
23 |
+
Try out the [demo](https://huggingface.co/spaces/HuggingFaceM4/screenshot2html)!
|
24 |
+
|
25 |
+
|
26 |
+
# Code snippet
|
27 |
+
|
28 |
+
The code snippet demonstrates how to perform batched generation to convert screenshots of websites into corresponding HTML + Tailwind code.
|
29 |
+
|
30 |
+
Note that the logic to process, and pad inputs will be encapsulated into a user-friendly processor upon the release of our vision and language model.
|
31 |
+
|
32 |
+
```python
|
33 |
+
import torch
|
34 |
+
import requests
|
35 |
+
|
36 |
+
from datasets import load_dataset
|
37 |
+
from io import BytesIO
|
38 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
39 |
+
from PIL import Image
|
40 |
+
|
41 |
+
from transformers.image_utils import to_numpy_array, PILImageResampling, ChannelDimension
|
42 |
+
from transformers.image_transforms import resize, to_channel_dimension_format
|
43 |
+
|
44 |
+
|
45 |
+
DEVICE = torch.device("cuda")
|
46 |
+
PROCESSOR = AutoProcessor.from_pretrained(
|
47 |
+
"HuggingFaceM4/Sightseer",
|
48 |
+
token=API_TOKEN,
|
49 |
+
)
|
50 |
+
MODEL = AutoModelForCausalLM.from_pretrained(
|
51 |
+
"HuggingFaceM4/Sightseer",
|
52 |
+
token=API_TOKEN,
|
53 |
+
trust_remote_code=True,
|
54 |
+
torch_dtype=torch.bfloat16,
|
55 |
+
).to(DEVICE)
|
56 |
+
image_seq_len = MODEL.config.perceiver_config.resampler_n_latents
|
57 |
+
BOS_TOKEN = PROCESSOR.tokenizer.bos_token
|
58 |
+
BAD_WORDS_IDS = PROCESSOR.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
59 |
+
|
60 |
+
|
61 |
+
def convert_to_rgb(image):
|
62 |
+
if image.mode == "RGB":
|
63 |
+
return image
|
64 |
+
|
65 |
+
image_rgba = image.convert("RGBA")
|
66 |
+
background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
|
67 |
+
alpha_composite = Image.alpha_composite(background, image_rgba)
|
68 |
+
alpha_composite = alpha_composite.convert("RGB")
|
69 |
+
return alpha_composite
|
70 |
+
|
71 |
+
|
72 |
+
# The processor is the same as the Idefics processor except for the BILINEAR interpolation,
|
73 |
+
# so this is a hack in order to redefine ONLY the transform method
|
74 |
+
def custom_transform(x):
|
75 |
+
x = convert_to_rgb(x)
|
76 |
+
x = to_numpy_array(x)
|
77 |
+
|
78 |
+
height, width = x.shape[:2]
|
79 |
+
aspect_ratio = width / height
|
80 |
+
if width >= height and width > 980:
|
81 |
+
width = 980
|
82 |
+
height = int(width / aspect_ratio)
|
83 |
+
elif height > width and height > 980:
|
84 |
+
height = 980
|
85 |
+
width = int(height * aspect_ratio)
|
86 |
+
width = max(width, 378)
|
87 |
+
height = max(height, 378)
|
88 |
+
|
89 |
+
x = resize(x, (height, width), resample=PILImageResampling.BILINEAR)
|
90 |
+
x = PROCESSOR.image_processor.rescale(x, scale=1 / 255)
|
91 |
+
x = PROCESSOR.image_processor.normalize(
|
92 |
+
x,
|
93 |
+
mean=PROCESSOR.image_processor.image_mean,
|
94 |
+
std=PROCESSOR.image_processor.image_std
|
95 |
+
)
|
96 |
+
x = to_channel_dimension_format(x, ChannelDimension.FIRST)
|
97 |
+
x = torch.tensor(x)
|
98 |
+
return x
|
99 |
+
|
100 |
+
|
101 |
+
# Create text token inputs
|
102 |
+
image_seq = '<image>' * image_seq_len
|
103 |
+
inputs = PROCESSOR.tokenizer(
|
104 |
+
[
|
105 |
+
f"{BOS_TOKEN}<fake_token_around_image>{image_seq}<fake_token_around_image>In this image, we see",
|
106 |
+
f"{BOS_TOKEN}bla bla<fake_token_around_image>{image_seq}<fake_token_around_image>{image_seq}<fake_token_around_image>",
|
107 |
+
],
|
108 |
+
return_tensors="pt",
|
109 |
+
add_special_tokens=False,
|
110 |
+
padding=True,
|
111 |
+
)
|
112 |
+
|
113 |
+
|
114 |
+
# Create pixel inputs
|
115 |
+
# We load images from WebSight, but any screenshot in the form of a PIL image will work
|
116 |
+
dataset = load_dataset("HuggingFaceM4/WebSight", streaming=True)
|
117 |
+
dataset = iter(dataset)
|
118 |
+
image1 = next(dataset)
|
119 |
+
image2 = next(dataset)
|
120 |
+
raw_images = [
|
121 |
+
[image1],
|
122 |
+
[image2],
|
123 |
+
]
|
124 |
+
output_images = [
|
125 |
+
[PROCESSOR.image_processor(img, transform=custom_transform) for img in img_list]
|
126 |
+
for img_list in raw_images
|
127 |
+
]
|
128 |
+
total_batch_size = len(output_images)
|
129 |
+
max_num_images = max([len(img_l) for img_l in output_images])
|
130 |
+
max_height = max([i.size(2) for img_l in output_images for i in img_l])
|
131 |
+
max_width = max([i.size(3) for img_l in output_images for i in img_l])
|
132 |
+
padded_image_tensor = torch.zeros(total_batch_size, max_num_images, 3, max_height, max_width)
|
133 |
+
padded_pixel_attention_masks = torch.zeros(
|
134 |
+
total_batch_size, max_num_images, max_height, max_width, dtype=torch.bool
|
135 |
+
)
|
136 |
+
for batch_idx, img_l in enumerate(output_images):
|
137 |
+
for img_idx, img in enumerate(img_l):
|
138 |
+
im_height, im_width = img.size()[2:]
|
139 |
+
padded_image_tensor[batch_idx, img_idx, :, :im_height, :im_width] = img
|
140 |
+
padded_pixel_attention_masks[batch_idx, img_idx, :im_height, :im_width] = True
|
141 |
+
|
142 |
+
inputs["pixel_values"] = padded_image_tensor
|
143 |
+
inputs["pixel_attention_mask"] = padded_pixel_attention_masks
|
144 |
+
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
145 |
+
|
146 |
+
generated_ids = MODEL.generate(**inputs, bad_words_ids=BAD_WORDS_IDS, max_new_tokens=10)
|
147 |
+
generated_texts = PROCESSOR.batch_decode(generated_ids, skip_special_tokens=True)
|
148 |
+
|
149 |
+
print(generated_texts)
|
150 |
+
```
|
151 |
+
|
152 |
+
|
153 |
+
# Model Details
|
154 |
+
|
155 |
+
- **Developed by:** Hugging Face
|
156 |
+
- **Model type:** Multi-modal model (screenshot of website component to HTML/Tailwind CSS code)
|
157 |
+
- **Language(s) (NLP):** en
|
158 |
+
- **License:** see [License section](#license)
|
159 |
+
- **Parent Models:** [SigLIP](https://github.com/huggingface/transformers/pull/26522) and [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
|
160 |
+
- **Resources for more information:**
|
161 |
+
- WebSight dataset: [Dataset card](https://huggingface.co/datasets/HuggingFaceM4/Websight)
|
162 |
+
|
163 |
+
# License
|
164 |
+
|
165 |
+
The model is built on top of two pre-trained models: [SigLIP](https://github.com/huggingface/transformers/pull/26522) and [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1), which are delivered under an Apache-2.0 license. As such, users should comply with the licenses of these models.
|
166 |
+
|
167 |
+
The two pre-trained models are connected to each other with newly initialized parameters that we train. These are not based on any of the two base frozen models forming the composite model. We release the additional weights we trained under an Apache-2.0 license.
|
added_tokens.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<fake_token_around_image>": 32000,
|
3 |
+
"<image>": 32001
|
4 |
+
}
|
common.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
|
21 |
+
import torch
|
22 |
+
from torch import nn
|
23 |
+
from transformers.activations import ACT2FN
|
24 |
+
|
25 |
+
import torch.nn.functional as F
|
26 |
+
|
27 |
+
class MLP(nn.Module):
|
28 |
+
def __init__(self, activation, input_size, intermediate_size, output_size):
|
29 |
+
super().__init__()
|
30 |
+
self.input_size = input_size
|
31 |
+
self.intermediate_size = intermediate_size
|
32 |
+
self.output_size = output_size
|
33 |
+
|
34 |
+
self.gate_proj = nn.Linear(input_size, intermediate_size, bias=False)
|
35 |
+
self.up_proj = nn.Linear(input_size, intermediate_size, bias=False)
|
36 |
+
self.down_proj = nn.Linear(intermediate_size, output_size, bias=False)
|
37 |
+
self.act_fn = ACT2FN[activation]
|
38 |
+
|
39 |
+
def forward(self, x):
|
40 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
41 |
+
|
42 |
+
|
43 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm
|
44 |
+
class RMSNorm(nn.Module):
|
45 |
+
def __init__(self, hidden_size, eps=1e-6):
|
46 |
+
"""
|
47 |
+
RMSNorm is equivalent to T5LayerNorm
|
48 |
+
"""
|
49 |
+
super().__init__()
|
50 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
51 |
+
self.variance_epsilon = eps
|
52 |
+
|
53 |
+
def forward(self, hidden_states):
|
54 |
+
input_dtype = hidden_states.dtype
|
55 |
+
hidden_states = hidden_states.to(torch.float32)
|
56 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
57 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
58 |
+
return self.weight * hidden_states.to(input_dtype)
|
59 |
+
|
60 |
+
|
61 |
+
class DecoupledEmbedding(nn.Embedding):
|
62 |
+
# Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/sparse.html#Embedding
|
63 |
+
"""
|
64 |
+
Implements a decoupling of parameters to allow freezing (or not) a subset of the embeddings.
|
65 |
+
In practise, the regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `num_additional_embeddings` > 0, then it will create `num_additional_embeddings` additional parameters that are always trained.
|
66 |
+
If `num_additional_embeddings=0`, then the module defaults back to the regular behavior of `nn.Embedding`.
|
67 |
+
"""
|
68 |
+
|
69 |
+
def __init__(
|
70 |
+
self,
|
71 |
+
num_embeddings,
|
72 |
+
num_additional_embeddings,
|
73 |
+
embedding_dim,
|
74 |
+
partially_freeze=False,
|
75 |
+
device=None,
|
76 |
+
dtype=None,
|
77 |
+
padding_idx=None,
|
78 |
+
**kwargs,
|
79 |
+
) -> None:
|
80 |
+
"""
|
81 |
+
num_additional_embeddings: int. Number of additional embeddings. Only useful when you `partially_freeze=True`.
|
82 |
+
partially_freeze: bool. If True, the regular `weight` will be frozen. `additional_weight` is never frozen.
|
83 |
+
|
84 |
+
Note: there are a lot of other parameters to initialize a standard `nn.Embedding` such as `padding_idx`, `max_norm` or `norm_type`. We are not supporting these.
|
85 |
+
"""
|
86 |
+
if padding_idx is not None and padding_idx > num_embeddings:
|
87 |
+
raise ValueError(f"padding_idx must be within num_embeddings. Got {padding_idx} and {num_embeddings}")
|
88 |
+
super().__init__(
|
89 |
+
num_embeddings=num_embeddings,
|
90 |
+
embedding_dim=embedding_dim,
|
91 |
+
device=device,
|
92 |
+
dtype=dtype,
|
93 |
+
padding_idx=padding_idx,
|
94 |
+
**kwargs,
|
95 |
+
)
|
96 |
+
self.num_embeddings = num_embeddings
|
97 |
+
self.padding_idx = padding_idx
|
98 |
+
self.num_additional_embeddings = num_additional_embeddings
|
99 |
+
self.partially_freeze = partially_freeze
|
100 |
+
|
101 |
+
if partially_freeze:
|
102 |
+
self.weight.requires_grad_(False)
|
103 |
+
|
104 |
+
if self.num_additional_embeddings > 0:
|
105 |
+
self.additional_embedding = nn.Embedding(
|
106 |
+
num_embeddings=self.num_additional_embeddings,
|
107 |
+
embedding_dim=embedding_dim,
|
108 |
+
device=device,
|
109 |
+
dtype=dtype,
|
110 |
+
)
|
111 |
+
|
112 |
+
def forward(self, input_ids):
|
113 |
+
"""
|
114 |
+
we have 2 embeddings, with different indices - one pretrained self.weight and another
|
115 |
+
self.additional_embedding.weight that is being trained.
|
116 |
+
|
117 |
+
in order to make a lookup of the input ids, we:
|
118 |
+
1. find out the indices of the entries belonging to the 2nd embedding
|
119 |
+
2. extract those values while subtracting the size of the first embedding (num_embeddings),
|
120 |
+
since the 2nd embedding starts from 0 and not num_embeddings
|
121 |
+
3. perform the 2nd embedding lookup
|
122 |
+
4. now we handle the 1st embedding, we overwrite indices belonging to the 2nd embedding with a padding index
|
123 |
+
5. perform the 1st embedding lookup
|
124 |
+
6. now we overwrite the values in the 1st embedding lookup with the values of the 2nd embedding lookup
|
125 |
+
|
126 |
+
note: for the 1st embedding lookup we could have looked up only the low indices and not do
|
127 |
+
the padding, but then we have to create a new tensor and populate it with 2 tensors that are
|
128 |
+
spread out across various indices - i.e. not a simple concat - I haven't benchmarked the
|
129 |
+
complex case if it's any faster, given that seqlens are usually relatively short it's
|
130 |
+
probably not faster or if faster not by much - but might be a good idea to measure.
|
131 |
+
|
132 |
+
"""
|
133 |
+
if self.num_additional_embeddings == 0:
|
134 |
+
return self.additional_embedding(input_ids)
|
135 |
+
|
136 |
+
# Clone so that we don't modify the original input_ids later on
|
137 |
+
input_ids = input_ids.clone()
|
138 |
+
additional_vocab_indices = torch.where(input_ids >= self.num_embeddings)
|
139 |
+
input_ids_additional_vocab = input_ids[additional_vocab_indices]
|
140 |
+
additional_embeddings = self.additional_embedding(input_ids_additional_vocab - self.num_embeddings)
|
141 |
+
|
142 |
+
# for successful lookup replace input_ids with 0, the results of these will be discarded anyway
|
143 |
+
input_ids[additional_vocab_indices] = 0
|
144 |
+
full_vector = F.embedding(input_ids, self.weight)
|
145 |
+
|
146 |
+
# overwrite the records with high indices
|
147 |
+
full_vector[additional_vocab_indices] = additional_embeddings
|
148 |
+
|
149 |
+
return full_vector
|
150 |
+
|
151 |
+
def extra_repr(self) -> str:
|
152 |
+
return "num_embeddings={}, num_additional_embeddings={}, embedding_dim={}, partially_freeze={}".format(
|
153 |
+
self.num_embeddings,
|
154 |
+
self.num_additional_embeddings,
|
155 |
+
self.embedding_dim,
|
156 |
+
self.partially_freeze,
|
157 |
+
)
|
158 |
+
|
159 |
+
@classmethod
|
160 |
+
def from_pretrained(cls, embeddings, freeze=True, **kwargs):
|
161 |
+
raise NotImplementedError
|
162 |
+
|
163 |
+
|
164 |
+
class DecoupledLinear(nn.Linear):
|
165 |
+
# Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear
|
166 |
+
"""
|
167 |
+
Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters.
|
168 |
+
In practise, the regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0, then it will create `out_additional_features * in_features` additional parameters that are always trained.
|
169 |
+
If `out_additional_features=0`, then the module defaults back to the regular behavior of `nn.Linear`.
|
170 |
+
"""
|
171 |
+
|
172 |
+
def __init__(
|
173 |
+
self,
|
174 |
+
in_features: int,
|
175 |
+
out_features: int,
|
176 |
+
out_additional_features: int = 0,
|
177 |
+
bias: bool = True,
|
178 |
+
partially_freeze: bool = True,
|
179 |
+
device=None,
|
180 |
+
dtype=None,
|
181 |
+
) -> None:
|
182 |
+
"""
|
183 |
+
out_additional_features: int. Number of additional trainable dimensions. Only makes sense when `partially_freeze=True`.
|
184 |
+
partially_freeze: bool. If True, the regular `weight` will be frozen and extra parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear.
|
185 |
+
"""
|
186 |
+
super().__init__(in_features, out_features, bias, device, dtype)
|
187 |
+
self.out_additional_features = out_additional_features
|
188 |
+
self.partially_freeze = partially_freeze
|
189 |
+
|
190 |
+
self.in_features = in_features
|
191 |
+
self.out_features = out_features
|
192 |
+
|
193 |
+
if partially_freeze:
|
194 |
+
self.weight.requires_grad_(False)
|
195 |
+
if bias:
|
196 |
+
self.bias.requires_grad_(False)
|
197 |
+
|
198 |
+
if out_additional_features > 0:
|
199 |
+
self.additional_fc = nn.Linear(
|
200 |
+
in_features=in_features,
|
201 |
+
out_features=out_additional_features,
|
202 |
+
bias=bias,
|
203 |
+
device=device,
|
204 |
+
dtype=dtype,
|
205 |
+
)
|
206 |
+
|
207 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
208 |
+
output = F.linear(input, self.weight, self.bias)
|
209 |
+
|
210 |
+
if self.out_additional_features > 0:
|
211 |
+
additional_features = self.additional_fc(input)
|
212 |
+
output = torch.cat((output, additional_features), -1)
|
213 |
+
|
214 |
+
return output
|
215 |
+
|
216 |
+
def extra_repr(self) -> str:
|
217 |
+
"""Overwriting `nn.Linear.extra_repr` to include new parameters."""
|
218 |
+
return "in_features={}, out_features={}, out_additional_features={}, bias={}, partially_freeze={}".format(
|
219 |
+
self.in_features,
|
220 |
+
self.out_features,
|
221 |
+
self.out_additional_features,
|
222 |
+
self.bias is not None,
|
223 |
+
self.partially_freeze,
|
224 |
+
)
|
config.json
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_commit_hash": null,
|
3 |
+
"_name_or_path": "None",
|
4 |
+
"additional_vocab_size": 2,
|
5 |
+
"alpha_initializer": "zeros",
|
6 |
+
"alpha_type": "float",
|
7 |
+
"alphas_initializer_range": 0.0,
|
8 |
+
"architectures": [
|
9 |
+
"Idefics2ForVisionText2Text"
|
10 |
+
],
|
11 |
+
"attention_dropout": 0.0,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoConfig": "configuration_idefics2.Idefics2Config",
|
14 |
+
"AutoModelForCausalLM": "modeling_idefics2.Idefics2ForVisionText2Text"
|
15 |
+
},
|
16 |
+
"bos_token_id": 1,
|
17 |
+
"cross_layer_interval": 1,
|
18 |
+
"eos_token_id": 2,
|
19 |
+
"freeze_lm_head": false,
|
20 |
+
"freeze_text_layers": false,
|
21 |
+
"freeze_text_module_exceptions": [],
|
22 |
+
"freeze_vision_layers": false,
|
23 |
+
"freeze_vision_module_exceptions": [],
|
24 |
+
"hidden_act": "silu",
|
25 |
+
"hidden_size": 4096,
|
26 |
+
"image_token_id": 32001,
|
27 |
+
"initializer_range": 0.02,
|
28 |
+
"intermediate_size": 14336,
|
29 |
+
"max_position_embeddings": 32768,
|
30 |
+
"model_type": "idefics2",
|
31 |
+
"num_attention_heads": 32,
|
32 |
+
"num_hidden_layers": 32,
|
33 |
+
"num_key_value_heads": 8,
|
34 |
+
"pad_token_id": 0,
|
35 |
+
"perceiver_config": {
|
36 |
+
"num_key_value_heads": 4,
|
37 |
+
"resampler_depth": 3,
|
38 |
+
"resampler_head_dim": 96,
|
39 |
+
"resampler_n_heads": 16,
|
40 |
+
"resampler_n_latents": 64,
|
41 |
+
"qk_layer_norms_perceiver": true
|
42 |
+
},
|
43 |
+
"qk_layer_norms": true,
|
44 |
+
"rms_norm_eps": 1e-05,
|
45 |
+
"rope_theta": 10000.0,
|
46 |
+
"sliding_window": 4096,
|
47 |
+
"tie_word_embeddings": false,
|
48 |
+
"torch_dtype": "bfloat16",
|
49 |
+
"transformers_version": "4.34.0.dev0",
|
50 |
+
"use_cache": true,
|
51 |
+
"use_resampler": true,
|
52 |
+
"vision_config": {
|
53 |
+
"hidden_size": 1152,
|
54 |
+
"image_size": 980,
|
55 |
+
"intermediate_size": 4304,
|
56 |
+
"model_type": "idefics2",
|
57 |
+
"num_attention_heads": 16,
|
58 |
+
"num_hidden_layers": 27,
|
59 |
+
"patch_size": 14
|
60 |
+
},
|
61 |
+
"vocab_size": 32000
|
62 |
+
}
|
configuration_idefics2.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Mistral AI and 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 |
+
""" Idefics2 model configuration"""
|
16 |
+
from transformers.configuration_utils import PretrainedConfig
|
17 |
+
from transformers.utils import logging
|
18 |
+
|
19 |
+
|
20 |
+
logger = logging.get_logger(__name__)
|
21 |
+
|
22 |
+
MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
23 |
+
"HuggingFaceM4/idefics2": "https://huggingface.co/HuggingFaceM4/idefics2/resolve/main/config.json",
|
24 |
+
}
|
25 |
+
|
26 |
+
|
27 |
+
class Idefics2VisionConfig(PretrainedConfig):
|
28 |
+
r"""
|
29 |
+
"""
|
30 |
+
model_type = "idefics2"
|
31 |
+
|
32 |
+
def __init__(
|
33 |
+
self,
|
34 |
+
hidden_size=768,
|
35 |
+
intermediate_size=3072,
|
36 |
+
num_hidden_layers=12,
|
37 |
+
num_attention_heads=12,
|
38 |
+
num_channels=3,
|
39 |
+
image_size=224,
|
40 |
+
patch_size=32,
|
41 |
+
hidden_act="gelu_pytorch_tanh",
|
42 |
+
layer_norm_eps=1e-6,
|
43 |
+
attention_dropout=0.0,
|
44 |
+
initializer_range=0.02,
|
45 |
+
initializer_factor=1.0,
|
46 |
+
_flash_attn_2_enabled=True,
|
47 |
+
**kwargs,
|
48 |
+
):
|
49 |
+
super().__init__(**kwargs)
|
50 |
+
|
51 |
+
self.hidden_size = hidden_size
|
52 |
+
self.intermediate_size = intermediate_size
|
53 |
+
self.num_hidden_layers = num_hidden_layers
|
54 |
+
self.num_attention_heads = num_attention_heads
|
55 |
+
self.num_channels = num_channels
|
56 |
+
self.patch_size = patch_size
|
57 |
+
self.image_size = image_size
|
58 |
+
self.initializer_range = initializer_range
|
59 |
+
self.initializer_factor = initializer_factor
|
60 |
+
self.attention_dropout = attention_dropout
|
61 |
+
self.layer_norm_eps = layer_norm_eps
|
62 |
+
self.hidden_act = hidden_act
|
63 |
+
self._flash_attn_2_enabled = _flash_attn_2_enabled
|
64 |
+
|
65 |
+
|
66 |
+
class Idefics2PerceiverConfig(PretrainedConfig):
|
67 |
+
r"""
|
68 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
69 |
+
documentation from [`PretrainedConfig`] for more information.
|
70 |
+
|
71 |
+
Args:
|
72 |
+
use_resampler (`bool`, *optional*, defaults to `False`):
|
73 |
+
Whether or not to use the resampler
|
74 |
+
resampler_n_latents (`int`, *optional*, defaults to ):
|
75 |
+
Number of latent embeddings to resample ("compress") the input sequence to (usually < 128).
|
76 |
+
resampler_depth (`int`, *optional*, defaults to 6):
|
77 |
+
Depth of the Perceiver Resampler (Transformer w/ cross attention). Should be shallow (< 3).
|
78 |
+
resampler_n_heads (`int`, *optional*, defaults to 16):
|
79 |
+
Number of heads in each Transformer block (for multi-headed self-attention).
|
80 |
+
resampler_head_dim (`int`, *optional*, defaults to 96):
|
81 |
+
Dimensionality of each head projection in the Transformer block.
|
82 |
+
qk_layer_norms_perceiver (`bool`, *optional*, defaults to `False`):
|
83 |
+
Whether or not to use qk layer norms in perceiver
|
84 |
+
"""
|
85 |
+
model_type = "idefics2"
|
86 |
+
|
87 |
+
def __init__(
|
88 |
+
self,
|
89 |
+
hidden_act="silu",
|
90 |
+
resampler_n_latents=64,
|
91 |
+
resampler_depth=6,
|
92 |
+
resampler_n_heads=16,
|
93 |
+
num_key_value_heads=1,
|
94 |
+
resampler_head_dim=96,
|
95 |
+
qk_layer_norms_perceiver=False,
|
96 |
+
attention_dropout=0.0,
|
97 |
+
**kwargs,
|
98 |
+
):
|
99 |
+
self.hidden_act = hidden_act
|
100 |
+
self.resampler_n_latents = resampler_n_latents
|
101 |
+
self.resampler_depth = resampler_depth
|
102 |
+
self.resampler_n_heads = resampler_n_heads
|
103 |
+
self.num_key_value_heads = num_key_value_heads
|
104 |
+
self.resampler_head_dim = resampler_head_dim
|
105 |
+
self.qk_layer_norms_perceiver = qk_layer_norms_perceiver
|
106 |
+
self.attention_dropout = attention_dropout
|
107 |
+
if self.num_key_value_heads > self.resampler_n_heads:
|
108 |
+
raise ValueError(
|
109 |
+
f"num_key_value_heads={self.num_key_value_heads} must be less than or equal to"
|
110 |
+
f" resampler_n_heads={self.resampler_n_heads}"
|
111 |
+
)
|
112 |
+
|
113 |
+
super().__init__(**kwargs)
|
114 |
+
|
115 |
+
|
116 |
+
class Idefics2Config(PretrainedConfig):
|
117 |
+
r"""
|
118 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
119 |
+
documentation from [`PretrainedConfig`] for more information.
|
120 |
+
|
121 |
+
Args:
|
122 |
+
additional_vocab_size (`int`, *optional`, defaults to 0):
|
123 |
+
Additional vocabulary size of the model, typically for the special "<img>" token. Additional vocab tokens
|
124 |
+
are always trainable whereas regular vocab tokens can be frozen or not.
|
125 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
126 |
+
Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the
|
127 |
+
`inputs_ids` passed when calling [`MistralModel`]
|
128 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
129 |
+
Dimension of the hidden representations.
|
130 |
+
intermediate_size (`int`, *optional*, defaults to 14336):
|
131 |
+
Dimension of the MLP representations.
|
132 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
133 |
+
Number of hidden layers in the Transformer encoder.
|
134 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
135 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
136 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
137 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
138 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
139 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
140 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
141 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
142 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
|
143 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
144 |
+
The non-linear activation function (function or string) in the decoder.
|
145 |
+
max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
|
146 |
+
The maximum sequence length that this model might ever be used with. Mistral's sliding window attention
|
147 |
+
allows sequence of up to 4096*32 tokens.
|
148 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
149 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
150 |
+
alpha_initializer (`str`, *optional*, defaults to `"zeros"`):
|
151 |
+
Initialization type for the alphas.
|
152 |
+
alphas_initializer_range (`float`, *optional*, defaults to 0.0):
|
153 |
+
The standard deviation of the truncated_normal_initializer for initializing the alphas in the Gated Cross
|
154 |
+
Attention.
|
155 |
+
alpha_type (`str`, *optional*, defaults to `"float"`):
|
156 |
+
Whether the gating alphas should be vectors or single floats.
|
157 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
158 |
+
The epsilon used by the rms normalization layers.
|
159 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
160 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
161 |
+
relevant if `config.is_decoder=True`.
|
162 |
+
pad_token_id (`int`, *optional*):
|
163 |
+
The id of the padding token.
|
164 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
165 |
+
The id of the "beginning-of-sequence" token.
|
166 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
167 |
+
The id of the "end-of-sequence" token.
|
168 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
169 |
+
Whether the model's input and output word embeddings should be tied.
|
170 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
171 |
+
The base period of the RoPE embeddings.
|
172 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
173 |
+
Sliding window attention window size. If not specified, will default to `4096`.
|
174 |
+
cross_layer_interval (`int`, *optional*, default to 1)
|
175 |
+
Interval for cross attention (from text to image) layers.
|
176 |
+
qk_layer_norms (`bool`, *optional*, defaults to `False`): Whether to add layer norm after q and k
|
177 |
+
freeze_text_layers (`bool`, *optional*, defaults to `True`): Whether to freeze text layers
|
178 |
+
freeze_text_module_exceptions (`bool`, *optional*, defaults to `[]`):
|
179 |
+
Exceptions to freezing text layers when `freeze_text_layers` is `True`
|
180 |
+
freeze_lm_head (`bool`, *optional*, defaults to `False`): Whether to freeze lm head
|
181 |
+
freeze_vision_layers (`bool`, *optional*, defaults to `True`): Whether to freeze vision layers
|
182 |
+
freeze_vision_module_exceptions (`bool`, *optional*, defaults to `[]`):
|
183 |
+
Exceptions to freezing vision layers when `freeze_vision_layers` is `True`
|
184 |
+
use_resampler (`bool`, *optional*, defaults to `False`): Whether to use the Resampler
|
185 |
+
vision_config (`IdeficsVisionConfig`, *optional*): Custom vision config or dict
|
186 |
+
perceiver_config (`IdeficsPerceiverConfig`, *optional*): Custom perceiver config or dict
|
187 |
+
|
188 |
+
Example:
|
189 |
+
```python
|
190 |
+
>>> from transformers import MistralModel, MistralConfig
|
191 |
+
|
192 |
+
>>> # Initializing a Mistral 7B style configuration
|
193 |
+
>>> configuration = MistralConfig()
|
194 |
+
|
195 |
+
>>> # Initializing a model from the Mistral 7B style configuration
|
196 |
+
>>> model = MistralModel(configuration)
|
197 |
+
|
198 |
+
>>> # Accessing the model configuration
|
199 |
+
>>> configuration = model.config
|
200 |
+
```"""
|
201 |
+
model_type = "idefics2"
|
202 |
+
is_composition = False
|
203 |
+
|
204 |
+
def __init__(
|
205 |
+
self,
|
206 |
+
additional_vocab_size=0,
|
207 |
+
vocab_size=32000,
|
208 |
+
hidden_size=4096,
|
209 |
+
intermediate_size=14336,
|
210 |
+
num_hidden_layers=32,
|
211 |
+
num_attention_heads=32,
|
212 |
+
num_key_value_heads=8,
|
213 |
+
hidden_act="silu",
|
214 |
+
max_position_embeddings=4096 * 32,
|
215 |
+
initializer_range=0.02,
|
216 |
+
alpha_initializer="zeros",
|
217 |
+
alphas_initializer_range=0.0,
|
218 |
+
alpha_type="float",
|
219 |
+
rms_norm_eps=1e-6,
|
220 |
+
use_cache=True,
|
221 |
+
pad_token_id=0, # None in the original configuration_mistral, we set it to the unk_token_id
|
222 |
+
bos_token_id=1,
|
223 |
+
eos_token_id=2,
|
224 |
+
image_token_id=32_001,
|
225 |
+
tie_word_embeddings=False,
|
226 |
+
rope_theta=10000.0,
|
227 |
+
sliding_window=4096,
|
228 |
+
cross_layer_interval=1,
|
229 |
+
qk_layer_norms=False,
|
230 |
+
freeze_text_layers=True,
|
231 |
+
freeze_text_module_exceptions=[],
|
232 |
+
freeze_lm_head=False,
|
233 |
+
freeze_vision_layers=True,
|
234 |
+
freeze_vision_module_exceptions=[],
|
235 |
+
attention_dropout=0.0,
|
236 |
+
_flash_attn_2_enabled=True,
|
237 |
+
use_resampler=True,
|
238 |
+
vision_config=None,
|
239 |
+
perceiver_config=None,
|
240 |
+
**kwargs,
|
241 |
+
):
|
242 |
+
self.vocab_size = vocab_size
|
243 |
+
self.additional_vocab_size = additional_vocab_size
|
244 |
+
self.image_token_id = image_token_id
|
245 |
+
self.max_position_embeddings = max_position_embeddings
|
246 |
+
self.hidden_size = hidden_size
|
247 |
+
self.intermediate_size = intermediate_size
|
248 |
+
self.num_hidden_layers = num_hidden_layers
|
249 |
+
self.num_attention_heads = num_attention_heads
|
250 |
+
self.sliding_window = sliding_window
|
251 |
+
|
252 |
+
# for backward compatibility
|
253 |
+
if num_key_value_heads is None:
|
254 |
+
num_key_value_heads = num_attention_heads
|
255 |
+
|
256 |
+
self.num_key_value_heads = num_key_value_heads
|
257 |
+
self.hidden_act = hidden_act
|
258 |
+
self.initializer_range = initializer_range
|
259 |
+
self.alpha_initializer = alpha_initializer
|
260 |
+
self.alphas_initializer_range = alphas_initializer_range
|
261 |
+
self.alpha_type = alpha_type
|
262 |
+
self.rms_norm_eps = rms_norm_eps
|
263 |
+
self.use_cache = use_cache
|
264 |
+
self.rope_theta = rope_theta
|
265 |
+
|
266 |
+
self.cross_layer_interval = cross_layer_interval
|
267 |
+
self.qk_layer_norms = qk_layer_norms
|
268 |
+
self.freeze_vision_layers = freeze_vision_layers
|
269 |
+
|
270 |
+
self.freeze_text_layers = freeze_text_layers
|
271 |
+
self.freeze_text_module_exceptions = freeze_text_module_exceptions
|
272 |
+
self.freeze_vision_module_exceptions = freeze_vision_module_exceptions
|
273 |
+
self.freeze_lm_head = freeze_lm_head
|
274 |
+
|
275 |
+
self.use_resampler = use_resampler
|
276 |
+
self._flash_attn_2_enabled = _flash_attn_2_enabled
|
277 |
+
self.attention_dropout = attention_dropout
|
278 |
+
|
279 |
+
if perceiver_config is None:
|
280 |
+
self.perceiver_config = Idefics2PerceiverConfig()
|
281 |
+
elif isinstance(perceiver_config, dict):
|
282 |
+
self.perceiver_config = Idefics2PerceiverConfig(**perceiver_config)
|
283 |
+
elif isinstance(perceiver_config, Idefics2PerceiverConfig):
|
284 |
+
self.perceiver_config = perceiver_config
|
285 |
+
|
286 |
+
if vision_config is None:
|
287 |
+
self.vision_config = Idefics2VisionConfig()
|
288 |
+
elif isinstance(vision_config, dict):
|
289 |
+
self.vision_config = Idefics2VisionConfig(**vision_config)
|
290 |
+
elif isinstance(vision_config, Idefics2VisionConfig):
|
291 |
+
self.vision_config = vision_config
|
292 |
+
|
293 |
+
super().__init__(
|
294 |
+
pad_token_id=pad_token_id,
|
295 |
+
bos_token_id=bos_token_id,
|
296 |
+
eos_token_id=eos_token_id,
|
297 |
+
tie_word_embeddings=tie_word_embeddings,
|
298 |
+
**kwargs,
|
299 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"transformers_version": "4.37.1"
|
7 |
+
}
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:84da111d10913688eb45e88b253de9dc053f1b079ca3865b18680f5db895579d
|
3 |
+
size 4966708008
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f5099ad602f89eacb8b7ad6131be7d8bb4cc98da2ffc2463a41c31edc96fa278
|
3 |
+
size 4915916128
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b1f5417310f95ca8d532ab312ea44ceb2c1786a1c4e25399b23a93a634c6f8a
|
3 |
+
size 4999819336
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2134c01ddb025692cd0966aa006e728c09fc9a4fd4bcf231c873c16af37ee9c5
|
3 |
+
size 1923190712
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,776 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {},
|
3 |
+
"weight_map": {
|
4 |
+
"lm_head.additional_fc.weight": "model-00004-of-00004.safetensors",
|
5 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
6 |
+
"model.embed_tokens.additional_embedding.weight": "model-00001-of-00004.safetensors",
|
7 |
+
"model.embed_tokens.weight": "model-00001-of-00004.safetensors",
|
8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
13 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
15 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
16 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
17 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
18 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
19 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
20 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
21 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
22 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
23 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
24 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
25 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
26 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
27 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
28 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
29 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
30 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
31 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
32 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
33 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
34 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
35 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
36 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
37 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
38 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
39 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
40 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
41 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
42 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
43 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
44 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
45 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
46 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
47 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
48 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
49 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
50 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
51 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
52 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
53 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
54 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
55 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
56 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
57 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
58 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
59 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
60 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
61 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
62 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
63 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
64 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
65 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
66 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
67 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
68 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
69 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
70 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
71 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
72 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
73 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
74 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
75 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
76 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
77 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
78 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
79 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
80 |
+
"model.layers.16.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
81 |
+
"model.layers.16.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
82 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
83 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
84 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
85 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
86 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
87 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
88 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
89 |
+
"model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
90 |
+
"model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
91 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
92 |
+
"model.layers.17.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
93 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
94 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
95 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
96 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
97 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
98 |
+
"model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
99 |
+
"model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
100 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
101 |
+
"model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
102 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
103 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
104 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
105 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
106 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
107 |
+
"model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
108 |
+
"model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
109 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
110 |
+
"model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
111 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
112 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
113 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
114 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
115 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
116 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
117 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
118 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
119 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
120 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
121 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
122 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
123 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
124 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
125 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
126 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
127 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
128 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
129 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
130 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
131 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
132 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
133 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
134 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
135 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
136 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
137 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
138 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
139 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
140 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
141 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
142 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
143 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
144 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
145 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
146 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
147 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
148 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
149 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
150 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
151 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
152 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
153 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
154 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
155 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
156 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
157 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
158 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
159 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
160 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
161 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
162 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
163 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
164 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
165 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
166 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
167 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
168 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
169 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
170 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
171 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
172 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
173 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
174 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
175 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
176 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
177 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
178 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
179 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
180 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
181 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
182 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
183 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
184 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
185 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
186 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
187 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
188 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
189 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
190 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
191 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
192 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
193 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
194 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
195 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
196 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
197 |
+
"model.layers.28.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
198 |
+
"model.layers.28.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
199 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
200 |
+
"model.layers.28.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
201 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
202 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
203 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
204 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
205 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
206 |
+
"model.layers.29.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
207 |
+
"model.layers.29.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
208 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
209 |
+
"model.layers.29.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
210 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
211 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
212 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
213 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
214 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
215 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
216 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
217 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
218 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
219 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
220 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
221 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
222 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
223 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
224 |
+
"model.layers.30.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
225 |
+
"model.layers.30.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
226 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
227 |
+
"model.layers.30.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
228 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
229 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
230 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
231 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
232 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
233 |
+
"model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
234 |
+
"model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
235 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
236 |
+
"model.layers.31.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
237 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
238 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
239 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
240 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
241 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
242 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
243 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
244 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
245 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
246 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
247 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
248 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
249 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
250 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
251 |
+
"model.layers.5.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
252 |
+
"model.layers.5.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
253 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
254 |
+
"model.layers.5.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
255 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
256 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
257 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
258 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
259 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
260 |
+
"model.layers.6.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
261 |
+
"model.layers.6.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
262 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
263 |
+
"model.layers.6.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
264 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
265 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
266 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
267 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
268 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
269 |
+
"model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
270 |
+
"model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
271 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
272 |
+
"model.layers.7.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
273 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
274 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
275 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
276 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
277 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
278 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
279 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
280 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
281 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
282 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
283 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
284 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
285 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
286 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
287 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
288 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
289 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
290 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
291 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
292 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
293 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
294 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
295 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
296 |
+
"model.modality_projection.down_proj.weight": "model-00001-of-00004.safetensors",
|
297 |
+
"model.modality_projection.gate_proj.weight": "model-00001-of-00004.safetensors",
|
298 |
+
"model.modality_projection.up_proj.weight": "model-00001-of-00004.safetensors",
|
299 |
+
"model.norm.weight": "model-00004-of-00004.safetensors",
|
300 |
+
"model.perceiver_resampler.latents": "model-00001-of-00004.safetensors",
|
301 |
+
"model.perceiver_resampler.layers.0.input_context_norm.weight": "model-00001-of-00004.safetensors",
|
302 |
+
"model.perceiver_resampler.layers.0.input_latents_norm.weight": "model-00001-of-00004.safetensors",
|
303 |
+
"model.perceiver_resampler.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
304 |
+
"model.perceiver_resampler.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
305 |
+
"model.perceiver_resampler.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
306 |
+
"model.perceiver_resampler.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
307 |
+
"model.perceiver_resampler.layers.0.self_attn.k_layer_norm.weight": "model-00001-of-00004.safetensors",
|
308 |
+
"model.perceiver_resampler.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
309 |
+
"model.perceiver_resampler.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
310 |
+
"model.perceiver_resampler.layers.0.self_attn.q_layer_norm.weight": "model-00001-of-00004.safetensors",
|
311 |
+
"model.perceiver_resampler.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
312 |
+
"model.perceiver_resampler.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
313 |
+
"model.perceiver_resampler.layers.1.input_context_norm.weight": "model-00001-of-00004.safetensors",
|
314 |
+
"model.perceiver_resampler.layers.1.input_latents_norm.weight": "model-00001-of-00004.safetensors",
|
315 |
+
"model.perceiver_resampler.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
316 |
+
"model.perceiver_resampler.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
317 |
+
"model.perceiver_resampler.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
318 |
+
"model.perceiver_resampler.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
319 |
+
"model.perceiver_resampler.layers.1.self_attn.k_layer_norm.weight": "model-00001-of-00004.safetensors",
|
320 |
+
"model.perceiver_resampler.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
321 |
+
"model.perceiver_resampler.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
322 |
+
"model.perceiver_resampler.layers.1.self_attn.q_layer_norm.weight": "model-00001-of-00004.safetensors",
|
323 |
+
"model.perceiver_resampler.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
324 |
+
"model.perceiver_resampler.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
325 |
+
"model.perceiver_resampler.layers.2.input_context_norm.weight": "model-00001-of-00004.safetensors",
|
326 |
+
"model.perceiver_resampler.layers.2.input_latents_norm.weight": "model-00001-of-00004.safetensors",
|
327 |
+
"model.perceiver_resampler.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
328 |
+
"model.perceiver_resampler.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
329 |
+
"model.perceiver_resampler.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
330 |
+
"model.perceiver_resampler.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
331 |
+
"model.perceiver_resampler.layers.2.self_attn.k_layer_norm.weight": "model-00001-of-00004.safetensors",
|
332 |
+
"model.perceiver_resampler.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
333 |
+
"model.perceiver_resampler.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
334 |
+
"model.perceiver_resampler.layers.2.self_attn.q_layer_norm.weight": "model-00001-of-00004.safetensors",
|
335 |
+
"model.perceiver_resampler.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
336 |
+
"model.perceiver_resampler.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
337 |
+
"model.perceiver_resampler.norm.weight": "model-00001-of-00004.safetensors",
|
338 |
+
"model.vision_model.embeddings.patch_embedding.bias": "model-00001-of-00004.safetensors",
|
339 |
+
"model.vision_model.embeddings.patch_embedding.weight": "model-00001-of-00004.safetensors",
|
340 |
+
"model.vision_model.embeddings.position_embedding.weight": "model-00001-of-00004.safetensors",
|
341 |
+
"model.vision_model.encoder.layers.0.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
342 |
+
"model.vision_model.encoder.layers.0.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
343 |
+
"model.vision_model.encoder.layers.0.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
344 |
+
"model.vision_model.encoder.layers.0.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
345 |
+
"model.vision_model.encoder.layers.0.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
346 |
+
"model.vision_model.encoder.layers.0.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
347 |
+
"model.vision_model.encoder.layers.0.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
348 |
+
"model.vision_model.encoder.layers.0.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
349 |
+
"model.vision_model.encoder.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
350 |
+
"model.vision_model.encoder.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
351 |
+
"model.vision_model.encoder.layers.0.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
352 |
+
"model.vision_model.encoder.layers.0.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
353 |
+
"model.vision_model.encoder.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
354 |
+
"model.vision_model.encoder.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
355 |
+
"model.vision_model.encoder.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
356 |
+
"model.vision_model.encoder.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
357 |
+
"model.vision_model.encoder.layers.1.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
358 |
+
"model.vision_model.encoder.layers.1.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
359 |
+
"model.vision_model.encoder.layers.1.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
360 |
+
"model.vision_model.encoder.layers.1.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
361 |
+
"model.vision_model.encoder.layers.1.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
362 |
+
"model.vision_model.encoder.layers.1.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
363 |
+
"model.vision_model.encoder.layers.1.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
364 |
+
"model.vision_model.encoder.layers.1.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
365 |
+
"model.vision_model.encoder.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
366 |
+
"model.vision_model.encoder.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
367 |
+
"model.vision_model.encoder.layers.1.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
368 |
+
"model.vision_model.encoder.layers.1.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
369 |
+
"model.vision_model.encoder.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
370 |
+
"model.vision_model.encoder.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
371 |
+
"model.vision_model.encoder.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
372 |
+
"model.vision_model.encoder.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
373 |
+
"model.vision_model.encoder.layers.10.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
374 |
+
"model.vision_model.encoder.layers.10.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
375 |
+
"model.vision_model.encoder.layers.10.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
376 |
+
"model.vision_model.encoder.layers.10.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
377 |
+
"model.vision_model.encoder.layers.10.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
378 |
+
"model.vision_model.encoder.layers.10.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
379 |
+
"model.vision_model.encoder.layers.10.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
380 |
+
"model.vision_model.encoder.layers.10.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
381 |
+
"model.vision_model.encoder.layers.10.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
382 |
+
"model.vision_model.encoder.layers.10.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
383 |
+
"model.vision_model.encoder.layers.10.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
384 |
+
"model.vision_model.encoder.layers.10.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
385 |
+
"model.vision_model.encoder.layers.10.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
386 |
+
"model.vision_model.encoder.layers.10.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
387 |
+
"model.vision_model.encoder.layers.10.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
388 |
+
"model.vision_model.encoder.layers.10.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
389 |
+
"model.vision_model.encoder.layers.11.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
390 |
+
"model.vision_model.encoder.layers.11.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
391 |
+
"model.vision_model.encoder.layers.11.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
392 |
+
"model.vision_model.encoder.layers.11.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
393 |
+
"model.vision_model.encoder.layers.11.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
394 |
+
"model.vision_model.encoder.layers.11.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
395 |
+
"model.vision_model.encoder.layers.11.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
396 |
+
"model.vision_model.encoder.layers.11.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
397 |
+
"model.vision_model.encoder.layers.11.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
398 |
+
"model.vision_model.encoder.layers.11.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
399 |
+
"model.vision_model.encoder.layers.11.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
400 |
+
"model.vision_model.encoder.layers.11.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
401 |
+
"model.vision_model.encoder.layers.11.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
402 |
+
"model.vision_model.encoder.layers.11.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
403 |
+
"model.vision_model.encoder.layers.11.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
404 |
+
"model.vision_model.encoder.layers.11.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
405 |
+
"model.vision_model.encoder.layers.12.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
406 |
+
"model.vision_model.encoder.layers.12.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
407 |
+
"model.vision_model.encoder.layers.12.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
408 |
+
"model.vision_model.encoder.layers.12.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
409 |
+
"model.vision_model.encoder.layers.12.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
410 |
+
"model.vision_model.encoder.layers.12.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
411 |
+
"model.vision_model.encoder.layers.12.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
412 |
+
"model.vision_model.encoder.layers.12.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
413 |
+
"model.vision_model.encoder.layers.12.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
414 |
+
"model.vision_model.encoder.layers.12.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
415 |
+
"model.vision_model.encoder.layers.12.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
416 |
+
"model.vision_model.encoder.layers.12.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
417 |
+
"model.vision_model.encoder.layers.12.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
418 |
+
"model.vision_model.encoder.layers.12.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
419 |
+
"model.vision_model.encoder.layers.12.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
420 |
+
"model.vision_model.encoder.layers.12.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
421 |
+
"model.vision_model.encoder.layers.13.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
422 |
+
"model.vision_model.encoder.layers.13.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
423 |
+
"model.vision_model.encoder.layers.13.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
424 |
+
"model.vision_model.encoder.layers.13.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
425 |
+
"model.vision_model.encoder.layers.13.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
426 |
+
"model.vision_model.encoder.layers.13.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
427 |
+
"model.vision_model.encoder.layers.13.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
428 |
+
"model.vision_model.encoder.layers.13.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
429 |
+
"model.vision_model.encoder.layers.13.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
430 |
+
"model.vision_model.encoder.layers.13.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
431 |
+
"model.vision_model.encoder.layers.13.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
432 |
+
"model.vision_model.encoder.layers.13.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
433 |
+
"model.vision_model.encoder.layers.13.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
434 |
+
"model.vision_model.encoder.layers.13.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
435 |
+
"model.vision_model.encoder.layers.13.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
436 |
+
"model.vision_model.encoder.layers.13.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
437 |
+
"model.vision_model.encoder.layers.14.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
438 |
+
"model.vision_model.encoder.layers.14.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
439 |
+
"model.vision_model.encoder.layers.14.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
440 |
+
"model.vision_model.encoder.layers.14.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
441 |
+
"model.vision_model.encoder.layers.14.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
442 |
+
"model.vision_model.encoder.layers.14.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
443 |
+
"model.vision_model.encoder.layers.14.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
444 |
+
"model.vision_model.encoder.layers.14.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
445 |
+
"model.vision_model.encoder.layers.14.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
446 |
+
"model.vision_model.encoder.layers.14.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
447 |
+
"model.vision_model.encoder.layers.14.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
448 |
+
"model.vision_model.encoder.layers.14.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
449 |
+
"model.vision_model.encoder.layers.14.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
450 |
+
"model.vision_model.encoder.layers.14.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
451 |
+
"model.vision_model.encoder.layers.14.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
452 |
+
"model.vision_model.encoder.layers.14.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
453 |
+
"model.vision_model.encoder.layers.15.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
454 |
+
"model.vision_model.encoder.layers.15.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
455 |
+
"model.vision_model.encoder.layers.15.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
456 |
+
"model.vision_model.encoder.layers.15.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
457 |
+
"model.vision_model.encoder.layers.15.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
458 |
+
"model.vision_model.encoder.layers.15.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
459 |
+
"model.vision_model.encoder.layers.15.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
460 |
+
"model.vision_model.encoder.layers.15.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
461 |
+
"model.vision_model.encoder.layers.15.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
462 |
+
"model.vision_model.encoder.layers.15.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
463 |
+
"model.vision_model.encoder.layers.15.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
464 |
+
"model.vision_model.encoder.layers.15.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
465 |
+
"model.vision_model.encoder.layers.15.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
466 |
+
"model.vision_model.encoder.layers.15.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
467 |
+
"model.vision_model.encoder.layers.15.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
468 |
+
"model.vision_model.encoder.layers.15.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
469 |
+
"model.vision_model.encoder.layers.16.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
470 |
+
"model.vision_model.encoder.layers.16.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
471 |
+
"model.vision_model.encoder.layers.16.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
472 |
+
"model.vision_model.encoder.layers.16.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
473 |
+
"model.vision_model.encoder.layers.16.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
474 |
+
"model.vision_model.encoder.layers.16.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
475 |
+
"model.vision_model.encoder.layers.16.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
476 |
+
"model.vision_model.encoder.layers.16.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
477 |
+
"model.vision_model.encoder.layers.16.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
478 |
+
"model.vision_model.encoder.layers.16.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
479 |
+
"model.vision_model.encoder.layers.16.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
480 |
+
"model.vision_model.encoder.layers.16.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
481 |
+
"model.vision_model.encoder.layers.16.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
482 |
+
"model.vision_model.encoder.layers.16.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
483 |
+
"model.vision_model.encoder.layers.16.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
484 |
+
"model.vision_model.encoder.layers.16.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
485 |
+
"model.vision_model.encoder.layers.17.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
486 |
+
"model.vision_model.encoder.layers.17.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
487 |
+
"model.vision_model.encoder.layers.17.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
488 |
+
"model.vision_model.encoder.layers.17.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
489 |
+
"model.vision_model.encoder.layers.17.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
490 |
+
"model.vision_model.encoder.layers.17.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
491 |
+
"model.vision_model.encoder.layers.17.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
492 |
+
"model.vision_model.encoder.layers.17.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
493 |
+
"model.vision_model.encoder.layers.17.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
494 |
+
"model.vision_model.encoder.layers.17.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
495 |
+
"model.vision_model.encoder.layers.17.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
496 |
+
"model.vision_model.encoder.layers.17.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
497 |
+
"model.vision_model.encoder.layers.17.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
498 |
+
"model.vision_model.encoder.layers.17.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
499 |
+
"model.vision_model.encoder.layers.17.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
500 |
+
"model.vision_model.encoder.layers.17.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
501 |
+
"model.vision_model.encoder.layers.18.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
502 |
+
"model.vision_model.encoder.layers.18.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
503 |
+
"model.vision_model.encoder.layers.18.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
504 |
+
"model.vision_model.encoder.layers.18.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
505 |
+
"model.vision_model.encoder.layers.18.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
506 |
+
"model.vision_model.encoder.layers.18.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
507 |
+
"model.vision_model.encoder.layers.18.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
508 |
+
"model.vision_model.encoder.layers.18.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
509 |
+
"model.vision_model.encoder.layers.18.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
510 |
+
"model.vision_model.encoder.layers.18.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
511 |
+
"model.vision_model.encoder.layers.18.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
512 |
+
"model.vision_model.encoder.layers.18.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
513 |
+
"model.vision_model.encoder.layers.18.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
514 |
+
"model.vision_model.encoder.layers.18.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
515 |
+
"model.vision_model.encoder.layers.18.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
516 |
+
"model.vision_model.encoder.layers.18.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
517 |
+
"model.vision_model.encoder.layers.19.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
518 |
+
"model.vision_model.encoder.layers.19.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
519 |
+
"model.vision_model.encoder.layers.19.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
520 |
+
"model.vision_model.encoder.layers.19.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
521 |
+
"model.vision_model.encoder.layers.19.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
522 |
+
"model.vision_model.encoder.layers.19.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
523 |
+
"model.vision_model.encoder.layers.19.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
524 |
+
"model.vision_model.encoder.layers.19.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
525 |
+
"model.vision_model.encoder.layers.19.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
526 |
+
"model.vision_model.encoder.layers.19.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
527 |
+
"model.vision_model.encoder.layers.19.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
528 |
+
"model.vision_model.encoder.layers.19.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
529 |
+
"model.vision_model.encoder.layers.19.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
530 |
+
"model.vision_model.encoder.layers.19.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
531 |
+
"model.vision_model.encoder.layers.19.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
532 |
+
"model.vision_model.encoder.layers.19.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
533 |
+
"model.vision_model.encoder.layers.2.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
534 |
+
"model.vision_model.encoder.layers.2.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
535 |
+
"model.vision_model.encoder.layers.2.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
536 |
+
"model.vision_model.encoder.layers.2.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
537 |
+
"model.vision_model.encoder.layers.2.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
538 |
+
"model.vision_model.encoder.layers.2.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
539 |
+
"model.vision_model.encoder.layers.2.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
540 |
+
"model.vision_model.encoder.layers.2.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
541 |
+
"model.vision_model.encoder.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
542 |
+
"model.vision_model.encoder.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
543 |
+
"model.vision_model.encoder.layers.2.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
544 |
+
"model.vision_model.encoder.layers.2.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
545 |
+
"model.vision_model.encoder.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
546 |
+
"model.vision_model.encoder.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
547 |
+
"model.vision_model.encoder.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
548 |
+
"model.vision_model.encoder.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
549 |
+
"model.vision_model.encoder.layers.20.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
550 |
+
"model.vision_model.encoder.layers.20.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
551 |
+
"model.vision_model.encoder.layers.20.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
552 |
+
"model.vision_model.encoder.layers.20.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
553 |
+
"model.vision_model.encoder.layers.20.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
554 |
+
"model.vision_model.encoder.layers.20.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
555 |
+
"model.vision_model.encoder.layers.20.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
556 |
+
"model.vision_model.encoder.layers.20.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
557 |
+
"model.vision_model.encoder.layers.20.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
558 |
+
"model.vision_model.encoder.layers.20.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
559 |
+
"model.vision_model.encoder.layers.20.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
560 |
+
"model.vision_model.encoder.layers.20.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
561 |
+
"model.vision_model.encoder.layers.20.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
562 |
+
"model.vision_model.encoder.layers.20.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
563 |
+
"model.vision_model.encoder.layers.20.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
564 |
+
"model.vision_model.encoder.layers.20.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
565 |
+
"model.vision_model.encoder.layers.21.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
566 |
+
"model.vision_model.encoder.layers.21.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
567 |
+
"model.vision_model.encoder.layers.21.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
568 |
+
"model.vision_model.encoder.layers.21.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
569 |
+
"model.vision_model.encoder.layers.21.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
570 |
+
"model.vision_model.encoder.layers.21.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
571 |
+
"model.vision_model.encoder.layers.21.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
572 |
+
"model.vision_model.encoder.layers.21.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
573 |
+
"model.vision_model.encoder.layers.21.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
574 |
+
"model.vision_model.encoder.layers.21.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
575 |
+
"model.vision_model.encoder.layers.21.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
576 |
+
"model.vision_model.encoder.layers.21.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
577 |
+
"model.vision_model.encoder.layers.21.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
578 |
+
"model.vision_model.encoder.layers.21.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
579 |
+
"model.vision_model.encoder.layers.21.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
580 |
+
"model.vision_model.encoder.layers.21.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
581 |
+
"model.vision_model.encoder.layers.22.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
582 |
+
"model.vision_model.encoder.layers.22.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
583 |
+
"model.vision_model.encoder.layers.22.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
584 |
+
"model.vision_model.encoder.layers.22.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
585 |
+
"model.vision_model.encoder.layers.22.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
586 |
+
"model.vision_model.encoder.layers.22.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
587 |
+
"model.vision_model.encoder.layers.22.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
588 |
+
"model.vision_model.encoder.layers.22.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
589 |
+
"model.vision_model.encoder.layers.22.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
590 |
+
"model.vision_model.encoder.layers.22.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
591 |
+
"model.vision_model.encoder.layers.22.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
592 |
+
"model.vision_model.encoder.layers.22.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
593 |
+
"model.vision_model.encoder.layers.22.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
594 |
+
"model.vision_model.encoder.layers.22.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
595 |
+
"model.vision_model.encoder.layers.22.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
596 |
+
"model.vision_model.encoder.layers.22.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
597 |
+
"model.vision_model.encoder.layers.23.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
598 |
+
"model.vision_model.encoder.layers.23.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
599 |
+
"model.vision_model.encoder.layers.23.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
600 |
+
"model.vision_model.encoder.layers.23.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
601 |
+
"model.vision_model.encoder.layers.23.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
602 |
+
"model.vision_model.encoder.layers.23.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
603 |
+
"model.vision_model.encoder.layers.23.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
604 |
+
"model.vision_model.encoder.layers.23.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
605 |
+
"model.vision_model.encoder.layers.23.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
606 |
+
"model.vision_model.encoder.layers.23.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
607 |
+
"model.vision_model.encoder.layers.23.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
608 |
+
"model.vision_model.encoder.layers.23.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
609 |
+
"model.vision_model.encoder.layers.23.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
610 |
+
"model.vision_model.encoder.layers.23.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
611 |
+
"model.vision_model.encoder.layers.23.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
612 |
+
"model.vision_model.encoder.layers.23.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
613 |
+
"model.vision_model.encoder.layers.24.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
614 |
+
"model.vision_model.encoder.layers.24.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
615 |
+
"model.vision_model.encoder.layers.24.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
616 |
+
"model.vision_model.encoder.layers.24.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
617 |
+
"model.vision_model.encoder.layers.24.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
618 |
+
"model.vision_model.encoder.layers.24.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
619 |
+
"model.vision_model.encoder.layers.24.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
620 |
+
"model.vision_model.encoder.layers.24.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
621 |
+
"model.vision_model.encoder.layers.24.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
622 |
+
"model.vision_model.encoder.layers.24.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
623 |
+
"model.vision_model.encoder.layers.24.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
624 |
+
"model.vision_model.encoder.layers.24.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
625 |
+
"model.vision_model.encoder.layers.24.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
626 |
+
"model.vision_model.encoder.layers.24.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
627 |
+
"model.vision_model.encoder.layers.24.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
628 |
+
"model.vision_model.encoder.layers.24.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
629 |
+
"model.vision_model.encoder.layers.25.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
630 |
+
"model.vision_model.encoder.layers.25.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
631 |
+
"model.vision_model.encoder.layers.25.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
632 |
+
"model.vision_model.encoder.layers.25.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
633 |
+
"model.vision_model.encoder.layers.25.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
634 |
+
"model.vision_model.encoder.layers.25.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
635 |
+
"model.vision_model.encoder.layers.25.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
636 |
+
"model.vision_model.encoder.layers.25.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
637 |
+
"model.vision_model.encoder.layers.25.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
638 |
+
"model.vision_model.encoder.layers.25.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
639 |
+
"model.vision_model.encoder.layers.25.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
640 |
+
"model.vision_model.encoder.layers.25.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
641 |
+
"model.vision_model.encoder.layers.25.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
642 |
+
"model.vision_model.encoder.layers.25.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
643 |
+
"model.vision_model.encoder.layers.25.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
644 |
+
"model.vision_model.encoder.layers.25.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
645 |
+
"model.vision_model.encoder.layers.26.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
646 |
+
"model.vision_model.encoder.layers.26.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
647 |
+
"model.vision_model.encoder.layers.26.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
648 |
+
"model.vision_model.encoder.layers.26.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
649 |
+
"model.vision_model.encoder.layers.26.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
650 |
+
"model.vision_model.encoder.layers.26.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
651 |
+
"model.vision_model.encoder.layers.26.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
652 |
+
"model.vision_model.encoder.layers.26.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
653 |
+
"model.vision_model.encoder.layers.26.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
654 |
+
"model.vision_model.encoder.layers.26.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
655 |
+
"model.vision_model.encoder.layers.26.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
656 |
+
"model.vision_model.encoder.layers.26.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
657 |
+
"model.vision_model.encoder.layers.26.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
658 |
+
"model.vision_model.encoder.layers.26.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
659 |
+
"model.vision_model.encoder.layers.26.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
660 |
+
"model.vision_model.encoder.layers.26.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
661 |
+
"model.vision_model.encoder.layers.3.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
662 |
+
"model.vision_model.encoder.layers.3.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
663 |
+
"model.vision_model.encoder.layers.3.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
664 |
+
"model.vision_model.encoder.layers.3.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
665 |
+
"model.vision_model.encoder.layers.3.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
666 |
+
"model.vision_model.encoder.layers.3.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
667 |
+
"model.vision_model.encoder.layers.3.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
668 |
+
"model.vision_model.encoder.layers.3.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
669 |
+
"model.vision_model.encoder.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
670 |
+
"model.vision_model.encoder.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
671 |
+
"model.vision_model.encoder.layers.3.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
672 |
+
"model.vision_model.encoder.layers.3.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
673 |
+
"model.vision_model.encoder.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
674 |
+
"model.vision_model.encoder.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
675 |
+
"model.vision_model.encoder.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
676 |
+
"model.vision_model.encoder.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
677 |
+
"model.vision_model.encoder.layers.4.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
678 |
+
"model.vision_model.encoder.layers.4.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
679 |
+
"model.vision_model.encoder.layers.4.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
680 |
+
"model.vision_model.encoder.layers.4.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
681 |
+
"model.vision_model.encoder.layers.4.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
682 |
+
"model.vision_model.encoder.layers.4.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
683 |
+
"model.vision_model.encoder.layers.4.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
684 |
+
"model.vision_model.encoder.layers.4.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
685 |
+
"model.vision_model.encoder.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
686 |
+
"model.vision_model.encoder.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
687 |
+
"model.vision_model.encoder.layers.4.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
688 |
+
"model.vision_model.encoder.layers.4.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
689 |
+
"model.vision_model.encoder.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
690 |
+
"model.vision_model.encoder.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
691 |
+
"model.vision_model.encoder.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
692 |
+
"model.vision_model.encoder.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
693 |
+
"model.vision_model.encoder.layers.5.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
694 |
+
"model.vision_model.encoder.layers.5.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
695 |
+
"model.vision_model.encoder.layers.5.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
696 |
+
"model.vision_model.encoder.layers.5.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
697 |
+
"model.vision_model.encoder.layers.5.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
698 |
+
"model.vision_model.encoder.layers.5.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
699 |
+
"model.vision_model.encoder.layers.5.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
700 |
+
"model.vision_model.encoder.layers.5.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
701 |
+
"model.vision_model.encoder.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
702 |
+
"model.vision_model.encoder.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
703 |
+
"model.vision_model.encoder.layers.5.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
704 |
+
"model.vision_model.encoder.layers.5.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
705 |
+
"model.vision_model.encoder.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
706 |
+
"model.vision_model.encoder.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
707 |
+
"model.vision_model.encoder.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
708 |
+
"model.vision_model.encoder.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
709 |
+
"model.vision_model.encoder.layers.6.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
710 |
+
"model.vision_model.encoder.layers.6.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
711 |
+
"model.vision_model.encoder.layers.6.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
712 |
+
"model.vision_model.encoder.layers.6.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
713 |
+
"model.vision_model.encoder.layers.6.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
714 |
+
"model.vision_model.encoder.layers.6.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
715 |
+
"model.vision_model.encoder.layers.6.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
716 |
+
"model.vision_model.encoder.layers.6.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
717 |
+
"model.vision_model.encoder.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
718 |
+
"model.vision_model.encoder.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
719 |
+
"model.vision_model.encoder.layers.6.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
720 |
+
"model.vision_model.encoder.layers.6.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
721 |
+
"model.vision_model.encoder.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
722 |
+
"model.vision_model.encoder.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
723 |
+
"model.vision_model.encoder.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
724 |
+
"model.vision_model.encoder.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
725 |
+
"model.vision_model.encoder.layers.7.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
726 |
+
"model.vision_model.encoder.layers.7.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
727 |
+
"model.vision_model.encoder.layers.7.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
728 |
+
"model.vision_model.encoder.layers.7.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
729 |
+
"model.vision_model.encoder.layers.7.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
730 |
+
"model.vision_model.encoder.layers.7.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
731 |
+
"model.vision_model.encoder.layers.7.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
732 |
+
"model.vision_model.encoder.layers.7.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
733 |
+
"model.vision_model.encoder.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
734 |
+
"model.vision_model.encoder.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
735 |
+
"model.vision_model.encoder.layers.7.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
736 |
+
"model.vision_model.encoder.layers.7.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
737 |
+
"model.vision_model.encoder.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
738 |
+
"model.vision_model.encoder.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
739 |
+
"model.vision_model.encoder.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
740 |
+
"model.vision_model.encoder.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
741 |
+
"model.vision_model.encoder.layers.8.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
742 |
+
"model.vision_model.encoder.layers.8.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
743 |
+
"model.vision_model.encoder.layers.8.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
744 |
+
"model.vision_model.encoder.layers.8.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
745 |
+
"model.vision_model.encoder.layers.8.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
746 |
+
"model.vision_model.encoder.layers.8.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
747 |
+
"model.vision_model.encoder.layers.8.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
748 |
+
"model.vision_model.encoder.layers.8.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
749 |
+
"model.vision_model.encoder.layers.8.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
750 |
+
"model.vision_model.encoder.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
751 |
+
"model.vision_model.encoder.layers.8.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
752 |
+
"model.vision_model.encoder.layers.8.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
753 |
+
"model.vision_model.encoder.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
754 |
+
"model.vision_model.encoder.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
755 |
+
"model.vision_model.encoder.layers.8.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
756 |
+
"model.vision_model.encoder.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
757 |
+
"model.vision_model.encoder.layers.9.layer_norm1.bias": "model-00001-of-00004.safetensors",
|
758 |
+
"model.vision_model.encoder.layers.9.layer_norm1.weight": "model-00001-of-00004.safetensors",
|
759 |
+
"model.vision_model.encoder.layers.9.layer_norm2.bias": "model-00001-of-00004.safetensors",
|
760 |
+
"model.vision_model.encoder.layers.9.layer_norm2.weight": "model-00001-of-00004.safetensors",
|
761 |
+
"model.vision_model.encoder.layers.9.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
762 |
+
"model.vision_model.encoder.layers.9.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
763 |
+
"model.vision_model.encoder.layers.9.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
764 |
+
"model.vision_model.encoder.layers.9.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
765 |
+
"model.vision_model.encoder.layers.9.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
766 |
+
"model.vision_model.encoder.layers.9.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
767 |
+
"model.vision_model.encoder.layers.9.self_attn.out_proj.bias": "model-00001-of-00004.safetensors",
|
768 |
+
"model.vision_model.encoder.layers.9.self_attn.out_proj.weight": "model-00001-of-00004.safetensors",
|
769 |
+
"model.vision_model.encoder.layers.9.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
770 |
+
"model.vision_model.encoder.layers.9.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
771 |
+
"model.vision_model.encoder.layers.9.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
772 |
+
"model.vision_model.encoder.layers.9.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
773 |
+
"model.vision_model.post_layernorm.bias": "model-00001-of-00004.safetensors",
|
774 |
+
"model.vision_model.post_layernorm.weight": "model-00001-of-00004.safetensors"
|
775 |
+
}
|
776 |
+
}
|
modeling_idefics2.py
ADDED
@@ -0,0 +1,1542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch Idefics2 model."""
|
21 |
+
from dataclasses import dataclass
|
22 |
+
import inspect
|
23 |
+
import math
|
24 |
+
import warnings
|
25 |
+
from typing import List, Optional, Tuple, Union
|
26 |
+
|
27 |
+
import torch
|
28 |
+
import torch.nn.functional as F
|
29 |
+
import torch.utils.checkpoint
|
30 |
+
from torch import nn
|
31 |
+
from torch.nn import CrossEntropyLoss
|
32 |
+
from transformers.activations import ACT2FN
|
33 |
+
from transformers.cache_utils import Cache, DynamicCache
|
34 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
35 |
+
from transformers.utils import (
|
36 |
+
add_start_docstrings,
|
37 |
+
add_start_docstrings_to_model_forward,
|
38 |
+
is_flash_attn_2_available,
|
39 |
+
is_flash_attn_greater_or_equal_2_10,
|
40 |
+
replace_return_docstrings,
|
41 |
+
)
|
42 |
+
|
43 |
+
from einops import rearrange, repeat
|
44 |
+
from transformers import PreTrainedModel
|
45 |
+
from transformers.utils import logging
|
46 |
+
from transformers.modeling_outputs import ModelOutput
|
47 |
+
|
48 |
+
from .configuration_idefics2 import Idefics2Config
|
49 |
+
from .vision import SiglipVisionTransformer
|
50 |
+
from .common import DecoupledEmbedding, DecoupledLinear, MLP, RMSNorm
|
51 |
+
from .perceiver import PerceiverResampler
|
52 |
+
|
53 |
+
|
54 |
+
if is_flash_attn_2_available():
|
55 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
56 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
57 |
+
|
58 |
+
_flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
|
59 |
+
|
60 |
+
logger = logging.get_logger(__name__)
|
61 |
+
|
62 |
+
_CONFIG_FOR_DOC = "Idefics2Config"
|
63 |
+
|
64 |
+
Idefics2_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
65 |
+
"HuggingFaceM4/idefics2"
|
66 |
+
]
|
67 |
+
|
68 |
+
@dataclass
|
69 |
+
class Idefics2BaseModelOutputWithPast(ModelOutput):
|
70 |
+
"""
|
71 |
+
Base class for Idefics2 model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
72 |
+
Args:
|
73 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
74 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
75 |
+
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
|
76 |
+
hidden_size)` is output.
|
77 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
78 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
79 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
|
80 |
+
`config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
|
81 |
+
encoder_sequence_length, embed_size_per_head)`.
|
82 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
|
83 |
+
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
|
84 |
+
input) to speed up sequential decoding.
|
85 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
86 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
87 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
88 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
89 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
90 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
91 |
+
sequence_length)`.
|
92 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
93 |
+
heads.
|
94 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
95 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
96 |
+
sequence_length, hidden_size)`.
|
97 |
+
image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
|
98 |
+
"""
|
99 |
+
|
100 |
+
last_hidden_state: torch.FloatTensor = None
|
101 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
102 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
103 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
104 |
+
image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
105 |
+
|
106 |
+
|
107 |
+
@dataclass
|
108 |
+
class Idefics2CausalLMOutputWithPast(ModelOutput):
|
109 |
+
"""
|
110 |
+
Base class for Idefics2 causal language model (or autoregressive) outputs.
|
111 |
+
Args:
|
112 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
113 |
+
Language modeling loss (for next-token prediction).
|
114 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
115 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
116 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
117 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
118 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
119 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
120 |
+
`past_key_values` input) to speed up sequential decoding.
|
121 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
122 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
123 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
124 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
125 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
126 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
127 |
+
sequence_length)`.
|
128 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
129 |
+
heads.
|
130 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
131 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
132 |
+
sequence_length, hidden_size)`.
|
133 |
+
image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
|
134 |
+
"""
|
135 |
+
|
136 |
+
loss: Optional[torch.FloatTensor] = None
|
137 |
+
logits: torch.FloatTensor = None
|
138 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None
|
139 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
140 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
141 |
+
image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
142 |
+
|
143 |
+
|
144 |
+
def expand_inputs_for_generation(
|
145 |
+
input_ids,
|
146 |
+
expand_size=1,
|
147 |
+
is_encoder_decoder=False,
|
148 |
+
attention_mask=None,
|
149 |
+
encoder_outputs=None,
|
150 |
+
**model_kwargs,
|
151 |
+
):
|
152 |
+
expanded_return_idx = (
|
153 |
+
torch.arange(input_ids.shape[0]).view(-1, 1).repeat(1, expand_size).view(-1).to(input_ids.device)
|
154 |
+
)
|
155 |
+
input_ids = input_ids.index_select(0, expanded_return_idx)
|
156 |
+
model_kwargs["pixel_values"] = model_kwargs.get("pixel_values", None)
|
157 |
+
model_kwargs["image_hidden_states"] = model_kwargs.get("image_hidden_states", None)
|
158 |
+
|
159 |
+
if "token_type_ids" in model_kwargs:
|
160 |
+
token_type_ids = model_kwargs["token_type_ids"]
|
161 |
+
model_kwargs["token_type_ids"] = token_type_ids.index_select(0, expanded_return_idx)
|
162 |
+
|
163 |
+
if attention_mask is not None:
|
164 |
+
model_kwargs["attention_mask"] = attention_mask.index_select(0, expanded_return_idx)
|
165 |
+
|
166 |
+
if model_kwargs["pixel_values"] is not None:
|
167 |
+
model_kwargs["pixel_values"] = model_kwargs["pixel_values"].index_select(0, expanded_return_idx)
|
168 |
+
|
169 |
+
elif model_kwargs["image_hidden_states"] is not None:
|
170 |
+
model_kwargs["image_hidden_states"] = model_kwargs["image_hidden_states"].index_select(0, expanded_return_idx)
|
171 |
+
|
172 |
+
return input_ids, model_kwargs
|
173 |
+
|
174 |
+
|
175 |
+
def update_model_kwargs_for_generation(outputs, model_kwargs):
|
176 |
+
# must have this key set to at least None
|
177 |
+
if "past_key_values" in outputs:
|
178 |
+
model_kwargs["past_key_values"] = outputs.past_key_values
|
179 |
+
else:
|
180 |
+
model_kwargs["past_key_values"] = None
|
181 |
+
|
182 |
+
# update token_type_ids with last value
|
183 |
+
if "token_type_ids" in model_kwargs:
|
184 |
+
token_type_ids = model_kwargs["token_type_ids"]
|
185 |
+
model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
|
186 |
+
|
187 |
+
# update attention masks
|
188 |
+
if "attention_mask" in model_kwargs:
|
189 |
+
attention_mask = model_kwargs["attention_mask"]
|
190 |
+
model_kwargs["attention_mask"] = torch.cat(
|
191 |
+
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
|
192 |
+
)
|
193 |
+
|
194 |
+
# Get the precomputed image_hidden_states
|
195 |
+
model_kwargs["image_hidden_states"] = outputs.image_hidden_states
|
196 |
+
|
197 |
+
return model_kwargs
|
198 |
+
|
199 |
+
|
200 |
+
def freeze_model(model, module_exceptions=[]):
|
201 |
+
mapping = {
|
202 |
+
"LayerNorm": nn.LayerNorm,
|
203 |
+
"Linear": nn.Linear,
|
204 |
+
"Embedding": nn.Embedding,
|
205 |
+
}
|
206 |
+
module_exceptions_mapped = [mapping[m] for m in module_exceptions]
|
207 |
+
for module in model.modules():
|
208 |
+
if module_exceptions and any([isinstance(module, t) for t in module_exceptions_mapped]):
|
209 |
+
module.requires_grad_(True) # Explicitly setting it to true to avoid any mistakes
|
210 |
+
else:
|
211 |
+
module.requires_grad_(False)
|
212 |
+
return model
|
213 |
+
|
214 |
+
|
215 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
216 |
+
def _get_unpad_data(attention_mask):
|
217 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
218 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
219 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
220 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
221 |
+
return (
|
222 |
+
indices,
|
223 |
+
cu_seqlens,
|
224 |
+
max_seqlen_in_batch,
|
225 |
+
)
|
226 |
+
|
227 |
+
|
228 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral
|
229 |
+
class MistralRotaryEmbedding(nn.Module):
|
230 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
231 |
+
super().__init__()
|
232 |
+
|
233 |
+
self.dim = dim
|
234 |
+
self.max_position_embeddings = max_position_embeddings
|
235 |
+
self.base = base
|
236 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
237 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
238 |
+
|
239 |
+
# Build here to make `torch.jit.trace` work.
|
240 |
+
self._set_cos_sin_cache(
|
241 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
242 |
+
)
|
243 |
+
|
244 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
245 |
+
self.max_seq_len_cached = seq_len
|
246 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
247 |
+
|
248 |
+
freqs = torch.outer(t, self.inv_freq)
|
249 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
250 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
251 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
252 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
253 |
+
|
254 |
+
def forward(self, x, seq_len=None):
|
255 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
256 |
+
if seq_len > self.max_seq_len_cached:
|
257 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
258 |
+
|
259 |
+
return (
|
260 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
261 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
262 |
+
)
|
263 |
+
|
264 |
+
|
265 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
266 |
+
def rotate_half(x):
|
267 |
+
"""Rotates half the hidden dims of the input."""
|
268 |
+
x1 = x[..., : x.shape[-1] // 2]
|
269 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
270 |
+
return torch.cat((-x2, x1), dim=-1)
|
271 |
+
|
272 |
+
|
273 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
274 |
+
# TODO @Arthur no longer copied from LLama after static cache
|
275 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
276 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
277 |
+
Args:
|
278 |
+
q (`torch.Tensor`): The query tensor.
|
279 |
+
k (`torch.Tensor`): The key tensor.
|
280 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
281 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
282 |
+
position_ids (`torch.Tensor`):
|
283 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
284 |
+
used to pass offsetted position ids when working with a KV-cache.
|
285 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
286 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
287 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
288 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
289 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
290 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
291 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
292 |
+
Returns:
|
293 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
294 |
+
"""
|
295 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
296 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
297 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
298 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
299 |
+
return q_embed, k_embed
|
300 |
+
|
301 |
+
|
302 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
303 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
304 |
+
"""
|
305 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
306 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
307 |
+
"""
|
308 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
309 |
+
if n_rep == 1:
|
310 |
+
return hidden_states
|
311 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
312 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
313 |
+
|
314 |
+
|
315 |
+
class MistralAttention(nn.Module):
|
316 |
+
"""
|
317 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
318 |
+
and "Generating Long Sequences with Sparse Transformers".
|
319 |
+
"""
|
320 |
+
|
321 |
+
def __init__(self, config: Idefics2Config, layer_idx: Optional[int] = None, qk_layer_norms: bool = False):
|
322 |
+
super().__init__()
|
323 |
+
self.config = config
|
324 |
+
self.layer_idx = layer_idx
|
325 |
+
if layer_idx is None:
|
326 |
+
logger.warning_once(
|
327 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
328 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
329 |
+
"when creating this class."
|
330 |
+
)
|
331 |
+
|
332 |
+
self.hidden_size = config.hidden_size
|
333 |
+
self.num_heads = config.num_attention_heads
|
334 |
+
self.head_dim = self.hidden_size // self.num_heads
|
335 |
+
self.num_key_value_heads = config.num_key_value_heads
|
336 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
337 |
+
self.max_position_embeddings = config.max_position_embeddings
|
338 |
+
self.rope_theta = config.rope_theta
|
339 |
+
self.is_causal = True
|
340 |
+
self.attention_dropout = config.attention_dropout
|
341 |
+
|
342 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
343 |
+
raise ValueError(
|
344 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
345 |
+
f" and `num_heads`: {self.num_heads})."
|
346 |
+
)
|
347 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
348 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
349 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
350 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
351 |
+
|
352 |
+
self.qk_layer_norms = qk_layer_norms
|
353 |
+
if self.qk_layer_norms:
|
354 |
+
self.q_layer_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
355 |
+
self.k_layer_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
356 |
+
|
357 |
+
self.rotary_emb = MistralRotaryEmbedding(
|
358 |
+
self.head_dim,
|
359 |
+
max_position_embeddings=self.max_position_embeddings,
|
360 |
+
base=self.rope_theta,
|
361 |
+
)
|
362 |
+
|
363 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
364 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
365 |
+
|
366 |
+
def forward(
|
367 |
+
self,
|
368 |
+
hidden_states: torch.Tensor,
|
369 |
+
attention_mask: Optional[torch.Tensor] = None,
|
370 |
+
position_ids: Optional[torch.LongTensor] = None,
|
371 |
+
past_key_value: Optional[Cache] = None,
|
372 |
+
output_attentions: bool = False,
|
373 |
+
use_cache: bool = False,
|
374 |
+
**kwargs,
|
375 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
376 |
+
if "padding_mask" in kwargs:
|
377 |
+
warnings.warn(
|
378 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
379 |
+
)
|
380 |
+
bsz, q_len, _ = hidden_states.size()
|
381 |
+
|
382 |
+
query_states = self.q_proj(hidden_states)
|
383 |
+
key_states = self.k_proj(hidden_states)
|
384 |
+
value_states = self.v_proj(hidden_states)
|
385 |
+
|
386 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
387 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
388 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
389 |
+
|
390 |
+
kv_seq_len = key_states.shape[-2]
|
391 |
+
if past_key_value is not None:
|
392 |
+
if self.layer_idx is None:
|
393 |
+
raise ValueError(
|
394 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
395 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
396 |
+
"with a layer index."
|
397 |
+
)
|
398 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
399 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
400 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
401 |
+
|
402 |
+
if past_key_value is not None:
|
403 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
404 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
405 |
+
|
406 |
+
if self.qk_layer_norms:
|
407 |
+
query_states = self.q_layer_norm(query_states)
|
408 |
+
key_states = self.k_layer_norm(key_states)
|
409 |
+
|
410 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
411 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
412 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
413 |
+
|
414 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
415 |
+
|
416 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
417 |
+
raise ValueError(
|
418 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
419 |
+
f" {attn_weights.size()}"
|
420 |
+
)
|
421 |
+
|
422 |
+
if attention_mask is not None:
|
423 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
424 |
+
raise ValueError(
|
425 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
426 |
+
)
|
427 |
+
|
428 |
+
attn_weights = attn_weights + attention_mask
|
429 |
+
|
430 |
+
# upcast attention to fp32
|
431 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
432 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
433 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
434 |
+
|
435 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
436 |
+
raise ValueError(
|
437 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
438 |
+
f" {attn_output.size()}"
|
439 |
+
)
|
440 |
+
|
441 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
442 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
443 |
+
|
444 |
+
attn_output = self.o_proj(attn_output)
|
445 |
+
|
446 |
+
if not output_attentions:
|
447 |
+
attn_weights = None
|
448 |
+
|
449 |
+
return attn_output, attn_weights, past_key_value
|
450 |
+
|
451 |
+
|
452 |
+
class MistralFlashAttention2(MistralAttention):
|
453 |
+
"""
|
454 |
+
Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays
|
455 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
456 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
457 |
+
"""
|
458 |
+
|
459 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
460 |
+
def __init__(self, *args, **kwargs):
|
461 |
+
super().__init__(*args, **kwargs)
|
462 |
+
|
463 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
464 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
465 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
466 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
467 |
+
|
468 |
+
def forward(
|
469 |
+
self,
|
470 |
+
hidden_states: torch.Tensor,
|
471 |
+
attention_mask: Optional[torch.Tensor] = None,
|
472 |
+
position_ids: Optional[torch.LongTensor] = None,
|
473 |
+
past_key_value: Optional[Cache] = None,
|
474 |
+
output_attentions: bool = False,
|
475 |
+
use_cache: bool = False,
|
476 |
+
**kwargs,
|
477 |
+
):
|
478 |
+
if "padding_mask" in kwargs:
|
479 |
+
warnings.warn(
|
480 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
481 |
+
)
|
482 |
+
|
483 |
+
# overwrite attention_mask with padding_mask
|
484 |
+
attention_mask = kwargs.pop("padding_mask")
|
485 |
+
bsz, q_len, _ = hidden_states.size()
|
486 |
+
|
487 |
+
query_states = self.q_proj(hidden_states)
|
488 |
+
key_states = self.k_proj(hidden_states)
|
489 |
+
value_states = self.v_proj(hidden_states)
|
490 |
+
|
491 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
492 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
493 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
494 |
+
|
495 |
+
kv_seq_len = key_states.shape[-2]
|
496 |
+
if past_key_value is not None:
|
497 |
+
if self.layer_idx is None:
|
498 |
+
raise ValueError(
|
499 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
500 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
501 |
+
"with a layer index."
|
502 |
+
)
|
503 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
504 |
+
|
505 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
506 |
+
rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
|
507 |
+
cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
508 |
+
|
509 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
510 |
+
|
511 |
+
use_sliding_windows = (
|
512 |
+
_flash_supports_window_size
|
513 |
+
and getattr(self.config, "sliding_window", None) is not None
|
514 |
+
and kv_seq_len > self.config.sliding_window
|
515 |
+
)
|
516 |
+
|
517 |
+
if not _flash_supports_window_size:
|
518 |
+
logger.warning_once(
|
519 |
+
"The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
520 |
+
" make sure to upgrade flash-attn library."
|
521 |
+
)
|
522 |
+
|
523 |
+
if past_key_value is not None:
|
524 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
525 |
+
cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
526 |
+
if (
|
527 |
+
getattr(self.config, "sliding_window", None) is not None
|
528 |
+
and kv_seq_len > self.config.sliding_window
|
529 |
+
and cache_has_contents
|
530 |
+
):
|
531 |
+
slicing_tokens = 1 - self.config.sliding_window
|
532 |
+
|
533 |
+
past_key = past_key_value[self.layer_idx][0]
|
534 |
+
past_value = past_key_value[self.layer_idx][1]
|
535 |
+
|
536 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
537 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
538 |
+
|
539 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
540 |
+
raise ValueError(
|
541 |
+
f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
542 |
+
f" {past_key.shape}"
|
543 |
+
)
|
544 |
+
|
545 |
+
if attention_mask is not None:
|
546 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
547 |
+
attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
548 |
+
|
549 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
550 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
551 |
+
|
552 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
553 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
554 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
555 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
556 |
+
|
557 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
558 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
559 |
+
# cast them back in float16 just to be sure everything works as expected.
|
560 |
+
input_dtype = query_states.dtype
|
561 |
+
if input_dtype == torch.float32:
|
562 |
+
if torch.is_autocast_enabled():
|
563 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
564 |
+
# Handle the case where the model is quantized
|
565 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
566 |
+
target_dtype = self.config._pre_quantization_dtype
|
567 |
+
else:
|
568 |
+
target_dtype = self.q_proj.weight.dtype
|
569 |
+
|
570 |
+
logger.warning_once(
|
571 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
572 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
573 |
+
f" {target_dtype}."
|
574 |
+
)
|
575 |
+
|
576 |
+
query_states = query_states.to(target_dtype)
|
577 |
+
key_states = key_states.to(target_dtype)
|
578 |
+
value_states = value_states.to(target_dtype)
|
579 |
+
|
580 |
+
# Reashape to the expected shape for Flash Attention
|
581 |
+
query_states = query_states.transpose(1, 2)
|
582 |
+
key_states = key_states.transpose(1, 2)
|
583 |
+
value_states = value_states.transpose(1, 2)
|
584 |
+
|
585 |
+
attn_output = self._flash_attention_forward(
|
586 |
+
query_states,
|
587 |
+
key_states,
|
588 |
+
value_states,
|
589 |
+
attention_mask,
|
590 |
+
q_len,
|
591 |
+
dropout=dropout_rate,
|
592 |
+
use_sliding_windows=use_sliding_windows,
|
593 |
+
)
|
594 |
+
|
595 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
596 |
+
attn_output = self.o_proj(attn_output)
|
597 |
+
|
598 |
+
if not output_attentions:
|
599 |
+
attn_weights = None
|
600 |
+
|
601 |
+
return attn_output, attn_weights, past_key_value
|
602 |
+
|
603 |
+
def _flash_attention_forward(
|
604 |
+
self,
|
605 |
+
query_states,
|
606 |
+
key_states,
|
607 |
+
value_states,
|
608 |
+
attention_mask,
|
609 |
+
query_length,
|
610 |
+
dropout=0.0,
|
611 |
+
softmax_scale=None,
|
612 |
+
use_sliding_windows=False,
|
613 |
+
):
|
614 |
+
"""
|
615 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
616 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
617 |
+
Args:
|
618 |
+
query_states (`torch.Tensor`):
|
619 |
+
Input query states to be passed to Flash Attention API
|
620 |
+
key_states (`torch.Tensor`):
|
621 |
+
Input key states to be passed to Flash Attention API
|
622 |
+
value_states (`torch.Tensor`):
|
623 |
+
Input value states to be passed to Flash Attention API
|
624 |
+
attention_mask (`torch.Tensor`):
|
625 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
626 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
627 |
+
dropout (`int`, *optional*):
|
628 |
+
Attention dropout
|
629 |
+
softmax_scale (`float`, *optional*):
|
630 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
631 |
+
use_sliding_windows (`bool`, *optional*):
|
632 |
+
Whether to activate sliding window attention.
|
633 |
+
"""
|
634 |
+
if not self._flash_attn_uses_top_left_mask:
|
635 |
+
causal = self.is_causal
|
636 |
+
else:
|
637 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
638 |
+
causal = self.is_causal and query_length != 1
|
639 |
+
|
640 |
+
# Contains at least one padding token in the sequence
|
641 |
+
if attention_mask is not None:
|
642 |
+
batch_size = query_states.shape[0]
|
643 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
644 |
+
query_states, key_states, value_states, attention_mask, query_length
|
645 |
+
)
|
646 |
+
|
647 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
648 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
649 |
+
|
650 |
+
if not use_sliding_windows:
|
651 |
+
attn_output_unpad = flash_attn_varlen_func(
|
652 |
+
query_states,
|
653 |
+
key_states,
|
654 |
+
value_states,
|
655 |
+
cu_seqlens_q=cu_seqlens_q,
|
656 |
+
cu_seqlens_k=cu_seqlens_k,
|
657 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
658 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
659 |
+
dropout_p=dropout,
|
660 |
+
softmax_scale=softmax_scale,
|
661 |
+
causal=causal,
|
662 |
+
)
|
663 |
+
else:
|
664 |
+
attn_output_unpad = flash_attn_varlen_func(
|
665 |
+
query_states,
|
666 |
+
key_states,
|
667 |
+
value_states,
|
668 |
+
cu_seqlens_q=cu_seqlens_q,
|
669 |
+
cu_seqlens_k=cu_seqlens_k,
|
670 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
671 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
672 |
+
dropout_p=dropout,
|
673 |
+
softmax_scale=softmax_scale,
|
674 |
+
causal=causal,
|
675 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
676 |
+
)
|
677 |
+
|
678 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
679 |
+
else:
|
680 |
+
if not use_sliding_windows:
|
681 |
+
attn_output = flash_attn_func(
|
682 |
+
query_states,
|
683 |
+
key_states,
|
684 |
+
value_states,
|
685 |
+
dropout,
|
686 |
+
softmax_scale=softmax_scale,
|
687 |
+
causal=causal,
|
688 |
+
)
|
689 |
+
else:
|
690 |
+
attn_output = flash_attn_func(
|
691 |
+
query_states,
|
692 |
+
key_states,
|
693 |
+
value_states,
|
694 |
+
dropout,
|
695 |
+
softmax_scale=softmax_scale,
|
696 |
+
causal=causal,
|
697 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
698 |
+
)
|
699 |
+
|
700 |
+
return attn_output
|
701 |
+
|
702 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
703 |
+
batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
704 |
+
|
705 |
+
# On the first iteration we need to properly re-create the padding mask
|
706 |
+
# by slicing it on the proper place
|
707 |
+
if kv_seq_len != attention_mask.shape[-1]:
|
708 |
+
attention_mask_num_tokens = attention_mask.shape[-1]
|
709 |
+
attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
710 |
+
|
711 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
712 |
+
|
713 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
714 |
+
value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
715 |
+
|
716 |
+
if query_length == kv_seq_len:
|
717 |
+
query_layer = index_first_axis(
|
718 |
+
query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
719 |
+
)
|
720 |
+
cu_seqlens_q = cu_seqlens_k
|
721 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
722 |
+
indices_q = indices_k
|
723 |
+
elif query_length == 1:
|
724 |
+
max_seqlen_in_batch_q = 1
|
725 |
+
cu_seqlens_q = torch.arange(
|
726 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
727 |
+
) # There is a memcpy here, that is very bad.
|
728 |
+
indices_q = cu_seqlens_q[:-1]
|
729 |
+
query_layer = query_layer.squeeze(1)
|
730 |
+
else:
|
731 |
+
# The -q_len: slice assumes left padding.
|
732 |
+
attention_mask = attention_mask[:, -query_length:]
|
733 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
734 |
+
|
735 |
+
return (
|
736 |
+
query_layer,
|
737 |
+
key_layer,
|
738 |
+
value_layer,
|
739 |
+
indices_q,
|
740 |
+
(cu_seqlens_q, cu_seqlens_k),
|
741 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
742 |
+
)
|
743 |
+
|
744 |
+
|
745 |
+
class MistralDecoderLayer(nn.Module):
|
746 |
+
def __init__(self, config: Idefics2Config, layer_idx: int):
|
747 |
+
super().__init__()
|
748 |
+
self.hidden_size = config.hidden_size
|
749 |
+
self.self_attn = (
|
750 |
+
MistralAttention(config=config, layer_idx=layer_idx)
|
751 |
+
if not getattr(config, "_flash_attn_2_enabled", False)
|
752 |
+
else MistralFlashAttention2(config=config, layer_idx=layer_idx)
|
753 |
+
)
|
754 |
+
self.mlp = MLP(
|
755 |
+
activation=config.hidden_act,
|
756 |
+
input_size=config.hidden_size,
|
757 |
+
intermediate_size=config.intermediate_size,
|
758 |
+
output_size=config.hidden_size,
|
759 |
+
)
|
760 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
761 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
762 |
+
|
763 |
+
def forward(
|
764 |
+
self,
|
765 |
+
hidden_states: torch.Tensor,
|
766 |
+
attention_mask: Optional[torch.Tensor] = None,
|
767 |
+
position_ids: Optional[torch.LongTensor] = None,
|
768 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
769 |
+
output_attentions: Optional[bool] = False,
|
770 |
+
use_cache: Optional[bool] = False,
|
771 |
+
**kwargs,
|
772 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
773 |
+
if "padding_mask" in kwargs:
|
774 |
+
warnings.warn(
|
775 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
776 |
+
)
|
777 |
+
"""
|
778 |
+
Args:
|
779 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
780 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
781 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
782 |
+
output_attentions (`bool`, *optional*):
|
783 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
784 |
+
returned tensors for more detail.
|
785 |
+
use_cache (`bool`, *optional*):
|
786 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
787 |
+
(see `past_key_values`).
|
788 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
789 |
+
"""
|
790 |
+
|
791 |
+
residual = hidden_states
|
792 |
+
|
793 |
+
hidden_states = self.input_layernorm(hidden_states)
|
794 |
+
|
795 |
+
# Self Attention
|
796 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
797 |
+
hidden_states=hidden_states,
|
798 |
+
attention_mask=attention_mask,
|
799 |
+
position_ids=position_ids,
|
800 |
+
past_key_value=past_key_value,
|
801 |
+
output_attentions=output_attentions,
|
802 |
+
use_cache=use_cache,
|
803 |
+
)
|
804 |
+
hidden_states = residual + hidden_states
|
805 |
+
|
806 |
+
# Fully Connected
|
807 |
+
residual = hidden_states
|
808 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
809 |
+
hidden_states = self.mlp(hidden_states)
|
810 |
+
hidden_states = residual + hidden_states
|
811 |
+
|
812 |
+
outputs = (hidden_states,)
|
813 |
+
|
814 |
+
if output_attentions:
|
815 |
+
outputs += (self_attn_weights,)
|
816 |
+
|
817 |
+
if use_cache:
|
818 |
+
outputs += (present_key_value,)
|
819 |
+
|
820 |
+
return outputs
|
821 |
+
|
822 |
+
|
823 |
+
MISTRAL_START_DOCSTRING = r"""
|
824 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
825 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
826 |
+
etc.)
|
827 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
828 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
829 |
+
and behavior.
|
830 |
+
Parameters:
|
831 |
+
config ([`Idefics2Config`]):
|
832 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
833 |
+
load the weights associated with the model, only the configuration. Check out the
|
834 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
835 |
+
"""
|
836 |
+
|
837 |
+
|
838 |
+
@add_start_docstrings(
|
839 |
+
"The bare Mistral Model outputting raw hidden-states without any specific head on top.",
|
840 |
+
MISTRAL_START_DOCSTRING,
|
841 |
+
)
|
842 |
+
class Idefics2PreTrainedModel(PreTrainedModel):
|
843 |
+
config_class = Idefics2Config
|
844 |
+
base_model_prefix = "model"
|
845 |
+
supports_gradient_checkpointing = True
|
846 |
+
_no_split_modules = ["MistralDecoderLayer"]
|
847 |
+
_skip_keys_device_placement = "past_key_values"
|
848 |
+
_supports_sdpa = False
|
849 |
+
|
850 |
+
def _init_weights(self, module):
|
851 |
+
# important: this ported version of the model isn't meant for training from scratch - only
|
852 |
+
# inference and fine-tuning - so the proper init weights code has been removed - the m4 code
|
853 |
+
# base should be used for training from scratch and it contains the correct code.
|
854 |
+
std = self.config.initializer_range
|
855 |
+
if isinstance(module, nn.Linear):
|
856 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
857 |
+
if module.bias is not None:
|
858 |
+
module.bias.data.zero_()
|
859 |
+
elif isinstance(module, nn.Embedding):
|
860 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
861 |
+
if module.padding_idx is not None:
|
862 |
+
module.weight.data[module.padding_idx].zero_()
|
863 |
+
|
864 |
+
|
865 |
+
MISTRAL_INPUTS_DOCSTRING = r"""
|
866 |
+
Args:
|
867 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
868 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
869 |
+
it.
|
870 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
871 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
872 |
+
[What are input IDs?](../glossary#input-ids)
|
873 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
874 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
875 |
+
- 1 for tokens that are **not masked**,
|
876 |
+
- 0 for tokens that are **masked**.
|
877 |
+
[What are attention masks?](../glossary#attention-mask)
|
878 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
879 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
880 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
881 |
+
`past_key_values`).
|
882 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
883 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
884 |
+
information on the default strategy.
|
885 |
+
- 1 indicates the head is **not masked**,
|
886 |
+
- 0 indicates the head is **masked**.
|
887 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
888 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
889 |
+
config.n_positions - 1]`.
|
890 |
+
[What are position IDs?](../glossary#position-ids)
|
891 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
892 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
893 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
894 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
895 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
896 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
897 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
898 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
899 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
900 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
901 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
902 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
903 |
+
model's internal embedding lookup matrix.
|
904 |
+
use_cache (`bool`, *optional*):
|
905 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
906 |
+
`past_key_values`).
|
907 |
+
output_attentions (`bool`, *optional*):
|
908 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
909 |
+
tensors for more detail.
|
910 |
+
output_hidden_states (`bool`, *optional*):
|
911 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
912 |
+
more detail.
|
913 |
+
return_dict (`bool`, *optional*):
|
914 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
915 |
+
"""
|
916 |
+
|
917 |
+
|
918 |
+
@add_start_docstrings(
|
919 |
+
"The bare Mistral Model outputting raw hidden-states without any specific head on top.",
|
920 |
+
MISTRAL_START_DOCSTRING,
|
921 |
+
)
|
922 |
+
class Idefics2Model(Idefics2PreTrainedModel):
|
923 |
+
"""
|
924 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]
|
925 |
+
Args:
|
926 |
+
config: Idefics2Config
|
927 |
+
"""
|
928 |
+
|
929 |
+
def __init__(self, config: Idefics2Config, vision_model=None):
|
930 |
+
super().__init__(config)
|
931 |
+
self.config = config
|
932 |
+
self.padding_idx = config.pad_token_id
|
933 |
+
self.vocab_size = config.vocab_size
|
934 |
+
|
935 |
+
self.sliding_window = config.sliding_window
|
936 |
+
|
937 |
+
self.embed_tokens = DecoupledEmbedding(
|
938 |
+
num_embeddings=config.vocab_size,
|
939 |
+
num_additional_embeddings=config.additional_vocab_size,
|
940 |
+
embedding_dim=config.hidden_size,
|
941 |
+
partially_freeze=config.freeze_text_layers,
|
942 |
+
padding_idx=self.padding_idx,
|
943 |
+
)
|
944 |
+
|
945 |
+
# Load an uninitialized model and later in from_pretrained will load the pre-trained model -
|
946 |
+
# this solves the losing of weights in `from_pretrained` on the main model
|
947 |
+
self.vision_model = SiglipVisionTransformer(config.vision_config)
|
948 |
+
|
949 |
+
# Dim projection - projecting from the vision dim to the text dim
|
950 |
+
self.modality_projection = MLP(
|
951 |
+
activation=self.config.hidden_act,
|
952 |
+
input_size=self.config.vision_config.hidden_size,
|
953 |
+
intermediate_size=self.config.intermediate_size,
|
954 |
+
output_size=self.config.hidden_size,
|
955 |
+
)
|
956 |
+
|
957 |
+
# Perceiver Resampler
|
958 |
+
if not config.use_resampler:
|
959 |
+
raise ValueError("NOT using the resampler is deprecated.")
|
960 |
+
|
961 |
+
if config.use_resampler:
|
962 |
+
self.perceiver_resampler = PerceiverResampler(config)
|
963 |
+
|
964 |
+
if config.use_resampler:
|
965 |
+
self.image_seq_len = config.perceiver_config.resampler_n_latents
|
966 |
+
else:
|
967 |
+
self.image_seq_len = (
|
968 |
+
config.vision_config.image_size // config.vision_config.patch_size
|
969 |
+
) ** 2
|
970 |
+
|
971 |
+
self.image_token_id = self.config.image_token_id
|
972 |
+
|
973 |
+
self.layers = nn.ModuleList([MistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
974 |
+
|
975 |
+
self.gradient_checkpointing = False
|
976 |
+
|
977 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
978 |
+
|
979 |
+
# Initialize weights and apply final processing
|
980 |
+
self.post_init()
|
981 |
+
|
982 |
+
self.freeze_relevant_params(config)
|
983 |
+
|
984 |
+
def enable_input_require_grads(self):
|
985 |
+
"""
|
986 |
+
Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
|
987 |
+
the model weights fixed.
|
988 |
+
"""
|
989 |
+
|
990 |
+
def get_lowest_module(module):
|
991 |
+
if len(list(module.children())) == 0:
|
992 |
+
# If the module has no children, it is a leaf module (e.g., Linear, Conv2d, etc.)
|
993 |
+
return module
|
994 |
+
else:
|
995 |
+
# Recursively call the function on each child module
|
996 |
+
return get_lowest_module(list(module.children())[0])
|
997 |
+
|
998 |
+
def make_inputs_require_grads(module, input, output):
|
999 |
+
output.requires_grad_(True)
|
1000 |
+
|
1001 |
+
self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads)
|
1002 |
+
self._vision_require_grads_hook = get_lowest_module(self.vision_model).register_forward_hook(
|
1003 |
+
make_inputs_require_grads
|
1004 |
+
)
|
1005 |
+
|
1006 |
+
def freeze_relevant_params(self, config=None):
|
1007 |
+
if config is None:
|
1008 |
+
config = self.config
|
1009 |
+
|
1010 |
+
if config.freeze_text_layers:
|
1011 |
+
self.freeze_text_layers(config.freeze_text_module_exceptions)
|
1012 |
+
|
1013 |
+
if config.freeze_vision_layers:
|
1014 |
+
freeze_model(self.vision_model, module_exceptions=config.freeze_vision_module_exceptions)
|
1015 |
+
|
1016 |
+
def freeze_text_layers(self, module_exceptions):
|
1017 |
+
for module in [self.layers, self.norm]:
|
1018 |
+
freeze_model(module, module_exceptions=module_exceptions)
|
1019 |
+
|
1020 |
+
def get_input_embeddings(self):
|
1021 |
+
return self.embed_tokens
|
1022 |
+
|
1023 |
+
def set_input_embeddings(self, value):
|
1024 |
+
self.embed_tokens = value
|
1025 |
+
|
1026 |
+
def inputs_merger(
|
1027 |
+
self,
|
1028 |
+
input_ids: torch.LongTensor = None,
|
1029 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1030 |
+
image_hidden_states: Optional[torch.Tensor] = None,
|
1031 |
+
):
|
1032 |
+
"""
|
1033 |
+
This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are fed to the transformer LM.
|
1034 |
+
The merging happens as follows:
|
1035 |
+
- The text token sequence is: `tok_1 tok_2 tok_3 <fake_token_around_image> <image> <image> ... <image> <fake_token_around_image> tok_4`.
|
1036 |
+
- We get the image hidden states for the image through the vision encoder (and potentially the perceiver), and that hidden state is then projected into the text embedding space.
|
1037 |
+
We thus have a sequence of image hidden states of size (1, image_seq_len, hidden_dim), where 1 is for batch_size of 1 image and hidden_dim is the hidden_dim of the LM transformer.
|
1038 |
+
- The merging happens so that we obtain the following sequence: `vector_tok_1 vector_tok_2 vector_tok_3 vector_fake_tok_around_image {sequence of image_seq_len image hidden states} vector_fake_toke_around_image vector_tok_4`. That sequence is fed to the LM.
|
1039 |
+
- To fit the format of that sequence, `input_ids`, `input_embeds`, `attention_mask` are all 3 adapted to insert the image hidden states.
|
1040 |
+
"""
|
1041 |
+
batch_size = input_ids.size(0)
|
1042 |
+
|
1043 |
+
if inputs_embeds is not None:
|
1044 |
+
if image_hidden_states is not None:
|
1045 |
+
vision_pipeline_output_seq_len = image_hidden_states.shape[1]
|
1046 |
+
vision_hidden_size = image_hidden_states.shape[2]
|
1047 |
+
new_inputs_embeds = inputs_embeds.clone()
|
1048 |
+
# Get the number of images for each example
|
1049 |
+
num_images = (input_ids == self.image_token_id).sum(dim=-1) // self.image_seq_len
|
1050 |
+
cum_num_images = num_images.cumsum(dim=-1)
|
1051 |
+
for batch_idx in range(batch_size):
|
1052 |
+
# Get the number of images for this particular example
|
1053 |
+
example_num_images = num_images[batch_idx]
|
1054 |
+
# Get the image_hidden_states corresponding to True images for the example, so get rid of the padding images.
|
1055 |
+
start = 0 if batch_idx == 0 else cum_num_images[batch_idx - 1]
|
1056 |
+
end = cum_num_images[batch_idx]
|
1057 |
+
example_true_image_hidden_states = image_hidden_states[start:end]
|
1058 |
+
if (
|
1059 |
+
new_inputs_embeds[batch_idx][input_ids[batch_idx] == self.image_token_id].shape[0]
|
1060 |
+
!= example_num_images * vision_pipeline_output_seq_len
|
1061 |
+
):
|
1062 |
+
raise ValueError(
|
1063 |
+
"new_inputs_embeds to replace has shape[0]:"
|
1064 |
+
f" {new_inputs_embeds[batch_idx][input_ids[batch_idx] == self.image_token_id].shape[0]} but"
|
1065 |
+
" should have shape[0]:"
|
1066 |
+
f" {example_num_images}*{vision_pipeline_output_seq_len}={example_num_images * vision_pipeline_output_seq_len} "
|
1067 |
+
)
|
1068 |
+
# Insert the image_hidden_states
|
1069 |
+
new_inputs_embeds[batch_idx][input_ids[batch_idx] == self.image_token_id] = (
|
1070 |
+
example_true_image_hidden_states.view(
|
1071 |
+
example_num_images * vision_pipeline_output_seq_len,
|
1072 |
+
vision_hidden_size,
|
1073 |
+
)
|
1074 |
+
)
|
1075 |
+
else:
|
1076 |
+
new_inputs_embeds = inputs_embeds
|
1077 |
+
|
1078 |
+
return_dict = {}
|
1079 |
+
if inputs_embeds is not None:
|
1080 |
+
return_dict["inputs_embeds"] = new_inputs_embeds
|
1081 |
+
|
1082 |
+
return return_dict
|
1083 |
+
|
1084 |
+
@add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
|
1085 |
+
def forward(
|
1086 |
+
self,
|
1087 |
+
input_ids: torch.LongTensor = None,
|
1088 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1089 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1090 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1091 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1092 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1093 |
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
1094 |
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
1095 |
+
use_cache: Optional[bool] = None,
|
1096 |
+
output_attentions: Optional[bool] = None,
|
1097 |
+
output_hidden_states: Optional[bool] = None,
|
1098 |
+
return_dict: Optional[bool] = None,
|
1099 |
+
) -> Union[Tuple, Idefics2BaseModelOutputWithPast]:
|
1100 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1101 |
+
|
1102 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1103 |
+
output_hidden_states = (
|
1104 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1105 |
+
)
|
1106 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1107 |
+
|
1108 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1109 |
+
|
1110 |
+
# retrieve input_ids and inputs_embeds
|
1111 |
+
if input_ids is not None and inputs_embeds is not None:
|
1112 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
1113 |
+
elif input_ids is not None:
|
1114 |
+
batch_size, seq_length = input_ids.shape
|
1115 |
+
elif inputs_embeds is not None:
|
1116 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
1117 |
+
else:
|
1118 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
1119 |
+
|
1120 |
+
if self.gradient_checkpointing and self.training:
|
1121 |
+
if use_cache:
|
1122 |
+
logger.warning_once(
|
1123 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1124 |
+
)
|
1125 |
+
use_cache = False
|
1126 |
+
|
1127 |
+
past_key_values_length = 0
|
1128 |
+
|
1129 |
+
if use_cache:
|
1130 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1131 |
+
if use_legacy_cache:
|
1132 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1133 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1134 |
+
|
1135 |
+
if position_ids is None:
|
1136 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1137 |
+
position_ids = torch.arange(
|
1138 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1139 |
+
)
|
1140 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
1141 |
+
else:
|
1142 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
1143 |
+
|
1144 |
+
if inputs_embeds is None:
|
1145 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1146 |
+
|
1147 |
+
# START VISUAL INPUTS INTEGRATION
|
1148 |
+
if pixel_values is not None and image_hidden_states is not None:
|
1149 |
+
raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
|
1150 |
+
elif pixel_values is not None:
|
1151 |
+
pixel_values = pixel_values.to(dtype=self.dtype, device=input_ids.device) # fp16 compatibility
|
1152 |
+
batch_size, num_images = pixel_values.size(0), pixel_values.size(1)
|
1153 |
+
pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
|
1154 |
+
|
1155 |
+
# Remove padding images - padding images are full 0.
|
1156 |
+
nb_values_per_image = pixel_values.shape[1:].numel()
|
1157 |
+
real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
|
1158 |
+
pixel_values = pixel_values[real_images_inds].contiguous()
|
1159 |
+
|
1160 |
+
# Handle the vision attention mask
|
1161 |
+
if pixel_attention_mask is None:
|
1162 |
+
pixel_attention_mask = torch.ones(
|
1163 |
+
size=(pixel_values.size(0), pixel_values.size(2), pixel_values.size(3)),
|
1164 |
+
dtype=torch.bool,
|
1165 |
+
device=pixel_values.device,
|
1166 |
+
)
|
1167 |
+
else:
|
1168 |
+
# Remove padding images from the mask
|
1169 |
+
pixel_attention_mask = pixel_attention_mask.view(
|
1170 |
+
batch_size * num_images, *pixel_attention_mask.shape[2:]
|
1171 |
+
)
|
1172 |
+
pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
|
1173 |
+
|
1174 |
+
patches_subgrid = pixel_attention_mask.unfold(
|
1175 |
+
dimension=1, size=self.config.vision_config.patch_size, step=self.config.vision_config.patch_size
|
1176 |
+
).unfold(dimension=2, size=self.config.vision_config.patch_size, step=self.config.vision_config.patch_size)
|
1177 |
+
patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
|
1178 |
+
|
1179 |
+
# Get sequence from the vision encoder
|
1180 |
+
image_hidden_states = self.vision_model(
|
1181 |
+
pixel_values=pixel_values,
|
1182 |
+
patch_attention_mask=patch_attention_mask,
|
1183 |
+
).last_hidden_state
|
1184 |
+
|
1185 |
+
# Modality projection
|
1186 |
+
image_hidden_states = self.modality_projection(image_hidden_states)
|
1187 |
+
|
1188 |
+
if self.config.use_resampler:
|
1189 |
+
image_hidden_states = self.perceiver_resampler(
|
1190 |
+
context=image_hidden_states, attention_mask=patch_attention_mask.view(pixel_values.size(0), -1)
|
1191 |
+
)
|
1192 |
+
elif image_hidden_states is not None:
|
1193 |
+
image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=input_ids.device)
|
1194 |
+
|
1195 |
+
if past_key_values_length == 0:
|
1196 |
+
# When we generate, we don't want to replace the potential image_token_id that we generated by images
|
1197 |
+
# that simply don't exist
|
1198 |
+
new_inp = self.inputs_merger(
|
1199 |
+
input_ids=input_ids,
|
1200 |
+
inputs_embeds=inputs_embeds,
|
1201 |
+
image_hidden_states=image_hidden_states,
|
1202 |
+
)
|
1203 |
+
inputs_embeds = new_inp["inputs_embeds"]
|
1204 |
+
|
1205 |
+
# Can do add some token types embeddings here (image token vs text token)
|
1206 |
+
# something like inputs_embeds += self.token_types(token_types)
|
1207 |
+
|
1208 |
+
# embed positions
|
1209 |
+
if (
|
1210 |
+
attention_mask is not None
|
1211 |
+
and hasattr(self.config, "_flash_attn_2_enabled")
|
1212 |
+
and self.config._flash_attn_2_enabled
|
1213 |
+
and use_cache
|
1214 |
+
):
|
1215 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
1216 |
+
if is_padding_right:
|
1217 |
+
raise ValueError(
|
1218 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
1219 |
+
" this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
|
1220 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
1221 |
+
)
|
1222 |
+
|
1223 |
+
if getattr(self.config, "_flash_attn_2_enabled", False):
|
1224 |
+
# 2d mask is passed through the layers
|
1225 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1226 |
+
else:
|
1227 |
+
# 4d mask is passed through the layers
|
1228 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1229 |
+
attention_mask,
|
1230 |
+
(batch_size, seq_length),
|
1231 |
+
inputs_embeds,
|
1232 |
+
past_key_values_length,
|
1233 |
+
sliding_window=self.config.sliding_window,
|
1234 |
+
)
|
1235 |
+
|
1236 |
+
hidden_states = inputs_embeds
|
1237 |
+
|
1238 |
+
# decoder layers
|
1239 |
+
all_hidden_states = () if output_hidden_states else None
|
1240 |
+
all_self_attns = () if output_attentions else None
|
1241 |
+
next_decoder_cache = None
|
1242 |
+
|
1243 |
+
for decoder_layer in self.layers:
|
1244 |
+
if output_hidden_states:
|
1245 |
+
all_hidden_states += (hidden_states,)
|
1246 |
+
|
1247 |
+
if self.gradient_checkpointing and self.training:
|
1248 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1249 |
+
decoder_layer.__call__,
|
1250 |
+
hidden_states,
|
1251 |
+
attention_mask,
|
1252 |
+
position_ids,
|
1253 |
+
past_key_values,
|
1254 |
+
output_attentions,
|
1255 |
+
use_cache,
|
1256 |
+
)
|
1257 |
+
else:
|
1258 |
+
layer_outputs = decoder_layer(
|
1259 |
+
hidden_states,
|
1260 |
+
attention_mask=attention_mask,
|
1261 |
+
position_ids=position_ids,
|
1262 |
+
past_key_value=past_key_values,
|
1263 |
+
output_attentions=output_attentions,
|
1264 |
+
use_cache=use_cache,
|
1265 |
+
)
|
1266 |
+
|
1267 |
+
hidden_states = layer_outputs[0]
|
1268 |
+
|
1269 |
+
if use_cache:
|
1270 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1271 |
+
|
1272 |
+
if output_attentions:
|
1273 |
+
all_self_attns += (layer_outputs[1],)
|
1274 |
+
|
1275 |
+
hidden_states = self.norm(hidden_states)
|
1276 |
+
|
1277 |
+
# add hidden states from the last decoder layer
|
1278 |
+
if output_hidden_states:
|
1279 |
+
all_hidden_states += (hidden_states,)
|
1280 |
+
|
1281 |
+
next_cache = None
|
1282 |
+
if use_cache:
|
1283 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1284 |
+
|
1285 |
+
if not return_dict:
|
1286 |
+
return tuple(
|
1287 |
+
v
|
1288 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, image_hidden_states]
|
1289 |
+
if v is not None
|
1290 |
+
)
|
1291 |
+
return Idefics2BaseModelOutputWithPast(
|
1292 |
+
last_hidden_state=hidden_states,
|
1293 |
+
past_key_values=next_cache,
|
1294 |
+
hidden_states=all_hidden_states,
|
1295 |
+
attentions=all_self_attns,
|
1296 |
+
image_hidden_states=image_hidden_states,
|
1297 |
+
)
|
1298 |
+
|
1299 |
+
|
1300 |
+
class Idefics2ForVisionText2Text(Idefics2PreTrainedModel):
|
1301 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1302 |
+
|
1303 |
+
def __init__(self, config, vision_model=None):
|
1304 |
+
super().__init__(config)
|
1305 |
+
self.model = Idefics2Model(config, vision_model=vision_model)
|
1306 |
+
self.image_token_id = self.config.image_token_id
|
1307 |
+
self.lm_head = DecoupledLinear(
|
1308 |
+
in_features=config.hidden_size,
|
1309 |
+
out_features=config.vocab_size,
|
1310 |
+
out_additional_features=config.additional_vocab_size,
|
1311 |
+
bias=False,
|
1312 |
+
partially_freeze=config.freeze_lm_head,
|
1313 |
+
)
|
1314 |
+
|
1315 |
+
# Initialize weights and apply final processing
|
1316 |
+
self.post_init()
|
1317 |
+
|
1318 |
+
def enable_input_require_grads(self):
|
1319 |
+
"""
|
1320 |
+
Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
|
1321 |
+
the model weights fixed.
|
1322 |
+
"""
|
1323 |
+
|
1324 |
+
def get_lowest_module(module):
|
1325 |
+
if len(list(module.children())) == 0:
|
1326 |
+
# If the module has no children, it is a leaf module (e.g., Linear, Conv2d, etc.)
|
1327 |
+
return module
|
1328 |
+
else:
|
1329 |
+
# Recursively call the function on each child module
|
1330 |
+
return get_lowest_module(list(module.children())[0])
|
1331 |
+
|
1332 |
+
def make_inputs_require_grads(module, input, output):
|
1333 |
+
output.requires_grad_(True)
|
1334 |
+
|
1335 |
+
self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads)
|
1336 |
+
self._vision_require_grads_hook = get_lowest_module(self.model.vision_model).register_forward_hook(
|
1337 |
+
make_inputs_require_grads
|
1338 |
+
)
|
1339 |
+
|
1340 |
+
def get_input_embeddings(self):
|
1341 |
+
return self.model.embed_tokens
|
1342 |
+
|
1343 |
+
def set_input_embeddings(self, value):
|
1344 |
+
self.model.embed_tokens = value
|
1345 |
+
|
1346 |
+
def get_output_embeddings(self):
|
1347 |
+
return self.lm_head
|
1348 |
+
|
1349 |
+
def set_output_embeddings(self, new_embeddings):
|
1350 |
+
self.lm_head = new_embeddings
|
1351 |
+
|
1352 |
+
def set_decoder(self, decoder):
|
1353 |
+
self.model = decoder
|
1354 |
+
|
1355 |
+
def get_decoder(self):
|
1356 |
+
return self.model
|
1357 |
+
|
1358 |
+
def tie_weights(self):
|
1359 |
+
"""
|
1360 |
+
Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of DecoupledLinear and DecoupledEmbedding.
|
1361 |
+
"""
|
1362 |
+
output_embeddings = self.get_output_embeddings()
|
1363 |
+
input_embeddings = self.get_input_embeddings()
|
1364 |
+
|
1365 |
+
if getattr(self.config, "tie_word_embeddings", True):
|
1366 |
+
output_embeddings.weight = input_embeddings.weight
|
1367 |
+
if input_embeddings.num_additional_embeddings > 0:
|
1368 |
+
assert output_embeddings.out_additional_features == input_embeddings.num_additional_embeddings
|
1369 |
+
output_embeddings.additional_fc.weight = input_embeddings.additional_embedding.weight
|
1370 |
+
|
1371 |
+
if hasattr(output_embeddings, "out_features") and hasattr(input_embeddings, "num_embeddings"):
|
1372 |
+
output_embeddings.out_features = input_embeddings.num_embeddings
|
1373 |
+
if hasattr(output_embeddings, "out_additional_features") and hasattr(
|
1374 |
+
input_embeddings, "num_additional_embeddings"
|
1375 |
+
):
|
1376 |
+
output_embeddings.out_additional_features = input_embeddings.num_additional_embeddings
|
1377 |
+
|
1378 |
+
@add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
|
1379 |
+
@replace_return_docstrings(output_type=Idefics2CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1380 |
+
def forward(
|
1381 |
+
self,
|
1382 |
+
input_ids: torch.LongTensor = None,
|
1383 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1384 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1385 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1386 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1387 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1388 |
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
1389 |
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
1390 |
+
labels: Optional[torch.LongTensor] = None,
|
1391 |
+
use_cache: Optional[bool] = None,
|
1392 |
+
output_attentions: Optional[bool] = None,
|
1393 |
+
output_hidden_states: Optional[bool] = None,
|
1394 |
+
return_dict: Optional[bool] = None,
|
1395 |
+
) -> Union[Tuple, Idefics2CausalLMOutputWithPast]:
|
1396 |
+
r"""
|
1397 |
+
Args:
|
1398 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1399 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1400 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1401 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1402 |
+
Returns:
|
1403 |
+
"""
|
1404 |
+
|
1405 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1406 |
+
output_hidden_states = (
|
1407 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1408 |
+
)
|
1409 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1410 |
+
|
1411 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1412 |
+
outputs = self.model(
|
1413 |
+
input_ids=input_ids,
|
1414 |
+
attention_mask=attention_mask,
|
1415 |
+
position_ids=position_ids,
|
1416 |
+
past_key_values=past_key_values,
|
1417 |
+
inputs_embeds=inputs_embeds,
|
1418 |
+
pixel_values=pixel_values,
|
1419 |
+
pixel_attention_mask=pixel_attention_mask,
|
1420 |
+
image_hidden_states=image_hidden_states,
|
1421 |
+
use_cache=use_cache,
|
1422 |
+
output_attentions=output_attentions,
|
1423 |
+
output_hidden_states=output_hidden_states,
|
1424 |
+
return_dict=return_dict,
|
1425 |
+
)
|
1426 |
+
|
1427 |
+
hidden_states = outputs[0]
|
1428 |
+
logits = self.lm_head(hidden_states)
|
1429 |
+
logits = logits.float()
|
1430 |
+
|
1431 |
+
loss = None
|
1432 |
+
if labels is not None:
|
1433 |
+
labels = labels.to(logits.device)
|
1434 |
+
# Shift so that tokens < n predict n
|
1435 |
+
if attention_mask is not None:
|
1436 |
+
shift_attention_mask = attention_mask[..., 1:].to(logits.device)
|
1437 |
+
shift_logits = logits[..., :-1, :][shift_attention_mask != 0].contiguous()
|
1438 |
+
shift_labels = labels[..., 1:][shift_attention_mask != 0].contiguous()
|
1439 |
+
else:
|
1440 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1441 |
+
shift_labels = labels[..., 1:].contiguous()
|
1442 |
+
# Flatten the tokens
|
1443 |
+
loss_fct = CrossEntropyLoss(ignore_index=self.image_token_id)
|
1444 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1445 |
+
|
1446 |
+
if not return_dict:
|
1447 |
+
output = (logits,) + outputs[1:]
|
1448 |
+
return (loss,) + output if loss is not None else output
|
1449 |
+
|
1450 |
+
return Idefics2CausalLMOutputWithPast(
|
1451 |
+
loss=loss,
|
1452 |
+
logits=logits,
|
1453 |
+
past_key_values=outputs.past_key_values,
|
1454 |
+
hidden_states=outputs.hidden_states,
|
1455 |
+
attentions=outputs.attentions,
|
1456 |
+
image_hidden_states=outputs.image_hidden_states,
|
1457 |
+
)
|
1458 |
+
|
1459 |
+
def prepare_inputs_for_generation(
|
1460 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1461 |
+
):
|
1462 |
+
# Omit tokens covered by past_key_values
|
1463 |
+
if past_key_values is not None:
|
1464 |
+
if isinstance(past_key_values, Cache):
|
1465 |
+
cache_length = past_key_values.get_seq_length()
|
1466 |
+
past_length = past_key_values.seen_tokens
|
1467 |
+
max_cache_length = past_key_values.get_max_length()
|
1468 |
+
else:
|
1469 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1470 |
+
max_cache_length = None
|
1471 |
+
|
1472 |
+
# Keep only the unprocessed tokens:
|
1473 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1474 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1475 |
+
# input)
|
1476 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1477 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1478 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1479 |
+
# input_ids based on the past_length.
|
1480 |
+
elif past_length < input_ids.shape[1]:
|
1481 |
+
input_ids = input_ids[:, past_length:]
|
1482 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1483 |
+
|
1484 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1485 |
+
if (
|
1486 |
+
max_cache_length is not None
|
1487 |
+
and attention_mask is not None
|
1488 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1489 |
+
):
|
1490 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1491 |
+
|
1492 |
+
position_ids = kwargs.get("position_ids", None)
|
1493 |
+
if attention_mask is not None and position_ids is None:
|
1494 |
+
# create position_ids on the fly for batch generation
|
1495 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1496 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1497 |
+
if past_key_values:
|
1498 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1499 |
+
|
1500 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1501 |
+
if inputs_embeds is not None and past_key_values is None:
|
1502 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1503 |
+
else:
|
1504 |
+
model_inputs = {"input_ids": input_ids}
|
1505 |
+
|
1506 |
+
image_hidden_states = kwargs.get("image_hidden_states", None)
|
1507 |
+
if image_hidden_states is not None:
|
1508 |
+
pixel_values = None
|
1509 |
+
else:
|
1510 |
+
pixel_values = kwargs.get("pixel_values", None)
|
1511 |
+
model_inputs.update(
|
1512 |
+
{
|
1513 |
+
"position_ids": position_ids,
|
1514 |
+
"past_key_values": past_key_values,
|
1515 |
+
"use_cache": kwargs.get("use_cache"),
|
1516 |
+
"attention_mask": attention_mask,
|
1517 |
+
"pixel_values": pixel_values,
|
1518 |
+
"image_hidden_states": image_hidden_states,
|
1519 |
+
}
|
1520 |
+
)
|
1521 |
+
return model_inputs
|
1522 |
+
|
1523 |
+
@staticmethod
|
1524 |
+
def _expand_inputs_for_generation(
|
1525 |
+
*args,
|
1526 |
+
**model_kwargs,
|
1527 |
+
):
|
1528 |
+
return expand_inputs_for_generation(*args, **model_kwargs)
|
1529 |
+
|
1530 |
+
@staticmethod
|
1531 |
+
def _update_model_kwargs_for_generation(outputs, model_kwargs, is_encoder_decoder):
|
1532 |
+
return update_model_kwargs_for_generation(outputs, model_kwargs)
|
1533 |
+
|
1534 |
+
@staticmethod
|
1535 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1536 |
+
reordered_past = ()
|
1537 |
+
for layer_past in past_key_values:
|
1538 |
+
reordered_past += (
|
1539 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1540 |
+
)
|
1541 |
+
return reordered_past
|
1542 |
+
|
perceiver.py
ADDED
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
|
21 |
+
import math
|
22 |
+
from typing import Optional, Tuple
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn as nn
|
26 |
+
import torch.nn.functional as F
|
27 |
+
from einops import repeat
|
28 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
29 |
+
from transformers.utils import is_flash_attn_2_available
|
30 |
+
from transformers.utils import logging
|
31 |
+
|
32 |
+
from .common import MLP, RMSNorm
|
33 |
+
|
34 |
+
|
35 |
+
if is_flash_attn_2_available():
|
36 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
37 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
|
42 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
43 |
+
def _get_unpad_data(attention_mask):
|
44 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
45 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
46 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
47 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
48 |
+
return (
|
49 |
+
indices,
|
50 |
+
cu_seqlens,
|
51 |
+
max_seqlen_in_batch,
|
52 |
+
)
|
53 |
+
|
54 |
+
|
55 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
56 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
57 |
+
"""
|
58 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
59 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
60 |
+
"""
|
61 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
62 |
+
if n_rep == 1:
|
63 |
+
return hidden_states
|
64 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
65 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
66 |
+
|
67 |
+
|
68 |
+
class PerceiverAttention(nn.Module):
|
69 |
+
def __init__(self, config) -> None:
|
70 |
+
"""Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`"""
|
71 |
+
super().__init__()
|
72 |
+
|
73 |
+
self.config = config
|
74 |
+
|
75 |
+
self.hidden_size = config.hidden_size
|
76 |
+
self.num_heads = config.perceiver_config.resampler_n_heads
|
77 |
+
self.head_dim = config.perceiver_config.resampler_head_dim
|
78 |
+
self.num_key_value_heads = config.perceiver_config.num_key_value_heads
|
79 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
80 |
+
self.qk_layer_norms = config.perceiver_config.qk_layer_norms_perceiver
|
81 |
+
self.attention_dropout = config.perceiver_config.attention_dropout
|
82 |
+
|
83 |
+
if self.qk_layer_norms:
|
84 |
+
self.q_layer_norm = RMSNorm(self.head_dim)
|
85 |
+
self.k_layer_norm = RMSNorm(self.head_dim)
|
86 |
+
|
87 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
88 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
89 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
90 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
91 |
+
|
92 |
+
self.is_causal = False
|
93 |
+
|
94 |
+
def forward(
|
95 |
+
self,
|
96 |
+
latents: torch.Tensor,
|
97 |
+
context: torch.Tensor,
|
98 |
+
attention_mask: Optional[torch.Tensor] = None,
|
99 |
+
position_ids: Optional[torch.LongTensor] = None,
|
100 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
101 |
+
output_attentions: bool = False,
|
102 |
+
use_cache: bool = False,
|
103 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
104 |
+
"""
|
105 |
+
Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension!
|
106 |
+
:param context: Tensor of shape [bsz, seq, embed_dim] representing long-form context to resample.
|
107 |
+
:param latents: Tensor of shape [bsz, n_latents, embed_dim] representing fixed length latents to compress to.
|
108 |
+
:return: Tensor of shape [bsz, n_latents, embed_dim] representing attention over latents w/ cross from context.
|
109 |
+
"""
|
110 |
+
bsz, q_len, _ = latents.size()
|
111 |
+
kv_seq_len = q_len + context.size()[1]
|
112 |
+
|
113 |
+
query_states = self.q_proj(latents).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
114 |
+
key_states = (
|
115 |
+
self.k_proj(torch.cat([context, latents], dim=-2))
|
116 |
+
.view(bsz, kv_seq_len, self.num_key_value_heads, self.head_dim)
|
117 |
+
.transpose(1, 2)
|
118 |
+
)
|
119 |
+
value_states = (
|
120 |
+
self.v_proj(torch.cat([context, latents], dim=-2))
|
121 |
+
.view(bsz, kv_seq_len, self.num_key_value_heads, self.head_dim)
|
122 |
+
.transpose(1, 2)
|
123 |
+
)
|
124 |
+
|
125 |
+
kv_seq_len = key_states.shape[-2]
|
126 |
+
if past_key_value is not None:
|
127 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
128 |
+
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
129 |
+
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
130 |
+
|
131 |
+
if past_key_value is not None:
|
132 |
+
# reuse k, v, self_attention
|
133 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
134 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
135 |
+
|
136 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
137 |
+
|
138 |
+
if self.qk_layer_norms:
|
139 |
+
query_states = self.q_layer_norm(query_states)
|
140 |
+
key_states = self.k_layer_norm(key_states)
|
141 |
+
|
142 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
143 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
144 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
145 |
+
|
146 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
147 |
+
|
148 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
149 |
+
raise ValueError(
|
150 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
151 |
+
f" {attn_weights.size()}"
|
152 |
+
)
|
153 |
+
|
154 |
+
if attention_mask is not None:
|
155 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
156 |
+
raise ValueError(
|
157 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
158 |
+
)
|
159 |
+
|
160 |
+
attn_weights = attn_weights + attention_mask
|
161 |
+
|
162 |
+
# upcast attention to fp32
|
163 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
164 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
165 |
+
|
166 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
167 |
+
raise ValueError(
|
168 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
169 |
+
f" {attn_output.size()}"
|
170 |
+
)
|
171 |
+
|
172 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
173 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim)
|
174 |
+
|
175 |
+
attn_output = self.o_proj(attn_output)
|
176 |
+
|
177 |
+
if not output_attentions:
|
178 |
+
attn_weights = None
|
179 |
+
|
180 |
+
return attn_output, attn_weights, past_key_value
|
181 |
+
|
182 |
+
|
183 |
+
class PerceiverFlashAttention2(PerceiverAttention):
|
184 |
+
"""
|
185 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
186 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
187 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
188 |
+
"""
|
189 |
+
|
190 |
+
def __init__(self, *args, **kwargs):
|
191 |
+
super().__init__(*args, **kwargs)
|
192 |
+
|
193 |
+
def forward(
|
194 |
+
self,
|
195 |
+
latents: torch.Tensor,
|
196 |
+
context: torch.Tensor,
|
197 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
198 |
+
position_ids: Optional[torch.LongTensor] = None,
|
199 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
200 |
+
output_attentions: bool = False,
|
201 |
+
use_cache: bool = False,
|
202 |
+
**kwargs,
|
203 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
204 |
+
bsz, q_len, _ = latents.size()
|
205 |
+
kv_seq_len = q_len + context.size()[1]
|
206 |
+
|
207 |
+
# Query, Key, Value Projections --> Note that in Flamingo, latents are *concatenated* with context prior to attn!
|
208 |
+
# Note: This results in queries w/ `seq = n_latents`, and keys, values with `seq = len(context) + n_latents`
|
209 |
+
query_states = self.q_proj(latents)
|
210 |
+
key_states = self.k_proj(torch.cat([context, latents], dim=-2))
|
211 |
+
value_states = self.v_proj(torch.cat([context, latents], dim=-2))
|
212 |
+
|
213 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
214 |
+
key_states = key_states.view(bsz, kv_seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
215 |
+
value_states = value_states.view(bsz, kv_seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
216 |
+
|
217 |
+
kv_seq_len = key_states.shape[-2]
|
218 |
+
if past_key_value is not None:
|
219 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
220 |
+
|
221 |
+
if past_key_value is not None:
|
222 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
223 |
+
if hasattr(self.config, "sliding_window") and kv_seq_len > self.config.sliding_window:
|
224 |
+
slicing_tokens = kv_seq_len - self.config.sliding_window
|
225 |
+
|
226 |
+
past_key = past_key_value[0]
|
227 |
+
past_value = past_key_value[1]
|
228 |
+
|
229 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
230 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
231 |
+
|
232 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
233 |
+
raise ValueError(
|
234 |
+
"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1,"
|
235 |
+
f" head_dim`), got {past_key.shape}"
|
236 |
+
)
|
237 |
+
|
238 |
+
past_key_value = (past_key, past_value)
|
239 |
+
|
240 |
+
if attention_mask is not None:
|
241 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
242 |
+
attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
243 |
+
|
244 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
245 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
246 |
+
|
247 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
248 |
+
|
249 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
250 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
251 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
252 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
253 |
+
|
254 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
255 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
256 |
+
# cast them back in float16 just to be sure everything works as expected.
|
257 |
+
input_dtype = query_states.dtype
|
258 |
+
if input_dtype == torch.float32:
|
259 |
+
# Handle the case where the model is quantized
|
260 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
261 |
+
target_dtype = self.config._pre_quantization_dtype
|
262 |
+
else:
|
263 |
+
target_dtype = self.q_proj.weight.dtype
|
264 |
+
|
265 |
+
logger.warning_once(
|
266 |
+
"The input hidden states seems to be silently casted in float32, this might be related to the fact"
|
267 |
+
" you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
268 |
+
f" {target_dtype}."
|
269 |
+
)
|
270 |
+
|
271 |
+
query_states = query_states.to(target_dtype)
|
272 |
+
key_states = key_states.to(target_dtype)
|
273 |
+
value_states = value_states.to(target_dtype)
|
274 |
+
|
275 |
+
# Reashape to the expected shape for Flash Attention
|
276 |
+
query_states = query_states.transpose(1, 2)
|
277 |
+
key_states = key_states.transpose(1, 2)
|
278 |
+
value_states = value_states.transpose(1, 2)
|
279 |
+
|
280 |
+
attn_output = self._flash_attention_forward(
|
281 |
+
query_states,
|
282 |
+
key_states,
|
283 |
+
value_states,
|
284 |
+
attention_mask,
|
285 |
+
q_len,
|
286 |
+
dropout=dropout_rate,
|
287 |
+
use_sliding_windows=False,
|
288 |
+
)
|
289 |
+
|
290 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
|
291 |
+
attn_output = self.o_proj(attn_output)
|
292 |
+
|
293 |
+
if not output_attentions:
|
294 |
+
attn_weights = None
|
295 |
+
|
296 |
+
return attn_output, attn_weights, past_key_value
|
297 |
+
|
298 |
+
def _flash_attention_forward(
|
299 |
+
self,
|
300 |
+
query_states,
|
301 |
+
key_states,
|
302 |
+
value_states,
|
303 |
+
attention_mask,
|
304 |
+
query_length,
|
305 |
+
dropout=0.0,
|
306 |
+
softmax_scale=None,
|
307 |
+
use_sliding_windows=False,
|
308 |
+
):
|
309 |
+
"""
|
310 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
311 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
312 |
+
|
313 |
+
Args:
|
314 |
+
query_states (`torch.Tensor`):
|
315 |
+
Input query states to be passed to Flash Attention API
|
316 |
+
key_states (`torch.Tensor`):
|
317 |
+
Input key states to be passed to Flash Attention API
|
318 |
+
value_states (`torch.Tensor`):
|
319 |
+
Input value states to be passed to Flash Attention API
|
320 |
+
attention_mask (`torch.Tensor`):
|
321 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
322 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
323 |
+
dropout (`int`, *optional*):
|
324 |
+
Attention dropout
|
325 |
+
softmax_scale (`float`, *optional*):
|
326 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
327 |
+
use_sliding_windows (`bool`, *optional*):
|
328 |
+
Whether to activate sliding window attention.
|
329 |
+
"""
|
330 |
+
# Contains at least one padding token in the sequence
|
331 |
+
if attention_mask is not None:
|
332 |
+
batch_size = query_states.shape[0]
|
333 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
334 |
+
query_states, key_states, value_states, attention_mask, query_length
|
335 |
+
)
|
336 |
+
|
337 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
338 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
339 |
+
|
340 |
+
if not use_sliding_windows:
|
341 |
+
attn_output_unpad = flash_attn_varlen_func(
|
342 |
+
query_states,
|
343 |
+
key_states,
|
344 |
+
value_states,
|
345 |
+
cu_seqlens_q=cu_seqlens_q,
|
346 |
+
cu_seqlens_k=cu_seqlens_k,
|
347 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
348 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
349 |
+
dropout_p=dropout,
|
350 |
+
softmax_scale=softmax_scale,
|
351 |
+
causal=self.is_causal,
|
352 |
+
)
|
353 |
+
else:
|
354 |
+
attn_output_unpad = flash_attn_varlen_func(
|
355 |
+
query_states,
|
356 |
+
key_states,
|
357 |
+
value_states,
|
358 |
+
cu_seqlens_q=cu_seqlens_q,
|
359 |
+
cu_seqlens_k=cu_seqlens_k,
|
360 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
361 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
362 |
+
dropout_p=dropout,
|
363 |
+
softmax_scale=softmax_scale,
|
364 |
+
causal=self.is_causal,
|
365 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
366 |
+
)
|
367 |
+
|
368 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
369 |
+
else:
|
370 |
+
if not use_sliding_windows:
|
371 |
+
attn_output = flash_attn_func(
|
372 |
+
query_states,
|
373 |
+
key_states,
|
374 |
+
value_states,
|
375 |
+
dropout,
|
376 |
+
softmax_scale=softmax_scale,
|
377 |
+
causal=self.is_causal,
|
378 |
+
)
|
379 |
+
else:
|
380 |
+
attn_output = flash_attn_func(
|
381 |
+
query_states,
|
382 |
+
key_states,
|
383 |
+
value_states,
|
384 |
+
dropout,
|
385 |
+
softmax_scale=softmax_scale,
|
386 |
+
causal=self.is_causal,
|
387 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
388 |
+
)
|
389 |
+
|
390 |
+
return attn_output
|
391 |
+
|
392 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
393 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
394 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
395 |
+
|
396 |
+
key_layer = index_first_axis(
|
397 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
398 |
+
)
|
399 |
+
value_layer = index_first_axis(
|
400 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
401 |
+
)
|
402 |
+
if query_length == kv_seq_len:
|
403 |
+
query_layer = index_first_axis(
|
404 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
405 |
+
)
|
406 |
+
cu_seqlens_q = cu_seqlens_k
|
407 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
408 |
+
indices_q = indices_k
|
409 |
+
elif query_length == 1:
|
410 |
+
max_seqlen_in_batch_q = 1
|
411 |
+
cu_seqlens_q = torch.arange(
|
412 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
413 |
+
) # There is a memcpy here, that is very bad.
|
414 |
+
indices_q = cu_seqlens_q[:-1]
|
415 |
+
query_layer = query_layer.squeeze(1)
|
416 |
+
else:
|
417 |
+
# The -q_len: slice assumes left padding.
|
418 |
+
attention_mask = attention_mask[:, -query_length:]
|
419 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
420 |
+
|
421 |
+
return (
|
422 |
+
query_layer,
|
423 |
+
key_layer,
|
424 |
+
value_layer,
|
425 |
+
indices_q,
|
426 |
+
(cu_seqlens_q, cu_seqlens_k),
|
427 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
428 |
+
)
|
429 |
+
|
430 |
+
|
431 |
+
class PerceiverLayer(nn.Module):
|
432 |
+
def __init__(self, config):
|
433 |
+
super().__init__()
|
434 |
+
self.config = config
|
435 |
+
self.hidden_size = config.hidden_size
|
436 |
+
self.hidden_act = config.perceiver_config.hidden_act
|
437 |
+
self.n_latents = config.perceiver_config.resampler_n_latents
|
438 |
+
self.depth = config.perceiver_config.resampler_depth
|
439 |
+
self.rms_norm_eps = config.rms_norm_eps
|
440 |
+
self.intermediate_size = self.hidden_size * 4
|
441 |
+
|
442 |
+
self.input_latents_norm = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
|
443 |
+
self.input_context_norm = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
|
444 |
+
self.self_attn = (
|
445 |
+
PerceiverAttention(config)
|
446 |
+
if not getattr(config, "_flash_attn_2_enabled", False)
|
447 |
+
else PerceiverFlashAttention2(config)
|
448 |
+
)
|
449 |
+
self.post_attention_layernorm = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
|
450 |
+
self.mlp = MLP(
|
451 |
+
activation=self.hidden_act,
|
452 |
+
input_size=self.hidden_size,
|
453 |
+
intermediate_size=self.intermediate_size,
|
454 |
+
output_size=self.hidden_size,
|
455 |
+
)
|
456 |
+
|
457 |
+
def forward(
|
458 |
+
self,
|
459 |
+
latents: torch.Tensor,
|
460 |
+
context: torch.Tensor,
|
461 |
+
attention_mask: Optional[torch.Tensor] = None,
|
462 |
+
position_ids: Optional[torch.LongTensor] = None,
|
463 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
464 |
+
output_attentions: Optional[bool] = False,
|
465 |
+
use_cache: Optional[bool] = False,
|
466 |
+
**kwargs,
|
467 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
468 |
+
"""
|
469 |
+
Args:
|
470 |
+
latents (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
471 |
+
context (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
472 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
473 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
474 |
+
output_attentions (`bool`, *optional*):
|
475 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
476 |
+
returned tensors for more detail.
|
477 |
+
use_cache (`bool`, *optional*):
|
478 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
479 |
+
(see `past_key_values`).
|
480 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
481 |
+
"""
|
482 |
+
residual = latents
|
483 |
+
|
484 |
+
latents = self.input_latents_norm(latents)
|
485 |
+
context = self.input_context_norm(context)
|
486 |
+
|
487 |
+
if attention_mask is None:
|
488 |
+
attention_mask = torch.ones(
|
489 |
+
size=(context.size(0), context.size(1)),
|
490 |
+
dtype=torch.bool,
|
491 |
+
device=context.device,
|
492 |
+
)
|
493 |
+
attention_mask = torch.cat(
|
494 |
+
[
|
495 |
+
attention_mask,
|
496 |
+
torch.ones(
|
497 |
+
size=(attention_mask.size(0), latents.size(1)),
|
498 |
+
dtype=attention_mask.dtype,
|
499 |
+
device=attention_mask.device,
|
500 |
+
),
|
501 |
+
],
|
502 |
+
dim=-1,
|
503 |
+
)
|
504 |
+
latents, self_attn_weights, present_key_value = self.self_attn(
|
505 |
+
latents=latents,
|
506 |
+
context=context,
|
507 |
+
attention_mask=(
|
508 |
+
_prepare_4d_attention_mask(attention_mask, latents.dtype, tgt_len=self.n_latents)
|
509 |
+
if not self.config._flash_attn_2_enabled
|
510 |
+
else attention_mask
|
511 |
+
),
|
512 |
+
)
|
513 |
+
latents = residual + latents
|
514 |
+
residual = latents
|
515 |
+
|
516 |
+
latents = self.post_attention_layernorm(latents)
|
517 |
+
latents = self.mlp(latents)
|
518 |
+
latents = residual + latents
|
519 |
+
|
520 |
+
outputs = (latents,)
|
521 |
+
|
522 |
+
if output_attentions:
|
523 |
+
outputs += (self_attn_weights,)
|
524 |
+
|
525 |
+
if use_cache:
|
526 |
+
outputs += (present_key_value,)
|
527 |
+
|
528 |
+
return outputs
|
529 |
+
|
530 |
+
|
531 |
+
class PerceiverResampler(nn.Module):
|
532 |
+
def __init__(
|
533 |
+
self,
|
534 |
+
config,
|
535 |
+
) -> None:
|
536 |
+
"""
|
537 |
+
Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or
|
538 |
+
MAE) of a given dimension, performs `depth` blocks of cross-attention with a fixed `n_latents` inputs, then
|
539 |
+
returns a Tensor of shape [bsz, n_latents, embed_dim].
|
540 |
+
:param embed_dim: Dimensionality of embeddings being fed to the Perceiver Resampler (also dimensionality of
|
541 |
+
latent embeddings *returned* by the Perceiver Resampler. Could be e.g., VIT embed_dim, ResNet
|
542 |
+
pool dim, and so on.
|
543 |
+
:param depth: Depth of the Perceiver Resampler (Transformer w/ cross attention). Should be shallow (< 3).
|
544 |
+
:param n_heads: Number of heads in each Transformer block (for multi-headed self-attention).
|
545 |
+
:param head_dim: Dimensionality of each head projection in the Transformer block.
|
546 |
+
:param n_latents: Number of latent embeddings to resample ("compress") the input sequence to (usually < 128).
|
547 |
+
"""
|
548 |
+
super().__init__()
|
549 |
+
self.config = config
|
550 |
+
self.hidden_size = config.hidden_size
|
551 |
+
self.hidden_act = config.perceiver_config.hidden_act
|
552 |
+
self.n_latents = config.perceiver_config.resampler_n_latents
|
553 |
+
self.depth = config.perceiver_config.resampler_depth
|
554 |
+
self.rms_norm_eps = config.rms_norm_eps
|
555 |
+
|
556 |
+
# Create Latents for Perceiver
|
557 |
+
self.latents = nn.Parameter(torch.ones(self.n_latents, self.hidden_size))
|
558 |
+
|
559 |
+
# Create Transformer Blocks
|
560 |
+
self.layers = nn.ModuleList([PerceiverLayer(config) for _ in range(self.depth)])
|
561 |
+
self.norm = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
|
562 |
+
|
563 |
+
def forward(
|
564 |
+
self,
|
565 |
+
context: torch.Tensor,
|
566 |
+
attention_mask: Optional[torch.Tensor] = None,
|
567 |
+
) -> torch.Tensor:
|
568 |
+
latents = repeat(self.latents, "seq embed -> bsz seq embed", bsz=context.shape[0])
|
569 |
+
|
570 |
+
for perceiver_layer in self.layers:
|
571 |
+
layer_outputs = perceiver_layer(
|
572 |
+
latents,
|
573 |
+
context,
|
574 |
+
attention_mask=attention_mask,
|
575 |
+
position_ids=None,
|
576 |
+
past_key_value=None,
|
577 |
+
output_attentions=False,
|
578 |
+
use_cache=False,
|
579 |
+
)
|
580 |
+
|
581 |
+
latents = layer_outputs[0]
|
582 |
+
|
583 |
+
latents = self.norm(latents)
|
584 |
+
|
585 |
+
return latents
|
preprocessor_config.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoProcessor": "IdeficsProcessor",
|
4 |
+
"AutoImageProcessor": "IdeficsImageProcessor"
|
5 |
+
},
|
6 |
+
"image_num_channels": 3,
|
7 |
+
"image_mean": [
|
8 |
+
0.5,
|
9 |
+
0.5,
|
10 |
+
0.5
|
11 |
+
],
|
12 |
+
"image_processor_type": "IdeficsImageProcessor",
|
13 |
+
"image_size": 980,
|
14 |
+
"image_std": [
|
15 |
+
0.5,
|
16 |
+
0.5,
|
17 |
+
0.5
|
18 |
+
],
|
19 |
+
"processor_class": "IdeficsProcessor"
|
20 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
{
|
4 |
+
"content": "<fake_token_around_image>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
},
|
10 |
+
{
|
11 |
+
"content": "<image>",
|
12 |
+
"lstrip": false,
|
13 |
+
"normalized": false,
|
14 |
+
"rstrip": false,
|
15 |
+
"single_word": false
|
16 |
+
}
|
17 |
+
],
|
18 |
+
"bos_token": {
|
19 |
+
"content": "<s>",
|
20 |
+
"lstrip": false,
|
21 |
+
"normalized": false,
|
22 |
+
"rstrip": false,
|
23 |
+
"single_word": false
|
24 |
+
},
|
25 |
+
"eos_token": {
|
26 |
+
"content": "</s>",
|
27 |
+
"lstrip": false,
|
28 |
+
"normalized": false,
|
29 |
+
"rstrip": false,
|
30 |
+
"single_word": false
|
31 |
+
},
|
32 |
+
"pad_token": {
|
33 |
+
"content": "<unk>",
|
34 |
+
"lstrip": false,
|
35 |
+
"normalized": false,
|
36 |
+
"rstrip": false,
|
37 |
+
"single_word": false
|
38 |
+
},
|
39 |
+
"unk_token": {
|
40 |
+
"content": "<unk>",
|
41 |
+
"lstrip": false,
|
42 |
+
"normalized": false,
|
43 |
+
"rstrip": false,
|
44 |
+
"single_word": false
|
45 |
+
}
|
46 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dadfd56d766715c61d2ef780a525ab43b8e6da4de6865bda3d95fdef5e134055
|
3 |
+
size 493443
|
tokenizer_config.json
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"0": {
|
6 |
+
"content": "<unk>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"1": {
|
14 |
+
"content": "<s>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"2": {
|
22 |
+
"content": "</s>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"32000": {
|
30 |
+
"content": "<fake_token_around_image>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"32001": {
|
38 |
+
"content": "<image>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
}
|
45 |
+
},
|
46 |
+
"additional_special_tokens": [
|
47 |
+
"<fake_token_around_image>",
|
48 |
+
"<image>"
|
49 |
+
],
|
50 |
+
"bos_token": "<s>",
|
51 |
+
"clean_up_tokenization_spaces": false,
|
52 |
+
"eos_token": "</s>",
|
53 |
+
"legacy": false,
|
54 |
+
"model_max_length": 1000000000000000019884624838656,
|
55 |
+
"pad_token": "<unk>",
|
56 |
+
"sp_model_kwargs": {},
|
57 |
+
"spaces_between_special_tokens": false,
|
58 |
+
"tokenizer_class": "LlamaTokenizer",
|
59 |
+
"unk_token": "<unk>",
|
60 |
+
"use_default_system_prompt": true
|
61 |
+
}
|
vision.py
ADDED
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Google AI and The HuggingFace 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 |
+
""" A simplified copy of https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit which is a siglip modified to allow variable size and image ratio preserving images. """
|
16 |
+
|
17 |
+
|
18 |
+
from dataclasses import dataclass
|
19 |
+
from typing import Any, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from transformers.activations import ACT2FN
|
26 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
27 |
+
from transformers.modeling_outputs import BaseModelOutput
|
28 |
+
from transformers.utils import (
|
29 |
+
ModelOutput,
|
30 |
+
is_flash_attn_2_available,
|
31 |
+
logging,
|
32 |
+
)
|
33 |
+
from .configuration_idefics2 import Idefics2VisionConfig
|
34 |
+
|
35 |
+
|
36 |
+
logger = logging.get_logger(__name__)
|
37 |
+
|
38 |
+
|
39 |
+
if is_flash_attn_2_available():
|
40 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
41 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
42 |
+
|
43 |
+
|
44 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
45 |
+
def _get_unpad_data(attention_mask):
|
46 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
47 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
48 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
49 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
50 |
+
return (
|
51 |
+
indices,
|
52 |
+
cu_seqlens,
|
53 |
+
max_seqlen_in_batch,
|
54 |
+
)
|
55 |
+
|
56 |
+
|
57 |
+
class SiglipVisionEmbeddings(nn.Module):
|
58 |
+
def __init__(self, config: Idefics2VisionConfig):
|
59 |
+
super().__init__()
|
60 |
+
self.config = config
|
61 |
+
self.embed_dim = config.hidden_size
|
62 |
+
self.image_size = config.image_size
|
63 |
+
self.patch_size = config.patch_size
|
64 |
+
|
65 |
+
self.patch_embedding = nn.Conv2d(
|
66 |
+
in_channels=config.num_channels,
|
67 |
+
out_channels=self.embed_dim,
|
68 |
+
kernel_size=self.patch_size,
|
69 |
+
stride=self.patch_size,
|
70 |
+
padding="valid",
|
71 |
+
)
|
72 |
+
|
73 |
+
self.num_patches_per_side = self.image_size // self.patch_size
|
74 |
+
self.num_patches = self.num_patches_per_side**2
|
75 |
+
self.num_positions = self.num_patches
|
76 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
77 |
+
|
78 |
+
def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor:
|
79 |
+
batch_size = pixel_values.size(0)
|
80 |
+
|
81 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
82 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
83 |
+
|
84 |
+
max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
|
85 |
+
max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
|
86 |
+
boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
|
87 |
+
position_ids = torch.full(
|
88 |
+
size=(
|
89 |
+
batch_size,
|
90 |
+
max_nb_patches_h * max_nb_patches_w,
|
91 |
+
),
|
92 |
+
fill_value=0,
|
93 |
+
)
|
94 |
+
|
95 |
+
for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
|
96 |
+
nb_patches_h = p_attn_mask[:, 0].sum()
|
97 |
+
nb_patches_w = p_attn_mask[0].sum()
|
98 |
+
|
99 |
+
fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
|
100 |
+
fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
|
101 |
+
|
102 |
+
bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
|
103 |
+
bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
|
104 |
+
|
105 |
+
pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
|
106 |
+
position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
|
107 |
+
|
108 |
+
position_ids = position_ids.to(self.position_embedding.weight.device)
|
109 |
+
|
110 |
+
embeddings = embeddings + self.position_embedding(position_ids)
|
111 |
+
return embeddings
|
112 |
+
|
113 |
+
|
114 |
+
class SiglipAttention(nn.Module):
|
115 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
116 |
+
|
117 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
|
118 |
+
def __init__(self, config):
|
119 |
+
super().__init__()
|
120 |
+
self.config = config
|
121 |
+
self.embed_dim = config.hidden_size
|
122 |
+
self.num_heads = config.num_attention_heads
|
123 |
+
self.head_dim = self.embed_dim // self.num_heads
|
124 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
125 |
+
raise ValueError(
|
126 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
127 |
+
f" {self.num_heads})."
|
128 |
+
)
|
129 |
+
self.scale = self.head_dim**-0.5
|
130 |
+
self.dropout = config.attention_dropout
|
131 |
+
|
132 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
133 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
134 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
135 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
136 |
+
|
137 |
+
def forward(
|
138 |
+
self,
|
139 |
+
hidden_states: torch.Tensor,
|
140 |
+
attention_mask: Optional[torch.Tensor] = None,
|
141 |
+
output_attentions: Optional[bool] = False,
|
142 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
143 |
+
"""Input shape: Batch x Time x Channel"""
|
144 |
+
|
145 |
+
batch_size, q_len, _ = hidden_states.size()
|
146 |
+
|
147 |
+
query_states = self.q_proj(hidden_states)
|
148 |
+
key_states = self.k_proj(hidden_states)
|
149 |
+
value_states = self.v_proj(hidden_states)
|
150 |
+
|
151 |
+
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
152 |
+
key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
153 |
+
value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
154 |
+
|
155 |
+
k_v_seq_len = key_states.shape[-2]
|
156 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
|
157 |
+
|
158 |
+
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
|
159 |
+
raise ValueError(
|
160 |
+
f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
|
161 |
+
f" {attn_weights.size()}"
|
162 |
+
)
|
163 |
+
|
164 |
+
if attention_mask is not None:
|
165 |
+
if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
|
166 |
+
raise ValueError(
|
167 |
+
f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
|
168 |
+
)
|
169 |
+
attn_weights = attn_weights + attention_mask
|
170 |
+
|
171 |
+
# upcast attention to fp32
|
172 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
173 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
174 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
175 |
+
|
176 |
+
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
|
177 |
+
raise ValueError(
|
178 |
+
f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
|
179 |
+
f" {attn_output.size()}"
|
180 |
+
)
|
181 |
+
|
182 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
183 |
+
attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
|
184 |
+
|
185 |
+
attn_output = self.out_proj(attn_output)
|
186 |
+
|
187 |
+
return attn_output, attn_weights
|
188 |
+
|
189 |
+
|
190 |
+
class SiglipFlashAttention2(SiglipAttention):
|
191 |
+
"""
|
192 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
193 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
194 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
195 |
+
"""
|
196 |
+
|
197 |
+
def __init__(self, *args, **kwargs):
|
198 |
+
super().__init__(*args, **kwargs)
|
199 |
+
self.is_causal = False # Hack to make sure we don't use a causal mask
|
200 |
+
|
201 |
+
def forward(
|
202 |
+
self,
|
203 |
+
hidden_states: torch.Tensor,
|
204 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
205 |
+
position_ids: Optional[torch.LongTensor] = None,
|
206 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
207 |
+
output_attentions: bool = False,
|
208 |
+
use_cache: bool = False,
|
209 |
+
**kwargs,
|
210 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
211 |
+
output_attentions = False
|
212 |
+
|
213 |
+
bsz, q_len, _ = hidden_states.size()
|
214 |
+
|
215 |
+
query_states = self.q_proj(hidden_states)
|
216 |
+
key_states = self.k_proj(hidden_states)
|
217 |
+
value_states = self.v_proj(hidden_states)
|
218 |
+
|
219 |
+
# Flash attention requires the input to have the shape
|
220 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
221 |
+
# therefore we just need to keep the original shape
|
222 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
223 |
+
key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
224 |
+
value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
225 |
+
|
226 |
+
kv_seq_len = key_states.shape[-2]
|
227 |
+
if past_key_value is not None:
|
228 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
229 |
+
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
230 |
+
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
231 |
+
|
232 |
+
# if past_key_value is not None:
|
233 |
+
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
234 |
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
235 |
+
|
236 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
237 |
+
# to be able to avoid many of these transpose/reshape/view.
|
238 |
+
query_states = query_states.transpose(1, 2)
|
239 |
+
key_states = key_states.transpose(1, 2)
|
240 |
+
value_states = value_states.transpose(1, 2)
|
241 |
+
|
242 |
+
dropout_rate = self.dropout if self.training else 0.0
|
243 |
+
|
244 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
245 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
246 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
247 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
248 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
249 |
+
|
250 |
+
input_dtype = query_states.dtype
|
251 |
+
if input_dtype == torch.float32:
|
252 |
+
if torch.is_autocast_enabled():
|
253 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
254 |
+
# Handle the case where the model is quantized
|
255 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
256 |
+
target_dtype = self.config._pre_quantization_dtype
|
257 |
+
else:
|
258 |
+
target_dtype = self.q_proj.weight.dtype
|
259 |
+
|
260 |
+
logger.warning_once(
|
261 |
+
"The input hidden states seems to be silently casted in float32, this might be related to the fact"
|
262 |
+
" you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
263 |
+
f" {target_dtype}."
|
264 |
+
)
|
265 |
+
|
266 |
+
query_states = query_states.to(target_dtype)
|
267 |
+
key_states = key_states.to(target_dtype)
|
268 |
+
value_states = value_states.to(target_dtype)
|
269 |
+
|
270 |
+
attn_output = self._flash_attention_forward(
|
271 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
272 |
+
)
|
273 |
+
|
274 |
+
attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
|
275 |
+
attn_output = self.out_proj(attn_output)
|
276 |
+
|
277 |
+
if not output_attentions:
|
278 |
+
attn_weights = None
|
279 |
+
|
280 |
+
return attn_output, attn_weights
|
281 |
+
|
282 |
+
def _flash_attention_forward(
|
283 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
284 |
+
):
|
285 |
+
"""
|
286 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
287 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
288 |
+
|
289 |
+
Args:
|
290 |
+
query_states (`torch.Tensor`):
|
291 |
+
Input query states to be passed to Flash Attention API
|
292 |
+
key_states (`torch.Tensor`):
|
293 |
+
Input key states to be passed to Flash Attention API
|
294 |
+
value_states (`torch.Tensor`):
|
295 |
+
Input value states to be passed to Flash Attention API
|
296 |
+
attention_mask (`torch.Tensor`):
|
297 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
298 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
299 |
+
dropout (`int`, *optional*):
|
300 |
+
Attention dropout
|
301 |
+
softmax_scale (`float`, *optional*):
|
302 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
303 |
+
"""
|
304 |
+
|
305 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
306 |
+
causal = self.is_causal and query_length != 1
|
307 |
+
|
308 |
+
# Contains at least one padding token in the sequence
|
309 |
+
if attention_mask is not None:
|
310 |
+
batch_size = query_states.shape[0]
|
311 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
312 |
+
query_states, key_states, value_states, attention_mask, query_length
|
313 |
+
)
|
314 |
+
|
315 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
316 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
317 |
+
|
318 |
+
attn_output_unpad = flash_attn_varlen_func(
|
319 |
+
query_states,
|
320 |
+
key_states,
|
321 |
+
value_states,
|
322 |
+
cu_seqlens_q=cu_seqlens_q,
|
323 |
+
cu_seqlens_k=cu_seqlens_k,
|
324 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
325 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
326 |
+
dropout_p=dropout,
|
327 |
+
softmax_scale=softmax_scale,
|
328 |
+
causal=causal,
|
329 |
+
)
|
330 |
+
|
331 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
332 |
+
else:
|
333 |
+
attn_output = flash_attn_func(
|
334 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
335 |
+
)
|
336 |
+
|
337 |
+
return attn_output
|
338 |
+
|
339 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
340 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
341 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
342 |
+
|
343 |
+
key_layer = index_first_axis(
|
344 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
345 |
+
)
|
346 |
+
value_layer = index_first_axis(
|
347 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
348 |
+
)
|
349 |
+
if query_length == kv_seq_len:
|
350 |
+
query_layer = index_first_axis(
|
351 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
352 |
+
)
|
353 |
+
cu_seqlens_q = cu_seqlens_k
|
354 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
355 |
+
indices_q = indices_k
|
356 |
+
elif query_length == 1:
|
357 |
+
max_seqlen_in_batch_q = 1
|
358 |
+
cu_seqlens_q = torch.arange(
|
359 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
360 |
+
) # There is a memcpy here, that is very bad.
|
361 |
+
indices_q = cu_seqlens_q[:-1]
|
362 |
+
query_layer = query_layer.squeeze(1)
|
363 |
+
else:
|
364 |
+
# The -q_len: slice assumes left padding.
|
365 |
+
attention_mask = attention_mask[:, -query_length:]
|
366 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
367 |
+
|
368 |
+
return (
|
369 |
+
query_layer,
|
370 |
+
key_layer,
|
371 |
+
value_layer,
|
372 |
+
indices_q,
|
373 |
+
(cu_seqlens_q, cu_seqlens_k),
|
374 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
375 |
+
)
|
376 |
+
|
377 |
+
|
378 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
|
379 |
+
class SiglipMLP(nn.Module):
|
380 |
+
def __init__(self, config):
|
381 |
+
super().__init__()
|
382 |
+
self.config = config
|
383 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
384 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
385 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
386 |
+
|
387 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
388 |
+
hidden_states = self.fc1(hidden_states)
|
389 |
+
hidden_states = self.activation_fn(hidden_states)
|
390 |
+
hidden_states = self.fc2(hidden_states)
|
391 |
+
return hidden_states
|
392 |
+
|
393 |
+
|
394 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
|
395 |
+
class SiglipEncoderLayer(nn.Module):
|
396 |
+
def __init__(self, config: Idefics2VisionConfig):
|
397 |
+
super().__init__()
|
398 |
+
self.embed_dim = config.hidden_size
|
399 |
+
self.self_attn = (
|
400 |
+
SiglipAttention(config)
|
401 |
+
if not getattr(config, "_flash_attn_2_enabled", False)
|
402 |
+
else SiglipFlashAttention2(config)
|
403 |
+
)
|
404 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
405 |
+
self.mlp = SiglipMLP(config)
|
406 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
407 |
+
|
408 |
+
def forward(
|
409 |
+
self,
|
410 |
+
hidden_states: torch.Tensor,
|
411 |
+
attention_mask: torch.Tensor,
|
412 |
+
output_attentions: Optional[bool] = False,
|
413 |
+
) -> Tuple[torch.FloatTensor]:
|
414 |
+
"""
|
415 |
+
Args:
|
416 |
+
hidden_states (`torch.FloatTensor`):
|
417 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
418 |
+
attention_mask (`torch.FloatTensor`):
|
419 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
420 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
421 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
422 |
+
returned tensors for more detail.
|
423 |
+
"""
|
424 |
+
residual = hidden_states
|
425 |
+
|
426 |
+
hidden_states = self.layer_norm1(hidden_states)
|
427 |
+
hidden_states, attn_weights = self.self_attn(
|
428 |
+
hidden_states=hidden_states,
|
429 |
+
attention_mask=attention_mask,
|
430 |
+
output_attentions=output_attentions,
|
431 |
+
)
|
432 |
+
hidden_states = residual + hidden_states
|
433 |
+
|
434 |
+
residual = hidden_states
|
435 |
+
hidden_states = self.layer_norm2(hidden_states)
|
436 |
+
hidden_states = self.mlp(hidden_states)
|
437 |
+
hidden_states = residual + hidden_states
|
438 |
+
|
439 |
+
outputs = (hidden_states,)
|
440 |
+
|
441 |
+
if output_attentions:
|
442 |
+
outputs += (attn_weights,)
|
443 |
+
|
444 |
+
return outputs
|
445 |
+
|
446 |
+
|
447 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
|
448 |
+
class SiglipEncoder(nn.Module):
|
449 |
+
"""
|
450 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
451 |
+
[`SiglipEncoderLayer`].
|
452 |
+
|
453 |
+
Args:
|
454 |
+
config: Idefics2VisionConfig
|
455 |
+
"""
|
456 |
+
|
457 |
+
def __init__(self, config: Idefics2VisionConfig):
|
458 |
+
super().__init__()
|
459 |
+
self.config = config
|
460 |
+
self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
461 |
+
self.gradient_checkpointing = False
|
462 |
+
|
463 |
+
def forward(
|
464 |
+
self,
|
465 |
+
inputs_embeds,
|
466 |
+
attention_mask: Optional[torch.Tensor] = None,
|
467 |
+
output_attentions: Optional[bool] = None,
|
468 |
+
output_hidden_states: Optional[bool] = None,
|
469 |
+
return_dict: Optional[bool] = None,
|
470 |
+
) -> Union[Tuple, BaseModelOutput]:
|
471 |
+
r"""
|
472 |
+
Args:
|
473 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
474 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
475 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
476 |
+
than the model's internal embedding lookup matrix.
|
477 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
478 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
479 |
+
|
480 |
+
- 1 for tokens that are **not masked**,
|
481 |
+
- 0 for tokens that are **masked**.
|
482 |
+
|
483 |
+
[What are attention masks?](../glossary#attention-mask)
|
484 |
+
output_attentions (`bool`, *optional*):
|
485 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
486 |
+
returned tensors for more detail.
|
487 |
+
output_hidden_states (`bool`, *optional*):
|
488 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
489 |
+
for more detail.
|
490 |
+
return_dict (`bool`, *optional*):
|
491 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
492 |
+
"""
|
493 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
494 |
+
output_hidden_states = (
|
495 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
496 |
+
)
|
497 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
498 |
+
|
499 |
+
encoder_states = () if output_hidden_states else None
|
500 |
+
all_attentions = () if output_attentions else None
|
501 |
+
|
502 |
+
hidden_states = inputs_embeds
|
503 |
+
for encoder_layer in self.layers:
|
504 |
+
if output_hidden_states:
|
505 |
+
encoder_states = encoder_states + (hidden_states,)
|
506 |
+
if self.gradient_checkpointing and self.training:
|
507 |
+
layer_outputs = self._gradient_checkpointing_func(
|
508 |
+
encoder_layer.__call__,
|
509 |
+
hidden_states,
|
510 |
+
attention_mask,
|
511 |
+
output_attentions,
|
512 |
+
)
|
513 |
+
else:
|
514 |
+
layer_outputs = encoder_layer(
|
515 |
+
hidden_states,
|
516 |
+
attention_mask,
|
517 |
+
output_attentions=output_attentions,
|
518 |
+
)
|
519 |
+
|
520 |
+
hidden_states = layer_outputs[0]
|
521 |
+
|
522 |
+
if output_attentions:
|
523 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
524 |
+
|
525 |
+
if output_hidden_states:
|
526 |
+
encoder_states = encoder_states + (hidden_states,)
|
527 |
+
|
528 |
+
if not return_dict:
|
529 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
530 |
+
return BaseModelOutput(
|
531 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
532 |
+
)
|
533 |
+
|
534 |
+
|
535 |
+
class SiglipVisionTransformer(nn.Module):
|
536 |
+
def __init__(self, config: Idefics2VisionConfig):
|
537 |
+
super().__init__()
|
538 |
+
self.config = config
|
539 |
+
embed_dim = config.hidden_size
|
540 |
+
|
541 |
+
self.embeddings = SiglipVisionEmbeddings(config)
|
542 |
+
self.encoder = SiglipEncoder(config)
|
543 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
544 |
+
|
545 |
+
def forward(
|
546 |
+
self,
|
547 |
+
pixel_values,
|
548 |
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
549 |
+
output_attentions: Optional[bool] = None,
|
550 |
+
output_hidden_states: Optional[bool] = None,
|
551 |
+
return_dict: Optional[bool] = None,
|
552 |
+
) -> Union[Tuple, BaseModelOutput]:
|
553 |
+
r"""
|
554 |
+
Returns:
|
555 |
+
|
556 |
+
"""
|
557 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
558 |
+
output_hidden_states = (
|
559 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
560 |
+
)
|
561 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
562 |
+
|
563 |
+
batch_size = pixel_values.size(0)
|
564 |
+
if patch_attention_mask is None:
|
565 |
+
patch_attention_mask = torch.ones(
|
566 |
+
size=(
|
567 |
+
batch_size,
|
568 |
+
pixel_values.size(2) // self.config.patch_size,
|
569 |
+
pixel_values.size(3) // self.config.patch_size,
|
570 |
+
),
|
571 |
+
dtype=torch.bool,
|
572 |
+
device=pixel_values.device,
|
573 |
+
)
|
574 |
+
|
575 |
+
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
|
576 |
+
|
577 |
+
patch_attention_mask = patch_attention_mask.view(batch_size, -1)
|
578 |
+
# The call to `_upad_input` in `_flash_attention_forward` is expensive
|
579 |
+
# So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
|
580 |
+
# avoiding passing the attention_mask, which is equivalent to attending to the full sequence
|
581 |
+
if not torch.any(~patch_attention_mask):
|
582 |
+
attention_mask=None
|
583 |
+
else:
|
584 |
+
attention_mask = (
|
585 |
+
_prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
|
586 |
+
if not self.config._flash_attn_2_enabled
|
587 |
+
else patch_attention_mask
|
588 |
+
)
|
589 |
+
|
590 |
+
encoder_outputs = self.encoder(
|
591 |
+
inputs_embeds=hidden_states,
|
592 |
+
attention_mask=attention_mask,
|
593 |
+
output_attentions=output_attentions,
|
594 |
+
output_hidden_states=output_hidden_states,
|
595 |
+
return_dict=return_dict,
|
596 |
+
)
|
597 |
+
|
598 |
+
last_hidden_state = encoder_outputs[0]
|
599 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
600 |
+
|
601 |
+
if not return_dict:
|
602 |
+
return (last_hidden_state,) + encoder_outputs[1:]
|
603 |
+
|
604 |
+
return BaseModelOutput(
|
605 |
+
last_hidden_state=last_hidden_state,
|
606 |
+
hidden_states=encoder_outputs.hidden_states,
|
607 |
+
attentions=encoder_outputs.attentions,
|
608 |
+
)
|
609 |
+
|
610 |
+
|
611 |
+
class SiglipVisionModel(nn.Module):
|
612 |
+
def __init__(self, config: Idefics2VisionConfig):
|
613 |
+
super().__init__()
|
614 |
+
|
615 |
+
self.config = config
|
616 |
+
self.vision_model = SiglipVisionTransformer(config)
|
617 |
+
|
618 |
+
def forward(
|
619 |
+
self,
|
620 |
+
pixel_values,
|
621 |
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
622 |
+
output_attentions: Optional[bool] = None,
|
623 |
+
output_hidden_states: Optional[bool] = None,
|
624 |
+
return_dict: Optional[bool] = None,
|
625 |
+
) -> Union[Tuple, BaseModelOutput]:
|
626 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
627 |
+
|
628 |
+
return self.vision_model(
|
629 |
+
pixel_values=pixel_values,
|
630 |
+
patch_attention_mask=patch_attention_mask,
|
631 |
+
output_attentions=output_attentions,
|
632 |
+
output_hidden_states=output_hidden_states,
|
633 |
+
return_dict=return_dict,
|
634 |
+
)
|