jasonfan commited on
Commit
f0d6538
·
verified ·
1 Parent(s): ba3ff47

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. models/Phi-4-multimodal-instruct/model.safetensors.index.json +0 -0
  2. models/Phi-4-multimodal-instruct/modeling_phi4mm.py +0 -0
  3. models/Phi-4-multimodal-instruct/preprocessor_config.json +14 -0
  4. models/Phi-4-multimodal-instruct/processing_phi4mm.py +733 -0
  5. models/Phi-4-multimodal-instruct/processor_config.json +6 -0
  6. models/Phi-4-multimodal-instruct/sample_finetune_speech.py +478 -0
  7. models/Phi-4-multimodal-instruct/sample_finetune_vision.py +556 -0
  8. models/Phi-4-multimodal-instruct/sample_inference_phi4mm.py +243 -0
  9. models/Phi-4-multimodal-instruct/special_tokens_map.json +24 -0
  10. models/Phi-4-multimodal-instruct/speech-lora/adapter_config.json +23 -0
  11. models/Phi-4-multimodal-instruct/speech-lora/added_tokens.json +12 -0
  12. models/Phi-4-multimodal-instruct/speech-lora/special_tokens_map.json +24 -0
  13. models/Phi-4-multimodal-instruct/speech-lora/tokenizer_config.json +125 -0
  14. models/Phi-4-multimodal-instruct/speech-lora/vocab.json +0 -0
  15. models/Phi-4-multimodal-instruct/speech_conformer_encoder.py +0 -0
  16. models/Phi-4-multimodal-instruct/tokenizer_config.json +125 -0
  17. models/Phi-4-multimodal-instruct/vision-lora/adapter_config.json +23 -0
  18. models/Phi-4-multimodal-instruct/vision-lora/added_tokens.json +12 -0
  19. models/Phi-4-multimodal-instruct/vision-lora/special_tokens_map.json +24 -0
  20. models/Phi-4-multimodal-instruct/vision-lora/tokenizer_config.json +125 -0
  21. models/Phi-4-multimodal-instruct/vision-lora/vocab.json +0 -0
  22. models/Phi-4-multimodal-instruct/vision_siglip_navit.py +1717 -0
  23. models/Phi-4-multimodal-instruct/vocab.json +0 -0
  24. models/Pixtral-12B-2409/.gitattributes +36 -0
  25. models/Pixtral-12B-2409/README.md +294 -0
  26. models/Pixtral-12B-2409/params.json +25 -0
  27. models/Qwen2-VL-7B-Instruct/.gitattributes +35 -0
  28. models/Qwen2-VL-7B-Instruct/LICENSE +202 -0
  29. models/Qwen2-VL-7B-Instruct/README.md +502 -0
  30. models/Qwen2-VL-7B-Instruct/chat_template.json +3 -0
  31. models/Qwen2-VL-7B-Instruct/config.json +52 -0
  32. models/Qwen2-VL-7B-Instruct/generation_config.json +14 -0
  33. models/Qwen2-VL-7B-Instruct/merges.txt +0 -0
  34. models/Qwen2-VL-7B-Instruct/model.safetensors.index.json +737 -0
  35. models/Qwen2-VL-7B-Instruct/preprocessor_config.json +19 -0
  36. models/Qwen2-VL-7B-Instruct/tokenizer.json +0 -0
  37. models/Qwen2-VL-7B-Instruct/tokenizer_config.json +129 -0
  38. models/Qwen2-VL-7B-Instruct/vocab.json +0 -0
  39. models/SmolVLM-Instruct/.gitattributes +37 -0
  40. models/SmolVLM-Instruct/README.md +191 -0
  41. models/SmolVLM-Instruct/added_tokens.json +5 -0
  42. models/SmolVLM-Instruct/chat_template.json +3 -0
  43. models/SmolVLM-Instruct/config.json +267 -0
  44. models/SmolVLM-Instruct/generation_config.json +7 -0
  45. models/SmolVLM-Instruct/merges.txt +0 -0
  46. models/SmolVLM-Instruct/preprocessor_config.json +28 -0
  47. models/SmolVLM-Instruct/processor_config.json +4 -0
  48. models/SmolVLM-Instruct/smolvlm-data.pdf +0 -0
  49. models/SmolVLM-Instruct/special_tokens_map.json +53 -0
  50. models/SmolVLM-Instruct/tokenizer.json +0 -0
models/Phi-4-multimodal-instruct/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
models/Phi-4-multimodal-instruct/modeling_phi4mm.py ADDED
The diff for this file is too large to render. See raw diff
 
models/Phi-4-multimodal-instruct/preprocessor_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_phi4mm.Phi4MMProcessor",
4
+ "AutoImageProcessor": "processing_phi4mm.Phi4MMImageProcessor",
5
+ "AutoFeatureExtractor": "processing_phi4mm.Phi4MMAudioFeatureExtractor"
6
+ },
7
+ "image_processor_type": "Phi4MMImageProcessor",
8
+ "processor_class": "Phi4MMProcessor",
9
+ "feature_extractor_type": "Phi4MMAudioFeatureExtractor",
10
+ "audio_compression_rate": 8,
11
+ "audio_downsample_rate": 1,
12
+ "audio_feat_stride": 1,
13
+ "dynamic_hd": 36
14
+ }
models/Phi-4-multimodal-instruct/processing_phi4mm.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Processor class for Phi4MM
17
+ """
18
+ import re
19
+ from typing import List, Optional, Tuple, Union
20
+ import math
21
+ from enum import Enum
22
+
23
+ import numpy as np
24
+ import scipy
25
+ import torch
26
+ import torchvision
27
+
28
+ from transformers import AutoFeatureExtractor, AutoImageProcessor
29
+ from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
30
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
31
+ from transformers.image_utils import (
32
+ ImageInput,
33
+ make_list_of_images,
34
+ valid_images,
35
+ )
36
+ from transformers.processing_utils import ProcessorMixin
37
+ from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
38
+ from transformers.utils import TensorType, logging
39
+ from torch.nn.utils.rnn import pad_sequence
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ # Special tokens
45
+ _COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN = r'<\|image_\d+\|>' # For backward compatibility
46
+ _COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN = r'<\|audio_\d+\|>' # For backward compatibility
47
+ _IMAGE_SPECIAL_TOKEN = '<|endoftext10|>'
48
+ _AUDIO_SPECIAL_TOKEN = '<|endoftext11|>'
49
+ _IMAGE_SPECIAL_TOKEN_ID = 200010 # '<|endoftext10|>', or we can better name it (in `tokenizer_config.json`)
50
+ _AUDIO_SPECIAL_TOKEN_ID = 200011 # '<|endoftext11|>'
51
+
52
+
53
+ class InputMode(Enum):
54
+ LANGUAGE = 0
55
+ VISION = 1
56
+ SPEECH = 2
57
+ VISION_SPEECH = 3
58
+
59
+
60
+ class Phi4MMImageProcessor(BaseImageProcessor):
61
+ r"""
62
+ Constructs a Phi4MM image processor.
63
+ """
64
+ model_input_names = ["input_image_embeds", "image_sizes", "image_attention_mask"]
65
+
66
+ def __init__(
67
+ self,
68
+ dynamic_hd,
69
+ **kwargs,
70
+ ) -> None:
71
+ super().__init__(**kwargs)
72
+ self.dynamic_hd = dynamic_hd
73
+
74
+ def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height, image_size):
75
+ best_ratio_diff = float('inf')
76
+ best_ratio = (1, 1)
77
+ area = width * height
78
+ for ratio in target_ratios:
79
+ target_aspect_ratio = ratio[0] / ratio[1]
80
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
81
+ if ratio_diff < best_ratio_diff:
82
+ best_ratio_diff = ratio_diff
83
+ best_ratio = ratio
84
+ elif ratio_diff == best_ratio_diff:
85
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
86
+ best_ratio = ratio
87
+ return best_ratio
88
+
89
+ def dynamic_preprocess(self, image, min_num=1, max_num=12, image_size=384, mask_size=27, use_thumbnail=True):
90
+ orig_width, orig_height = image.size
91
+
92
+ w_crop_num = math.ceil(orig_width/float(image_size))
93
+ h_crop_num = math.ceil(orig_height/float(image_size))
94
+ if w_crop_num * h_crop_num > max_num:
95
+
96
+ aspect_ratio = orig_width / orig_height
97
+
98
+ # calculate the existing image aspect ratio
99
+ target_ratios = set(
100
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
101
+ i * j <= max_num and i * j >= min_num)
102
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
103
+
104
+ # find the closest aspect ratio to the target
105
+ target_aspect_ratio = self.find_closest_aspect_ratio(
106
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
107
+
108
+ # calculate the target width and height
109
+ target_width = image_size * target_aspect_ratio[0]
110
+ target_height = image_size * target_aspect_ratio[1]
111
+ else:
112
+ target_width = image_size * w_crop_num
113
+ target_height = image_size * h_crop_num
114
+ target_aspect_ratio = (w_crop_num, h_crop_num)
115
+
116
+ # Calculate the ratio
117
+ ratio_width = target_width / orig_width
118
+ ratio_height = target_height / orig_height
119
+ if ratio_width < ratio_height:
120
+ new_size = (target_width, int(orig_height * ratio_width))
121
+ padding_width = 0
122
+ padding_height = target_height - int(orig_height * ratio_width)
123
+ else:
124
+ new_size = (int(orig_width * ratio_height), target_height)
125
+ padding_width = target_width - int(orig_width * ratio_height)
126
+ padding_height = 0
127
+
128
+ attention_mask = torch.ones((int(mask_size*target_aspect_ratio[1]), int(mask_size*target_aspect_ratio[0])))
129
+ if padding_width >= 14:
130
+ attention_mask[:, -math.floor(padding_width/14):] = 0
131
+ if padding_height >= 14:
132
+ attention_mask[-math.floor(padding_height/14):,:] = 0
133
+ assert attention_mask.sum() > 0
134
+
135
+ if min(new_size[1], target_height) < 10 or min(new_size[0], target_width) < 10:
136
+ raise ValueError(f'the aspect ratio is very extreme {new_size}')
137
+
138
+ image = torchvision.transforms.functional.resize(image, [new_size[1], new_size[0]],)
139
+
140
+ resized_img = torchvision.transforms.functional.pad(image, [0, 0, padding_width, padding_height], fill=[255,255,255])
141
+
142
+ return resized_img, attention_mask
143
+
144
+ def pad_to_max_num_crops(self, images, max_crops=5):
145
+ """
146
+ images: B x 3 x H x W, B<=max_crops
147
+ """
148
+ B, _, H, W = images.shape
149
+ if B < max_crops:
150
+ pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
151
+ images = torch.cat([images, pad], dim=0)
152
+ return images
153
+
154
+ def pad_mask_to_max_num_crops(self, masks, max_crops=5):
155
+ B, H, W = masks.shape
156
+ if B < max_crops:
157
+ pad = torch.ones(max_crops - B, H, W, dtype=masks.dtype, device=masks.device)
158
+ masks = torch.cat([masks, pad], dim=0)
159
+ return masks
160
+
161
+ def preprocess(
162
+ self,
163
+ images: ImageInput,
164
+ return_tensors: Optional[Union[str, TensorType]] = None,
165
+ ):
166
+ """
167
+ Args:
168
+ images (`ImageInput`):
169
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
170
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
171
+ return_tensors (`str` or `TensorType`, *optional*):
172
+ The type of tensors to return. Can be one of:
173
+ - Unset: Return a list of `np.ndarray`.
174
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
175
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
176
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
177
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
178
+ """
179
+ images = make_list_of_images(images)
180
+
181
+ if not valid_images(images):
182
+ raise ValueError(
183
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
184
+ "torch.Tensor, tf.Tensor or jax.ndarray."
185
+ )
186
+
187
+ # Basic settings.
188
+ img_processor = torchvision.transforms.Compose([
189
+ torchvision.transforms.ToTensor(),
190
+ torchvision.transforms.Normalize(
191
+ (0.5, 0.5, 0.5),
192
+ (0.5, 0.5, 0.5)
193
+ ),
194
+ ])
195
+ dyhd_base_resolution = 448
196
+
197
+ # Dynamic HD
198
+ base_resolution = dyhd_base_resolution
199
+ images = [image.convert('RGB') for image in images]
200
+ # cover 384 and 448 resolution
201
+ mask_resolution = base_resolution // 14
202
+ elems, image_attention_masks = [], []
203
+ for im in images:
204
+ elem, attention_mask = self.dynamic_preprocess(im, max_num=self.dynamic_hd, image_size=base_resolution, mask_size=mask_resolution)
205
+ elems.append(elem)
206
+ image_attention_masks.append(attention_mask)
207
+ hd_images = [img_processor(im) for im in elems]
208
+ global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(base_resolution, base_resolution), mode='bicubic',).to(im.dtype) for im in hd_images]
209
+ shapes = [[im.size(1), im.size(2)] for im in hd_images]
210
+ mask_shapes = [[mask.size(0), mask.size(1)] for mask in image_attention_masks]
211
+ global_attention_mask = [torch.ones((1, mask_resolution, mask_resolution)) for _ in hd_images]
212
+ hd_images_reshape = [im.reshape(1, 3,
213
+ h//base_resolution,
214
+ base_resolution,
215
+ w//base_resolution,
216
+ base_resolution
217
+ ).permute(0,2,4,1,3,5).reshape(-1, 3, base_resolution, base_resolution).contiguous() for im, (h, w) in zip(hd_images, shapes)]
218
+ attention_masks_reshape = [mask.reshape(1,
219
+ h//mask_resolution,
220
+ mask_resolution,
221
+ w//mask_resolution,
222
+ mask_resolution
223
+ ).permute(0,1,3,2,4).reshape(-1, mask_resolution, mask_resolution).contiguous() for mask, (h, w) in zip(image_attention_masks, mask_shapes)]
224
+ downsample_attention_masks = [mask[:,0::2,0::2].reshape(1,
225
+ h//mask_resolution,
226
+ w//mask_resolution,
227
+ mask_resolution//2+mask_resolution%2,
228
+ mask_resolution//2+mask_resolution%2
229
+ ).permute(0,1,3,2,4) for mask, (h,w) in zip(attention_masks_reshape, mask_shapes)]
230
+ downsample_attention_masks = [mask.reshape(mask.size(1)*mask.size(2), mask.size(3)*mask.size(4))for mask in downsample_attention_masks]
231
+ num_img_tokens = [256 + 1 + int(mask.sum().item()) + int(mask[:,0].sum().item()) + 16 for mask in downsample_attention_masks]
232
+
233
+ hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
234
+ hd_masks_reshape = [torch.cat([_global_mask] + [_mask], dim=0) for _global_mask, _mask in zip(global_attention_mask, attention_masks_reshape)]
235
+ max_crops = max([img.size(0) for img in hd_images_reshape])
236
+ image_transformed = [self.pad_to_max_num_crops(im, max_crops) for im in hd_images_reshape]
237
+ image_transformed = torch.stack(image_transformed, dim=0)
238
+ mask_transformed = [self.pad_mask_to_max_num_crops(mask, max_crops) for mask in hd_masks_reshape]
239
+ mask_transformed = torch.stack(mask_transformed, dim=0)
240
+
241
+ returned_input_image_embeds = image_transformed
242
+ returned_image_sizes = torch.tensor(shapes, dtype=torch.long)
243
+ returned_image_attention_mask = mask_transformed
244
+ returned_num_img_tokens = num_img_tokens
245
+
246
+ data = {
247
+ "input_image_embeds": returned_input_image_embeds,
248
+ "image_sizes": returned_image_sizes,
249
+ "image_attention_mask": returned_image_attention_mask,
250
+ "num_img_tokens": returned_num_img_tokens,
251
+ }
252
+
253
+ return BatchFeature(data=data, tensor_type=return_tensors)
254
+
255
+
256
+ AudioInput = Tuple[Union[np.ndarray, torch.Tensor], int]
257
+ AudioInputs = List[AudioInput]
258
+
259
+
260
+ def speechlib_mel(sample_rate, n_fft, n_mels, fmin=None, fmax=None):
261
+ """Create a Mel filter-bank the same as SpeechLib FbankFC.
262
+
263
+ Args:
264
+ sample_rate (int): Sample rate in Hz. number > 0 [scalar]
265
+ n_fft (int): FFT size. int > 0 [scalar]
266
+ n_mel (int): Mel filter size. int > 0 [scalar]
267
+ fmin (float): lowest frequency (in Hz). If None use 0.0.
268
+ float >= 0 [scalar]
269
+ fmax: highest frequency (in Hz). If None use sample_rate / 2.
270
+ float >= 0 [scalar]
271
+
272
+ Returns
273
+ out (numpy.ndarray): Mel transform matrix
274
+ [shape=(n_mels, 1 + n_fft/2)]
275
+ """
276
+
277
+ bank_width = int(n_fft // 2 + 1)
278
+ if fmax is None:
279
+ fmax = sample_rate / 2
280
+ if fmin is None:
281
+ fmin = 0
282
+ assert fmin >= 0, "fmin cannot be negtive"
283
+ assert fmin < fmax <= sample_rate / 2, "fmax must be between (fmin, samplerate / 2]"
284
+
285
+ def mel(f):
286
+ return 1127.0 * np.log(1.0 + f / 700.0)
287
+
288
+ def bin2mel(fft_bin):
289
+ return 1127.0 * np.log(1.0 + fft_bin * sample_rate / (n_fft * 700.0))
290
+
291
+ def f2bin(f):
292
+ return int((f * n_fft / sample_rate) + 0.5)
293
+
294
+ # Spec 1: FFT bin range [f2bin(fmin) + 1, f2bin(fmax) - 1]
295
+ klo = f2bin(fmin) + 1
296
+ khi = f2bin(fmax)
297
+
298
+ khi = max(khi, klo)
299
+
300
+ # Spec 2: SpeechLib uses trianges in Mel space
301
+ mlo = mel(fmin)
302
+ mhi = mel(fmax)
303
+ m_centers = np.linspace(mlo, mhi, n_mels + 2)
304
+ ms = (mhi - mlo) / (n_mels + 1)
305
+
306
+ matrix = np.zeros((n_mels, bank_width), dtype=np.float32)
307
+ for m in range(0, n_mels):
308
+ left = m_centers[m]
309
+ center = m_centers[m + 1]
310
+ right = m_centers[m + 2]
311
+ for fft_bin in range(klo, khi):
312
+ mbin = bin2mel(fft_bin)
313
+ if left < mbin < right:
314
+ matrix[m, fft_bin] = 1.0 - abs(center - mbin) / ms
315
+
316
+ return matrix
317
+
318
+
319
+ class Phi4MMAudioFeatureExtractor(SequenceFeatureExtractor):
320
+ model_input_names = ["input_audio_embeds", "audio_embed_sizes", "audio_attention_mask"]
321
+
322
+ def __init__(self, audio_compression_rate, audio_downsample_rate, audio_feat_stride, **kwargs):
323
+ feature_size = 80
324
+ sampling_rate = 16000
325
+ padding_value = 0.0
326
+ super().__init__(feature_size, sampling_rate, padding_value, **kwargs)
327
+
328
+ self.compression_rate = audio_compression_rate
329
+ self.qformer_compression_rate = audio_downsample_rate
330
+ self.feat_stride = audio_feat_stride
331
+
332
+ self._eightk_method = "fillzero"
333
+ self._mel = speechlib_mel(16000, 512, 80, fmin=None, fmax=7690).T
334
+
335
+ self._hamming400 = np.hamming(400) # for 16k audio
336
+ self._hamming200 = np.hamming(200) # for 8k audio
337
+
338
+ def duration_to_frames(self, duration):
339
+ """duration in s, estimated frames"""
340
+ frame_rate = 10
341
+
342
+ num_frames = duration * 1000 // frame_rate
343
+ return num_frames
344
+
345
+ def __call__(
346
+ self,
347
+ audios: List[AudioInput],
348
+ return_tensors: Optional[Union[str, TensorType]] = None,
349
+ ):
350
+ # Ref: https://github.com/huggingface/transformers/blob/v4.47.0/src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py#L161
351
+ returned_input_audio_embeds = []
352
+ returned_audio_embed_sizes = []
353
+ audio_frames_list = []
354
+
355
+ for audio_data, sample_rate in audios:
356
+ audio_embeds = self._extract_features(audio_data, sample_rate)
357
+ audio_frames = len(audio_embeds) * self.feat_stride
358
+ audio_embed_size = self._compute_audio_embed_size(audio_frames)
359
+
360
+ returned_input_audio_embeds.append(torch.tensor(audio_embeds))
361
+ returned_audio_embed_sizes.append(torch.tensor(audio_embed_size).long())
362
+ audio_frames_list.append(audio_frames)
363
+
364
+ returned_input_audio_embeds = pad_sequence(
365
+ returned_input_audio_embeds, batch_first=True
366
+ )
367
+ returned_audio_embed_sizes = torch.stack(returned_audio_embed_sizes, dim=0)
368
+ audio_frames = torch.tensor(audio_frames_list)
369
+ returned_audio_attention_mask = torch.arange(0, audio_frames.max()).unsqueeze(0) < audio_frames.unsqueeze(1) if len(audios) > 1 else None
370
+
371
+ data = {
372
+ "input_audio_embeds": returned_input_audio_embeds,
373
+ "audio_embed_sizes": returned_audio_embed_sizes,
374
+ }
375
+ if returned_audio_attention_mask is not None:
376
+ data["audio_attention_mask"] = returned_audio_attention_mask
377
+
378
+ return BatchFeature(data=data, tensor_type=return_tensors)
379
+
380
+ def _extract_spectrogram(self, wav, fs):
381
+ """Extract spectrogram features from waveform.
382
+ Args:
383
+ wav (1D array): waveform of the input
384
+ fs (int): sampling rate of the waveform, 16000 or 8000.
385
+ If fs=8000, the waveform will be resampled to 16000Hz.
386
+ Output:
387
+ log_fbank (2D array): a TxD matrix of log Mel filterbank features.
388
+ D=80, and T is the number of frames.
389
+ """
390
+ if wav.ndim > 1:
391
+ wav = np.squeeze(wav)
392
+
393
+ # by default, we extract the mean if stereo
394
+ if len(wav.shape) == 2:
395
+ wav = wav.mean(1)
396
+
397
+ # Resample to 16000 or 8000 if needed
398
+ if fs > 16000:
399
+ wav = scipy.signal.resample_poly(wav, 1, fs // 16000)
400
+ fs = 16000
401
+ elif 8000 < fs < 16000:
402
+ wav = scipy.signal.resample_poly(wav, 1, fs // 8000)
403
+ fs = 8000
404
+ elif fs < 8000:
405
+ raise RuntimeError(f"Unsupported sample rate {fs}")
406
+
407
+ if fs == 8000:
408
+ if self._eightk_method == "resample":
409
+ # Input audio is 8 kHz. Convert to 16 kHz before feature
410
+ # extraction
411
+ wav = scipy.signal.resample_poly(wav, 2, 1)
412
+ fs = 16000
413
+ # Do nothing here for fillzero method
414
+ elif fs != 16000:
415
+ # Input audio is not a supported sample rate.
416
+ raise RuntimeError(f"Input data using an unsupported sample rate: {fs}")
417
+
418
+ preemphasis = 0.97
419
+
420
+ if fs == 8000:
421
+ n_fft = 256
422
+ win_length = 200
423
+ hop_length = 80
424
+ fft_window = self._hamming200
425
+ elif fs == 16000:
426
+ n_fft = 512
427
+ win_length = 400
428
+ hop_length = 160
429
+ fft_window = self._hamming400
430
+
431
+ # Spec 1: SpeechLib cut remaining sample insufficient for a hop
432
+ n_batch = (wav.shape[0] - win_length) // hop_length + 1
433
+ # Here we don't use stride_tricks since the input array may not satisfy
434
+ # memory layout requirement and we need writeable output
435
+ # Here we only use list of views before copy to desination
436
+ # so it is more efficient than broadcasting
437
+ y_frames = np.array(
438
+ [wav[_stride : _stride + win_length] for _stride in range(0, hop_length * n_batch, hop_length)],
439
+ dtype=np.float32,
440
+ )
441
+
442
+ # Spec 2: SpeechLib applies preemphasis within each batch
443
+ y_frames_prev = np.roll(y_frames, 1, axis=1)
444
+ y_frames_prev[:, 0] = y_frames_prev[:, 1]
445
+ y_frames = (y_frames - preemphasis * y_frames_prev) * 32768
446
+
447
+ S = np.fft.rfft(fft_window * y_frames, n=n_fft, axis=1).astype(np.complex64)
448
+
449
+ if fs == 8000:
450
+ # Need to pad the output to look like 16 kHz data but with zeros in
451
+ # the 4 to 8 kHz bins.
452
+ frames, bins = S.shape
453
+ padarray = np.zeros((frames, bins))
454
+ S = np.concatenate((S[:, 0:-1], padarray), axis=1) # Nyquist bin gets set to zero
455
+
456
+ spec = np.abs(S).astype(np.float32)
457
+ return spec
458
+
459
+ def _extract_features(self, wav, fs):
460
+ """Extract log filterbank features from waveform.
461
+ Args:
462
+ wav (1D array): waveform of the input
463
+ fs (int): sampling rate of the waveform, 16000 or 8000.
464
+ If fs=8000, the waveform will be resampled to 16000Hz.
465
+ Output:
466
+ log_fbank (2D array): a TxD matrix of log Mel filterbank features.
467
+ D=80, and T is the number of frames.
468
+ """
469
+ spec = self._extract_spectrogram(wav, fs)
470
+ spec_power = spec**2
471
+
472
+ fbank_power = np.clip(spec_power.dot(self._mel), 1.0, None)
473
+ log_fbank = np.log(fbank_power).astype(np.float32)
474
+
475
+ return log_fbank
476
+
477
+ def _compute_audio_embed_size(self, audio_frames):
478
+ integer = audio_frames // self.compression_rate
479
+ remainder = audio_frames % self.compression_rate
480
+
481
+ result = integer if remainder == 0 else integer + 1
482
+
483
+ integer = result // self.qformer_compression_rate
484
+ remainder = result % self.qformer_compression_rate
485
+ result = integer if remainder == 0 else integer + 1 # qformer compression
486
+
487
+ return result
488
+
489
+
490
+ class Phi4MMProcessor(ProcessorMixin):
491
+ r"""
492
+ Constructs a Phi4MM processor which raps an image processor, a audio processor, and a GPT tokenizer into a single processor.
493
+
494
+ [`Phi4MMProcessor`] offers all the functionalities of [`Phi4MMImageProcessor`] and [`GPT2Tokenizer`]. See the
495
+ [`~Phi4MMProcessor.__call__`] and [`~Phi4MMProcessor.decode`] for more information.
496
+
497
+ Args:
498
+ image_processor ([`Phi4MMImageProcessor`], *optional*):
499
+ The image processor is a required input.
500
+ tokenizer ([`GPT2Tokenizer`], *optional*):
501
+ The tokenizer is a required input.
502
+ """
503
+
504
+ attributes = ["image_processor", "audio_processor", "tokenizer"]
505
+ tokenizer_class = "GPT2TokenizerFast"
506
+ image_processor_class = "AutoImageProcessor" # Phi4MMImageProcessor will be registered later
507
+ audio_processor_class = "AutoFeatureExtractor" # Phi4MMAudioFeatureExtractor will be registered later
508
+
509
+ def __init__(self, image_processor, audio_processor, tokenizer):
510
+ self.image_processor = image_processor
511
+ self.audio_processor = audio_processor
512
+ self.tokenizer = tokenizer
513
+
514
+ def __call__(
515
+ self,
516
+ text: Union[TextInput, List[TextInput]],
517
+ images: Optional[ImageInput] = None,
518
+ audios: Optional[AudioInputs] = None,
519
+ padding: Union[bool, str, PaddingStrategy] = False,
520
+ truncation: Optional[Union[bool, str, TruncationStrategy]] = None,
521
+ max_length=None,
522
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
523
+ ) -> BatchFeature:
524
+ """
525
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forards the `text`
526
+ and `kwargs` arguments to GPT2Tokenizer's [`~GPT2Tokenizer.__call__`] if `text` is not `None` to encode
527
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
528
+ Phi4MMImageProcessor's [`~Phi4MMImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
529
+ of the above two methods for more information.
530
+
531
+ Args:
532
+ text (`str`, `List[str]`, `List[List[str]]`):
533
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
534
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
535
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
536
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
537
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
538
+ tensor. Both channels-first and channels-last formats are supported.
539
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
540
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
541
+ index) among:
542
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
543
+ sequence if provided).
544
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
545
+ acceptable input length for the model if that argument is not provided.
546
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
547
+ lengths).
548
+ max_length (`int`, *optional*):
549
+ Maximum length of the returned list and optionally padding length (see above).
550
+ truncation (`bool`, *optional*):
551
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
552
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
553
+ If set, will return tensors of a particular framework. Acceptable values are:
554
+
555
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
556
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
557
+ - `'np'`: Return NumPy `np.ndarray` objects.
558
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
559
+
560
+ Returns:
561
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
562
+
563
+ - **input_ids** -- List of token ids to be fed to a model.
564
+ - **input_image_embeds** -- Pixel values to be fed to a model.
565
+ - **image_sizes** -- List of tuples specifying the size of each image in `input_image_embeds`.
566
+ - **image_attention_mask** -- List of attention masks for each image in `input_image_embeds`.
567
+ - **input_audio_embeds** -- Audio embeddings to be fed to a model.
568
+ - **audio_embed_sizes** -- List of integers specifying the size of each audio in `input_audio_embeds`.
569
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model.
570
+ """
571
+ image_inputs = self.image_processor(images, return_tensors=return_tensors) if images is not None else {}
572
+ audio_inputs = self.audio_processor(audios, return_tensors=return_tensors) if audios is not None else {}
573
+ inputs = self._convert_images_audios_text_to_inputs(
574
+ image_inputs,
575
+ audio_inputs,
576
+ text,
577
+ padding=padding,
578
+ truncation=truncation,
579
+ max_length=max_length,
580
+ return_tensors=return_tensors,
581
+ )
582
+
583
+ # idenfity the input mode
584
+ if len(image_inputs) > 0 and len(audio_inputs) > 0:
585
+ input_mode = InputMode.VISION_SPEECH
586
+ elif len(image_inputs) > 0:
587
+ input_mode = InputMode.VISION
588
+ elif len(audio_inputs) > 0:
589
+ input_mode = InputMode.SPEECH
590
+ else:
591
+ input_mode = InputMode.LANGUAGE
592
+ inputs["input_mode"] = torch.tensor([input_mode.value], dtype=torch.long)
593
+
594
+ return inputs
595
+
596
+ @property
597
+ def special_image_token_id(self):
598
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
599
+
600
+ def get_special_image_token_id(self):
601
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
602
+
603
+ @property
604
+ def chat_template(self):
605
+ return self.tokenizer.chat_template
606
+
607
+ def _convert_images_audios_text_to_inputs(
608
+ self, images, audios, text, padding=False, truncation=None, max_length=None, return_tensors=None
609
+ ):
610
+ # prepare image id to image input ids
611
+ if len(images) > 0:
612
+ input_image_embeds = images["input_image_embeds"]
613
+ image_sizes = images["image_sizes"]
614
+ image_attention_mask = images["image_attention_mask"]
615
+ num_img_tokens = images['num_img_tokens']
616
+ else:
617
+ input_image_embeds = torch.tensor([])
618
+ image_sizes = torch.tensor([])
619
+ image_attention_mask = torch.tensor([])
620
+ num_img_tokens = []
621
+
622
+ # prepare audio id to audio input ids
623
+ if len(audios) > 0:
624
+ input_audio_embeds = audios["input_audio_embeds"]
625
+ audio_embed_sizes = audios["audio_embed_sizes"]
626
+ audio_attention_mask = audios.get("audio_attention_mask", None)
627
+ else:
628
+ input_audio_embeds = torch.tensor([])
629
+ audio_embed_sizes = torch.tensor([])
630
+ audio_attention_mask = None
631
+
632
+ # Replace certain special tokens for compatibility
633
+ # Ref: https://stackoverflow.com/questions/11475885/python-replace-regex
634
+ if isinstance(text, str):
635
+ text = [text]
636
+ assert isinstance(text, list)
637
+ processed_text = [re.sub(_COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN, _IMAGE_SPECIAL_TOKEN, t) for t in text]
638
+ processed_text = [re.sub(_COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN, _AUDIO_SPECIAL_TOKEN, t) for t in processed_text]
639
+
640
+ input_ids_list = [self.tokenizer(t).input_ids for t in processed_text]
641
+
642
+ img_cnt, audio_cnt = 0, 0 # only needed for later assertion
643
+ image_token_count_iter = iter(num_img_tokens)
644
+ audio_embed_size_iter = iter(audio_embed_sizes.tolist())
645
+ new_input_ids_list = []
646
+ for input_ids in input_ids_list:
647
+ i = 0
648
+ while i < len(input_ids):
649
+ token_id = input_ids[i]
650
+ if token_id == _AUDIO_SPECIAL_TOKEN_ID:
651
+ token_count = next(audio_embed_size_iter)
652
+ audio_cnt += 1
653
+ elif token_id == _IMAGE_SPECIAL_TOKEN_ID:
654
+ token_count = next(image_token_count_iter)
655
+ img_cnt += 1
656
+ else:
657
+ i += 1
658
+ continue
659
+ tokens = [token_id] * token_count
660
+ input_ids = input_ids[:i] + tokens + input_ids[i + 1:]
661
+ i += token_count
662
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
663
+ new_input_ids_list.append(input_ids)
664
+ lengths = torch.tensor([len(input_ids) for input_ids in new_input_ids_list])
665
+ max_len = lengths.max()
666
+ input_ids = input_ids.new_full((len(new_input_ids_list), max_len), self.tokenizer.pad_token_id)
667
+ # batched inference requires left padding
668
+ for i in range(len(new_input_ids_list)):
669
+ input_ids[i, max_len - len(new_input_ids_list[i]):] = new_input_ids_list[i]
670
+
671
+ # If the below assertion fails, it might be that input pure-text
672
+ # messages contain image/audio special tokens literally
673
+ # (<|endoftext10|>, <|endoftext11|>).
674
+ assert (
675
+ img_cnt == len(num_img_tokens)
676
+ ), (
677
+ f"Number of image tokens in prompt_token_ids ({img_cnt}) "
678
+ f"does not match number of images ({len(num_img_tokens)})"
679
+ )
680
+ assert (
681
+ audio_cnt == len(audio_embed_sizes)
682
+ ), (
683
+ f"Number of audio tokens in prompt_token_ids ({audio_cnt}) "
684
+ f"does not match number of audios ({len(audio_embed_sizes)})"
685
+ )
686
+
687
+ # prepare attention mask
688
+ seq_range = torch.arange(max_len - 1, -1, -1)
689
+ attention_mask = seq_range.unsqueeze(0) < lengths.unsqueeze(1)
690
+
691
+ # prepare batch feature
692
+ data = {
693
+ "input_ids": input_ids,
694
+ "input_image_embeds": input_image_embeds,
695
+ "image_sizes": image_sizes,
696
+ "image_attention_mask": image_attention_mask,
697
+ "input_audio_embeds": input_audio_embeds,
698
+ "audio_embed_sizes": audio_embed_sizes,
699
+ "audio_attention_mask": audio_attention_mask,
700
+ "attention_mask": attention_mask,
701
+ }
702
+
703
+ return BatchFeature(
704
+ data=data
705
+ )
706
+
707
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
708
+ def batch_decode(self, *args, **kwargs):
709
+ """
710
+ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
711
+ refer to the docstring of this method for more information.
712
+ """
713
+ return self.tokenizer.batch_decode(*args, **kwargs)
714
+
715
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
716
+ def decode(self, *args, **kwargs):
717
+ """
718
+ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
719
+ the docstring of this method for more information.
720
+ """
721
+ return self.tokenizer.decode(*args, **kwargs)
722
+
723
+ @property
724
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
725
+ def model_input_names(self):
726
+ tokenizer_input_names = self.tokenizer.model_input_names
727
+ image_processor_input_names = self.image_processor.model_input_names
728
+ audio_processor_input_names = self.audio_processor.model_input_names
729
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names + audio_processor_input_names))
730
+
731
+
732
+ AutoImageProcessor.register("Phi4MMImageProcessor", Phi4MMImageProcessor)
733
+ AutoFeatureExtractor.register("Phi4MMAudioFeatureExtractor", Phi4MMAudioFeatureExtractor)
models/Phi-4-multimodal-instruct/processor_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_phi4mm.Phi4MMProcessor"
4
+ },
5
+ "processor_class": "Phi4MMProcessor"
6
+ }
models/Phi-4-multimodal-instruct/sample_finetune_speech.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ finetune Phi-4-multimodal-instruct on an speech task
3
+
4
+ scipy==1.15.1
5
+ peft==0.13.2
6
+ backoff==2.2.1
7
+ transformers==4.46.1
8
+ accelerate==1.3.0
9
+ """
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+
16
+ import torch
17
+ import sacrebleu
18
+ from accelerate import Accelerator
19
+ from accelerate.utils import gather_object
20
+ from datasets import load_dataset
21
+ from torch.utils.data import Dataset
22
+ from tqdm import tqdm
23
+ from transformers import (
24
+ AutoModelForCausalLM,
25
+ AutoProcessor,
26
+ BatchFeature,
27
+ Trainer,
28
+ TrainingArguments,
29
+ StoppingCriteria,
30
+ StoppingCriteriaList,
31
+ )
32
+
33
+
34
+ INSTSRUCTION = {
35
+ "en_zh-CN": "Translate the audio to Mandarin.",
36
+ "en_id": "Translate the audio to Indonesian.",
37
+ "en_sl": "Translate the audio to Slovenian.",
38
+ }
39
+ TOKENIZER = {
40
+ "en_zh-CN": "zh",
41
+ "en_ja": "ja-mecab",
42
+ }
43
+ ANSWER_SUFFIX = "<|end|><|endoftext|>"
44
+ _IGNORE_INDEX = -100
45
+ _TRAIN_SIZE = 50000
46
+ _EVAL_SIZE = 200
47
+
48
+ class MultipleTokenBatchStoppingCriteria(StoppingCriteria):
49
+ """Stopping criteria capable of receiving multiple stop-tokens and handling batched inputs."""
50
+
51
+ def __init__(self, stop_tokens: torch.LongTensor, batch_size: int = 1) -> None:
52
+ """Initialize the multiple token batch stopping criteria.
53
+
54
+ Args:
55
+ stop_tokens: Stop-tokens.
56
+ batch_size: Batch size.
57
+
58
+ """
59
+
60
+ self.stop_tokens = stop_tokens
61
+ self.max_stop_tokens = stop_tokens.shape[-1]
62
+ self.stop_tokens_idx = torch.zeros(batch_size, dtype=torch.long, device=stop_tokens.device)
63
+
64
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
65
+ # Only gather the maximum number of inputs compatible with stop tokens
66
+ # and checks whether generated inputs are equal to `stop_tokens`
67
+ generated_inputs = torch.eq(input_ids[:, -self.max_stop_tokens :].unsqueeze(1), self.stop_tokens)
68
+ equal_generated_inputs = torch.all(generated_inputs, dim=2)
69
+
70
+ # Mark the position where a stop token has been produced for each input in the batch,
71
+ # but only if the corresponding entry is not already set
72
+ sequence_idx = torch.any(equal_generated_inputs, dim=1)
73
+ sequence_set_mask = self.stop_tokens_idx == 0
74
+ self.stop_tokens_idx[sequence_idx & sequence_set_mask] = input_ids.shape[-1]
75
+
76
+ return torch.all(self.stop_tokens_idx)
77
+
78
+ class CoVoSTDataset(Dataset):
79
+ def __init__(self, processor, data_dir, split,
80
+ lang="en_zh-CN", rank=0, world_size=1):
81
+
82
+ self.data = load_dataset("facebook/covost2",
83
+ lang,
84
+ data_dir=data_dir,
85
+ split=split,
86
+ trust_remote_code=True
87
+ )
88
+ self.training = "train" in split
89
+ self.processor = processor
90
+ self.instruction = INSTSRUCTION[lang]
91
+
92
+ if world_size > 1:
93
+ self.data = self.data.shard(world_size, rank)
94
+
95
+ def __len__(self):
96
+ return len(self.data)
97
+
98
+ def __getitem__(self, idx):
99
+ """
100
+ {'client_id': '0013037a1d45cc33460806cc3f8ecee9d536c45639ba4cbbf1564f1c051f53ff3c9f89ef2f1bf04badf55b3a2e7654c086f903681a7b6299616cff6f67598eff',
101
+ 'file': '{data_dir}/clips/common_voice_en_699711.mp3',
102
+ 'audio': {'path': '{data_dir}/clips/common_voice_en_699711.mp3',
103
+ 'array': array([-1.28056854e-09, -1.74622983e-09, -1.16415322e-10, ...,
104
+ 3.92560651e-10, 6.62794264e-10, -3.89536581e-09]),
105
+ 'sampling_rate': 16000},
106
+ 'sentence': '"She\'ll be all right."',
107
+ 'translation': '她会没事的。',
108
+ 'id': 'common_voice_en_699711'}
109
+ """
110
+ data = self.data[idx]
111
+ user_message = {
112
+ 'role': 'user',
113
+ 'content': '<|audio_1|>\n' + self.instruction,
114
+ }
115
+ prompt = self.processor.tokenizer.apply_chat_template(
116
+ [user_message], tokenize=False, add_generation_prompt=True
117
+ )
118
+ inputs = self.processor(text=prompt, audios=[(data["audio"]["array"], data["audio"]["sampling_rate"])], return_tensors='pt')
119
+
120
+ answer = f"{data['translation']}{ANSWER_SUFFIX}"
121
+ answer_ids = self.processor.tokenizer(answer, return_tensors='pt').input_ids
122
+ if self.training:
123
+ input_ids = torch.cat([inputs.input_ids, answer_ids], dim=1)
124
+ labels = torch.full_like(input_ids, _IGNORE_INDEX)
125
+ labels[:, -answer_ids.shape[1] :] = answer_ids
126
+ else:
127
+ input_ids = inputs.input_ids
128
+ labels = answer_ids
129
+
130
+ return {
131
+ 'input_ids': input_ids,
132
+ 'labels': labels,
133
+ 'input_audio_embeds': inputs.input_audio_embeds,
134
+ 'audio_embed_sizes': inputs.audio_embed_sizes,
135
+ }
136
+
137
+ def pad_sequence(sequences, padding_side='right', padding_value=0):
138
+ """
139
+ Pad a list of sequences to the same length.
140
+ sequences: list of tensors in [seq_len, *] shape
141
+ """
142
+ assert padding_side in ['right', 'left']
143
+ max_size = sequences[0].size()
144
+ trailing_dims = max_size[1:]
145
+ max_len = max(len(seq) for seq in sequences)
146
+ batch_size = len(sequences)
147
+ output = sequences[0].new_full((batch_size, max_len) + trailing_dims, padding_value)
148
+ for i, seq in enumerate(sequences):
149
+ length = seq.size(0)
150
+ if padding_side == 'right':
151
+ output.data[i, :length] = seq
152
+ else:
153
+ output.data[i, -length:] = seq
154
+ return output
155
+
156
+
157
+ def cat_with_pad(tensors, dim, padding_value=0):
158
+ """
159
+ cat along dim, while pad to max for all other dims
160
+ """
161
+ ndim = tensors[0].dim()
162
+ assert all(
163
+ t.dim() == ndim for t in tensors[1:]
164
+ ), 'All tensors must have the same number of dimensions'
165
+
166
+ out_size = [max(t.shape[i] for t in tensors) for i in range(ndim)]
167
+ out_size[dim] = sum(t.shape[dim] for t in tensors)
168
+ output = tensors[0].new_full(out_size, padding_value)
169
+
170
+ index = 0
171
+ for t in tensors:
172
+ # Create a slice list where every dimension except dim is full slice
173
+ slices = [slice(0, t.shape[d]) for d in range(ndim)]
174
+ # Update only the concat dimension slice
175
+ slices[dim] = slice(index, index + t.shape[dim])
176
+
177
+ output[slices] = t
178
+ index += t.shape[dim]
179
+
180
+ return output
181
+
182
+
183
+ def covost_collate_fn(batch):
184
+ input_ids_list = []
185
+ labels_list = []
186
+ input_audio_embeds_list = []
187
+ audio_embed_sizes_list = []
188
+ audio_attention_mask_list = []
189
+ for inputs in batch:
190
+ input_ids_list.append(inputs['input_ids'][0])
191
+ labels_list.append(inputs['labels'][0])
192
+ input_audio_embeds_list.append(inputs['input_audio_embeds'])
193
+ audio_embed_sizes_list.append(inputs['audio_embed_sizes'])
194
+ audio_attention_mask_list.append(
195
+ inputs['input_audio_embeds'].new_full((inputs['input_audio_embeds'].size(1),), True, dtype=torch.bool)
196
+ )
197
+
198
+ try:
199
+ input_ids = pad_sequence(input_ids_list, padding_side='left', padding_value=0)
200
+ labels = pad_sequence(labels_list, padding_side='left', padding_value=0)
201
+ audio_attention_mask = (
202
+ pad_sequence(audio_attention_mask_list, padding_side='right', padding_value=False)
203
+ if len(audio_attention_mask_list) > 1
204
+ else None
205
+ )
206
+ except Exception as e:
207
+ print(e)
208
+ print(input_ids_list)
209
+ print(labels_list)
210
+ raise
211
+ attention_mask = (input_ids != 0).long()
212
+ input_audio_embeds = cat_with_pad(input_audio_embeds_list, dim=0)
213
+ audio_embed_sizes = torch.cat(audio_embed_sizes_list)
214
+
215
+ return BatchFeature(
216
+ {
217
+ 'input_ids': input_ids,
218
+ 'labels': labels,
219
+ 'attention_mask': attention_mask,
220
+ 'input_audio_embeds': input_audio_embeds,
221
+ 'audio_embed_sizes': audio_embed_sizes,
222
+ 'audio_attention_mask': audio_attention_mask,
223
+ 'input_mode': 2, # speech mode
224
+ }
225
+ )
226
+
227
+
228
+
229
+ def create_model(model_name_or_path, use_flash_attention=False):
230
+ model = AutoModelForCausalLM.from_pretrained(
231
+ model_name_or_path,
232
+ torch_dtype=torch.bfloat16 if use_flash_attention else torch.float32,
233
+ _attn_implementation='flash_attention_2' if use_flash_attention else 'sdpa',
234
+ trust_remote_code=True,
235
+ ).to('cuda')
236
+
237
+ return model
238
+
239
+
240
+ @torch.no_grad()
241
+ def evaluate(
242
+ model, processor, eval_dataset, save_path=None, disable_tqdm=False, eval_batch_size=1
243
+ ):
244
+ rank = int(os.environ.get('RANK', 0))
245
+ local_rank = int(os.environ.get('LOCAL_RANK', 0))
246
+
247
+ model.eval()
248
+ all_generated_texts = []
249
+ all_labels = []
250
+
251
+ eval_dataloader = torch.utils.data.DataLoader(
252
+ eval_dataset,
253
+ batch_size=eval_batch_size,
254
+ collate_fn=covost_collate_fn,
255
+ shuffle=False,
256
+ drop_last=False,
257
+ num_workers=8,
258
+ prefetch_factor=2,
259
+ pin_memory=True,
260
+ )
261
+ stop_tokens = ["<|end|>", processor.tokenizer.eos_token]
262
+ stop_tokens_ids = processor.tokenizer(stop_tokens, add_special_tokens=False, padding="longest", return_tensors="pt")["input_ids"]
263
+ stop_tokens_ids = stop_tokens_ids.to(f'cuda:{local_rank}')
264
+
265
+ for inputs in tqdm(
266
+ eval_dataloader, disable=(rank != 0) or disable_tqdm, desc='running eval'
267
+ ):
268
+ stopping_criteria=StoppingCriteriaList([MultipleTokenBatchStoppingCriteria(stop_tokens_ids, batch_size=inputs.input_ids.size(0))])
269
+ inputs = inputs.to(f'cuda:{local_rank}')
270
+ generated_ids = model.generate(
271
+ **inputs, eos_token_id=processor.tokenizer.eos_token_id, max_new_tokens=64,
272
+ stopping_criteria=stopping_criteria,
273
+ )
274
+
275
+ stop_tokens_idx = stopping_criteria[0].stop_tokens_idx.reshape(inputs.input_ids.size(0), -1)[:, 0]
276
+
277
+ stop_tokens_idx = torch.where(
278
+ stop_tokens_idx > 0,
279
+ stop_tokens_idx - stop_tokens_ids.shape[-1],
280
+ generated_ids.shape[-1],
281
+ )
282
+ generated_text = [
283
+ processor.decode(_pred_ids[inputs["input_ids"].shape[1] : _stop_tokens_idx], skip_special_tokens=True, clean_up_tokenization_spaces=False)
284
+ for _pred_ids, _stop_tokens_idx in zip(generated_ids, stop_tokens_idx)
285
+ ]
286
+ all_generated_texts.extend(generated_text)
287
+ labels = [processor.decode(_label_ids[_label_ids != 0]).removesuffix(ANSWER_SUFFIX) for _label_ids in inputs["labels"]]
288
+ all_labels.extend(labels)
289
+
290
+ all_generated_texts = gather_object(all_generated_texts)
291
+ all_labels = gather_object(all_labels)
292
+
293
+ if rank == 0:
294
+ assert len(all_generated_texts) == len(all_labels)
295
+ bleu = sacrebleu.corpus_bleu(all_generated_texts, [all_labels])
296
+ print(bleu)
297
+ if save_path:
298
+ with open(save_path, 'w') as f:
299
+ save_dict = {
300
+ 'all_generated_texts': all_generated_texts,
301
+ 'all_labels': all_labels,
302
+ 'score': bleu.score,
303
+ }
304
+ json.dump(save_dict, f)
305
+
306
+ return bleu.score
307
+ return None
308
+
309
+
310
+ def main():
311
+ parser = argparse.ArgumentParser()
312
+ parser.add_argument(
313
+ '--model_name_or_path',
314
+ type=str,
315
+ default='microsoft/Phi-4-multimodal-instruct',
316
+ help='Model name or path to load from',
317
+ )
318
+ parser.add_argument(
319
+ "--common_voice_dir",
320
+ type=str,
321
+ default="CommonVoice/EN",
322
+ help="Unzipped Common Voice Audio dataset directory, refer to https://commonvoice.mozilla.org/en/datasets, version 4.0",
323
+ )
324
+ parser.add_argument(
325
+ "--lang",
326
+ type=str,
327
+ default="en_sl",
328
+ help="Language pair for translation.",
329
+ )
330
+ parser.add_argument('--use_flash_attention', action='store_true', help='Use Flash Attention')
331
+ parser.add_argument('--output_dir', type=str, default='./output/', help='Output directory')
332
+ parser.add_argument('--batch_size', type=int, default=128, help='Batch size')
333
+ parser.add_argument(
334
+ '--batch_size_per_gpu',
335
+ type=int,
336
+ default=32,
337
+ help='Batch size per GPU (adjust this to fit in GPU memory)',
338
+ )
339
+ parser.add_argument(
340
+ '--num_train_epochs', type=int, default=1, help='Number of training epochs'
341
+ )
342
+ parser.add_argument('--learning_rate', type=float, default=4.0e-5, help='Learning rate')
343
+ parser.add_argument('--wd', type=float, default=0.01, help='Weight decay')
344
+ parser.add_argument('--no-tqdm', dest='tqdm', action='store_false', help='Disable tqdm')
345
+ args = parser.parse_args()
346
+
347
+ accelerator = Accelerator()
348
+
349
+ with accelerator.local_main_process_first():
350
+ processor = AutoProcessor.from_pretrained(
351
+ args.model_name_or_path,
352
+ trust_remote_code=True,
353
+ )
354
+ model = create_model(
355
+ args.model_name_or_path,
356
+ use_flash_attention=args.use_flash_attention,
357
+ )
358
+
359
+ model.set_lora_adapter('speech')
360
+
361
+
362
+ rank = int(os.environ.get('RANK', 0))
363
+ world_size = int(os.environ.get('WORLD_SIZE', 1))
364
+
365
+ eval_dataset = CoVoSTDataset(processor,
366
+ data_dir=args.common_voice_dir,
367
+ split=f'test[:{_EVAL_SIZE}]',
368
+ lang=args.lang,
369
+ rank=rank,
370
+ world_size=world_size)
371
+
372
+ train_dataset = CoVoSTDataset(processor,
373
+ data_dir=args.common_voice_dir,
374
+ split=f'train[:{_TRAIN_SIZE}]',
375
+ lang=args.lang)
376
+
377
+ num_gpus = accelerator.num_processes
378
+ print(f'training on {num_gpus} GPUs')
379
+ assert (
380
+ args.batch_size % (num_gpus * args.batch_size_per_gpu) == 0
381
+ ), 'Batch size must be divisible by the number of GPUs'
382
+ gradient_accumulation_steps = args.batch_size // (num_gpus * args.batch_size_per_gpu)
383
+
384
+ if args.use_flash_attention:
385
+ fp16 = False
386
+ bf16 = True
387
+ else:
388
+ fp16 = True
389
+ bf16 = False
390
+
391
+ # hard coded training args
392
+ training_args = TrainingArguments(
393
+ num_train_epochs=args.num_train_epochs,
394
+ per_device_train_batch_size=args.batch_size_per_gpu,
395
+ gradient_checkpointing=True,
396
+ gradient_checkpointing_kwargs={'use_reentrant': False},
397
+ gradient_accumulation_steps=gradient_accumulation_steps,
398
+ optim='adamw_torch',
399
+ adam_beta1=0.9,
400
+ adam_beta2=0.95,
401
+ adam_epsilon=1e-7,
402
+ learning_rate=args.learning_rate,
403
+ weight_decay=args.wd,
404
+ max_grad_norm=1.0,
405
+ lr_scheduler_type='linear',
406
+ warmup_steps=50,
407
+ logging_steps=10,
408
+ output_dir=args.output_dir,
409
+ save_strategy='no',
410
+ save_total_limit=10,
411
+ save_only_model=True,
412
+ bf16=bf16,
413
+ fp16=fp16,
414
+ remove_unused_columns=False,
415
+ report_to='none',
416
+ deepspeed=None,
417
+ disable_tqdm=not args.tqdm,
418
+ dataloader_num_workers=4,
419
+ ddp_find_unused_parameters=True, # for unused SigLIP layers
420
+ )
421
+
422
+ # eval before fine-tuning
423
+ out_path = Path(training_args.output_dir)
424
+ out_path.mkdir(parents=True, exist_ok=True)
425
+
426
+ score = evaluate(
427
+ model,
428
+ processor,
429
+ eval_dataset,
430
+ save_path=out_path / 'eval_before.json',
431
+ disable_tqdm=not args.tqdm,
432
+ eval_batch_size=args.batch_size_per_gpu,
433
+ )
434
+ if accelerator.is_main_process:
435
+ print(f'BLEU Score before finetuning: {score}')
436
+
437
+ trainer = Trainer(
438
+ model=model,
439
+ args=training_args,
440
+ data_collator=covost_collate_fn,
441
+ train_dataset=train_dataset,
442
+ )
443
+
444
+ trainer.train()
445
+ trainer.save_model()
446
+ if accelerator.is_main_process:
447
+ processor.save_pretrained(training_args.output_dir)
448
+ accelerator.wait_for_everyone()
449
+
450
+ # eval after fine-tuning (load saved checkpoint)
451
+ # first try to clear GPU memory
452
+ del model
453
+ del trainer
454
+ __import__('gc').collect()
455
+ torch.cuda.empty_cache()
456
+
457
+ # reload the model for inference
458
+ model = AutoModelForCausalLM.from_pretrained(
459
+ training_args.output_dir,
460
+ torch_dtype=torch.bfloat16 if args.use_flash_attention else torch.float32,
461
+ trust_remote_code=True,
462
+ _attn_implementation='flash_attention_2' if args.use_flash_attention else 'sdpa',
463
+ ).to('cuda')
464
+
465
+ score = evaluate(
466
+ model,
467
+ processor,
468
+ eval_dataset,
469
+ save_path=out_path / 'eval_after.json',
470
+ disable_tqdm=not args.tqdm,
471
+ eval_batch_size=args.batch_size_per_gpu,
472
+ )
473
+ if accelerator.is_main_process:
474
+ print(f'BLEU Score after finetuning: {score}')
475
+
476
+
477
+ if __name__ == '__main__':
478
+ main()
models/Phi-4-multimodal-instruct/sample_finetune_vision.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ finetune Phi-4-multimodal-instruct on an image task
3
+
4
+ scipy==1.15.1
5
+ peft==0.13.2
6
+ backoff==2.2.1
7
+ transformers==4.47.0
8
+ accelerate==1.3.0
9
+ """
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import tempfile
15
+ import zipfile
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ from accelerate import Accelerator
20
+ from accelerate.utils import gather_object
21
+ from datasets import load_dataset
22
+ from huggingface_hub import hf_hub_download
23
+ from PIL import Image
24
+ from torch.utils.data import Dataset
25
+ from tqdm import tqdm
26
+ from transformers import (
27
+ AutoModelForCausalLM,
28
+ AutoProcessor,
29
+ BatchFeature,
30
+ Trainer,
31
+ TrainingArguments,
32
+ )
33
+
34
+ DEFAULT_INSTSRUCTION = "Answer with the option's letter from the given choices directly."
35
+ _IGNORE_INDEX = -100
36
+ _TRAIN_SIZE = 8000
37
+ _EVAL_SIZE = 500
38
+ _MAX_TRAINING_LENGTH = 8192
39
+
40
+
41
+ class PmcVqaTrainDataset(Dataset):
42
+ def __init__(self, processor, data_size, instruction=DEFAULT_INSTSRUCTION):
43
+ # Download the file
44
+ file_path = hf_hub_download(
45
+ repo_id='xmcmic/PMC-VQA', # repository name
46
+ filename='images_2.zip', # file to download
47
+ repo_type='dataset', # specify it's a dataset repo
48
+ )
49
+
50
+ # file_path will be the local path where the file was downloaded
51
+ print(f'File downloaded to: {file_path}')
52
+
53
+ # unzip to temp folder
54
+ self.image_folder = Path(tempfile.mkdtemp())
55
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
56
+ zip_ref.extractall(self.image_folder)
57
+
58
+ data_files = {
59
+ 'train': 'https://huggingface.co/datasets/xmcmic/PMC-VQA/resolve/main/train_2.csv',
60
+ }
61
+ split = 'train' if data_size is None else f'train[:{data_size}]'
62
+ self.annotations = load_dataset('xmcmic/PMC-VQA', data_files=data_files, split=split)
63
+ self.processor = processor
64
+ self.instruction = instruction
65
+
66
+ def __len__(self):
67
+ return len(self.annotations)
68
+
69
+ def __getitem__(self, idx):
70
+ """
71
+ {'index': 35,
72
+ 'Figure_path': 'PMC8253797_Fig4_11.jpg',
73
+ 'Caption': 'A slightly altered cell . (c-c‴) A highly altered cell as seen from 4 different angles . Note mitochondria/mitochondrial networks (green), Golgi complexes (red), cell nuclei (light blue) and the cell outline (yellow).',
74
+ 'Question': ' What color is used to label the Golgi complexes in the image?',
75
+ 'Choice A': ' A: Green ',
76
+ 'Choice B': ' B: Red ',
77
+ 'Choice C': ' C: Light blue ',
78
+ 'Choice D': ' D: Yellow',
79
+ 'Answer': 'B',
80
+ 'split': 'train'}
81
+ """
82
+ annotation = self.annotations[idx]
83
+ image = Image.open(self.image_folder / 'figures' / annotation['Figure_path'])
84
+ question = annotation['Question']
85
+ choices = [annotation[f'Choice {chr(ord("A") + i)}'] for i in range(4)]
86
+ user_message = {
87
+ 'role': 'user',
88
+ 'content': '<|image_1|>' + '\n'.join([question] + choices + [self.instruction]),
89
+ }
90
+ prompt = self.processor.tokenizer.apply_chat_template(
91
+ [user_message], tokenize=False, add_generation_prompt=True
92
+ )
93
+ answer = f'{annotation["Answer"]}<|end|><|endoftext|>'
94
+ inputs = self.processor(prompt, images=[image], return_tensors='pt')
95
+
96
+ answer_ids = self.processor.tokenizer(answer, return_tensors='pt').input_ids
97
+
98
+ input_ids = torch.cat([inputs.input_ids, answer_ids], dim=1)
99
+ labels = torch.full_like(input_ids, _IGNORE_INDEX)
100
+ labels[:, -answer_ids.shape[1] :] = answer_ids
101
+
102
+ if input_ids.size(1) > _MAX_TRAINING_LENGTH:
103
+ input_ids = input_ids[:, :_MAX_TRAINING_LENGTH]
104
+ labels = labels[:, :_MAX_TRAINING_LENGTH]
105
+ if torch.all(labels == _IGNORE_INDEX).item():
106
+ # workaround to make sure loss compute won't fail
107
+ labels[:, -1] = self.processor.tokenizer.eos_token_id
108
+
109
+ return {
110
+ 'input_ids': input_ids,
111
+ 'labels': labels,
112
+ 'input_image_embeds': inputs.input_image_embeds,
113
+ 'image_attention_mask': inputs.image_attention_mask,
114
+ 'image_sizes': inputs.image_sizes,
115
+ }
116
+
117
+ def __del__(self):
118
+ __import__('shutil').rmtree(self.image_folder)
119
+
120
+
121
+ class PmcVqaEvalDataset(Dataset):
122
+ def __init__(
123
+ self, processor, data_size, instruction=DEFAULT_INSTSRUCTION, rank=0, world_size=1
124
+ ):
125
+ # Download the file
126
+ file_path = hf_hub_download(
127
+ repo_id='xmcmic/PMC-VQA', # repository name
128
+ filename='images_2.zip', # file to download
129
+ repo_type='dataset', # specify it's a dataset repo
130
+ )
131
+
132
+ # file_path will be the local path where the file was downloaded
133
+ print(f'File downloaded to: {file_path}')
134
+
135
+ # unzip to temp folder
136
+ self.image_folder = Path(tempfile.mkdtemp())
137
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
138
+ zip_ref.extractall(self.image_folder)
139
+
140
+ data_files = {
141
+ 'test': 'https://huggingface.co/datasets/xmcmic/PMC-VQA/resolve/main/test_2.csv',
142
+ }
143
+ split = 'test' if data_size is None else f'test[:{data_size}]'
144
+ self.annotations = load_dataset(
145
+ 'xmcmic/PMC-VQA', data_files=data_files, split=split
146
+ ).shard(num_shards=world_size, index=rank)
147
+ self.processor = processor
148
+ self.instruction = instruction
149
+
150
+ def __len__(self):
151
+ return len(self.annotations)
152
+
153
+ def __getitem__(self, idx):
154
+ """
155
+ {'index': 62,
156
+ 'Figure_path': 'PMC8253867_Fig2_41.jpg',
157
+ 'Caption': 'CT pulmonary angiogram reveals encasement and displacement of the left anterior descending coronary artery ( blue arrows ).',
158
+ 'Question': ' What is the name of the artery encased and displaced in the image? ',
159
+ 'Choice A': ' A: Right Coronary Artery ',
160
+ 'Choice B': ' B: Left Anterior Descending Coronary Artery ',
161
+ 'Choice C': ' C: Circumflex Coronary Artery ',
162
+ 'Choice D': ' D: Superior Mesenteric Artery ',
163
+ 'Answer': 'B',
164
+ 'split': 'test'}
165
+ """
166
+ annotation = self.annotations[idx]
167
+ image = Image.open(self.image_folder / 'figures' / annotation['Figure_path'])
168
+ question = annotation['Question']
169
+ choices = [annotation[f'Choice {chr(ord("A") + i)}'] for i in range(4)]
170
+ user_message = {
171
+ 'role': 'user',
172
+ 'content': '<|image_1|>' + '\n'.join([question] + choices + [self.instruction]),
173
+ }
174
+ prompt = self.processor.tokenizer.apply_chat_template(
175
+ [user_message], tokenize=False, add_generation_prompt=True
176
+ )
177
+ answer = annotation['Answer']
178
+ inputs = self.processor(prompt, images=[image], return_tensors='pt')
179
+
180
+ unique_id = f'{annotation["index"]:010d}'
181
+ return {
182
+ 'id': unique_id,
183
+ 'input_ids': inputs.input_ids,
184
+ 'input_image_embeds': inputs.input_image_embeds,
185
+ 'image_attention_mask': inputs.image_attention_mask,
186
+ 'image_sizes': inputs.image_sizes,
187
+ 'answer': answer,
188
+ }
189
+
190
+ def __del__(self):
191
+ __import__('shutil').rmtree(self.image_folder)
192
+
193
+
194
+ def pad_sequence(sequences, padding_side='right', padding_value=0):
195
+ """
196
+ Pad a list of sequences to the same length.
197
+ sequences: list of tensors in [seq_len, *] shape
198
+ """
199
+ assert padding_side in ['right', 'left']
200
+ max_size = sequences[0].size()
201
+ trailing_dims = max_size[1:]
202
+ max_len = max(len(seq) for seq in sequences)
203
+ batch_size = len(sequences)
204
+ output = sequences[0].new_full((batch_size, max_len) + trailing_dims, padding_value)
205
+ for i, seq in enumerate(sequences):
206
+ length = seq.size(0)
207
+ if padding_side == 'right':
208
+ output.data[i, :length] = seq
209
+ else:
210
+ output.data[i, -length:] = seq
211
+ return output
212
+
213
+
214
+ def cat_with_pad(tensors, dim, padding_value=0):
215
+ """
216
+ cat along dim, while pad to max for all other dims
217
+ """
218
+ ndim = tensors[0].dim()
219
+ assert all(
220
+ t.dim() == ndim for t in tensors[1:]
221
+ ), 'All tensors must have the same number of dimensions'
222
+
223
+ out_size = [max(t.shape[i] for t in tensors) for i in range(ndim)]
224
+ out_size[dim] = sum(t.shape[dim] for t in tensors)
225
+ output = tensors[0].new_full(out_size, padding_value)
226
+
227
+ index = 0
228
+ for t in tensors:
229
+ # Create a slice list where every dimension except dim is full slice
230
+ slices = [slice(0, t.shape[d]) for d in range(ndim)]
231
+ # Update only the concat dimension slice
232
+ slices[dim] = slice(index, index + t.shape[dim])
233
+
234
+ output[slices] = t
235
+ index += t.shape[dim]
236
+
237
+ return output
238
+
239
+
240
+ def pmc_vqa_collate_fn(batch):
241
+ input_ids_list = []
242
+ labels_list = []
243
+ input_image_embeds_list = []
244
+ image_attention_mask_list = []
245
+ image_sizes_list = []
246
+ for inputs in batch:
247
+ input_ids_list.append(inputs['input_ids'][0])
248
+ labels_list.append(inputs['labels'][0])
249
+ input_image_embeds_list.append(inputs['input_image_embeds'])
250
+ image_attention_mask_list.append(inputs['image_attention_mask'])
251
+ image_sizes_list.append(inputs['image_sizes'])
252
+
253
+ input_ids = pad_sequence(input_ids_list, padding_side='right', padding_value=0)
254
+ labels = pad_sequence(labels_list, padding_side='right', padding_value=0)
255
+ attention_mask = (input_ids != 0).long()
256
+ input_image_embeds = cat_with_pad(input_image_embeds_list, dim=0)
257
+ image_attention_mask = cat_with_pad(image_attention_mask_list, dim=0)
258
+ image_sizes = torch.cat(image_sizes_list)
259
+
260
+ return BatchFeature(
261
+ {
262
+ 'input_ids': input_ids,
263
+ 'labels': labels,
264
+ 'attention_mask': attention_mask,
265
+ 'input_image_embeds': input_image_embeds,
266
+ 'image_attention_mask': image_attention_mask,
267
+ 'image_sizes': image_sizes,
268
+ 'input_mode': 1, # vision mode
269
+ }
270
+ )
271
+
272
+
273
+ def pmc_vqa_eval_collate_fn(batch):
274
+ input_ids_list = []
275
+ input_image_embeds_list = []
276
+ image_attention_mask_list = []
277
+ image_sizes_list = []
278
+ all_unique_ids = []
279
+ all_answers = []
280
+ for inputs in batch:
281
+ input_ids_list.append(inputs['input_ids'][0])
282
+ input_image_embeds_list.append(inputs['input_image_embeds'])
283
+ image_attention_mask_list.append(inputs['image_attention_mask'])
284
+ image_sizes_list.append(inputs['image_sizes'])
285
+ all_unique_ids.append(inputs['id'])
286
+ all_answers.append(inputs['answer'])
287
+
288
+ input_ids = pad_sequence(input_ids_list, padding_side='left', padding_value=0)
289
+ attention_mask = (input_ids != 0).long()
290
+ input_image_embeds = cat_with_pad(input_image_embeds_list, dim=0)
291
+ image_attention_mask = cat_with_pad(image_attention_mask_list, dim=0)
292
+ image_sizes = torch.cat(image_sizes_list)
293
+
294
+ return (
295
+ all_unique_ids,
296
+ all_answers,
297
+ BatchFeature(
298
+ {
299
+ 'input_ids': input_ids,
300
+ 'attention_mask': attention_mask,
301
+ 'input_image_embeds': input_image_embeds,
302
+ 'image_attention_mask': image_attention_mask,
303
+ 'image_sizes': image_sizes,
304
+ 'input_mode': 1, # vision mode
305
+ }
306
+ ),
307
+ )
308
+
309
+
310
+ def create_model(model_name_or_path, use_flash_attention=False):
311
+ model = AutoModelForCausalLM.from_pretrained(
312
+ model_name_or_path,
313
+ torch_dtype=torch.bfloat16 if use_flash_attention else torch.float32,
314
+ _attn_implementation='flash_attention_2' if use_flash_attention else 'sdpa',
315
+ trust_remote_code=True,
316
+ ).to('cuda')
317
+ # remove parameters irrelevant to vision tasks
318
+ del model.model.embed_tokens_extend.audio_embed # remove audio encoder
319
+ for layer in model.model.layers:
320
+ # remove audio lora
321
+ del layer.mlp.down_proj.lora_A.speech
322
+ del layer.mlp.down_proj.lora_B.speech
323
+ del layer.mlp.gate_up_proj.lora_A.speech
324
+ del layer.mlp.gate_up_proj.lora_B.speech
325
+ del layer.self_attn.o_proj.lora_A.speech
326
+ del layer.self_attn.o_proj.lora_B.speech
327
+ del layer.self_attn.qkv_proj.lora_A.speech
328
+ del layer.self_attn.qkv_proj.lora_B.speech
329
+
330
+ # TODO remove unused vision layers?
331
+
332
+ return model
333
+
334
+
335
+ @torch.no_grad()
336
+ def evaluate(
337
+ model, processor, eval_dataset, save_path=None, disable_tqdm=False, eval_batch_size=1
338
+ ):
339
+ rank = int(os.environ.get('RANK', 0))
340
+ local_rank = int(os.environ.get('LOCAL_RANK', 0))
341
+
342
+ model.eval()
343
+ all_answers = []
344
+ all_generated_texts = []
345
+
346
+ eval_dataloader = torch.utils.data.DataLoader(
347
+ eval_dataset,
348
+ batch_size=eval_batch_size,
349
+ collate_fn=pmc_vqa_eval_collate_fn,
350
+ shuffle=False,
351
+ drop_last=False,
352
+ num_workers=4,
353
+ prefetch_factor=2,
354
+ pin_memory=True,
355
+ )
356
+ for ids, answers, inputs in tqdm(
357
+ eval_dataloader, disable=(rank != 0) or disable_tqdm, desc='running eval'
358
+ ):
359
+ all_answers.extend({'id': i, 'answer': a.strip().lower()} for i, a in zip(ids, answers))
360
+
361
+ inputs = inputs.to(f'cuda:{local_rank}')
362
+ generated_ids = model.generate(
363
+ **inputs, eos_token_id=processor.tokenizer.eos_token_id, max_new_tokens=64
364
+ )
365
+
366
+ input_len = inputs.input_ids.size(1)
367
+ generated_texts = processor.batch_decode(
368
+ generated_ids[:, input_len:],
369
+ skip_special_tokens=True,
370
+ clean_up_tokenization_spaces=False,
371
+ )
372
+ all_generated_texts.extend(
373
+ {'id': i, 'generated_text': g.strip().lower()} for i, g in zip(ids, generated_texts)
374
+ )
375
+
376
+ # gather outputs from all ranks
377
+ all_answers = gather_object(all_answers)
378
+ all_generated_texts = gather_object(all_generated_texts)
379
+
380
+ if rank == 0:
381
+ assert len(all_answers) == len(all_generated_texts)
382
+ acc = sum(
383
+ a['answer'] == g['generated_text'] for a, g in zip(all_answers, all_generated_texts)
384
+ ) / len(all_answers)
385
+ if save_path:
386
+ with open(save_path, 'w') as f:
387
+ save_dict = {
388
+ 'answers_unique': all_answers,
389
+ 'generated_texts_unique': all_generated_texts,
390
+ 'accuracy': acc,
391
+ }
392
+ json.dump(save_dict, f)
393
+
394
+ return acc
395
+ return None
396
+
397
+
398
+ def main():
399
+ parser = argparse.ArgumentParser()
400
+ parser.add_argument(
401
+ '--model_name_or_path',
402
+ type=str,
403
+ default='microsoft/Phi-4-multimodal-instruct',
404
+ help='Model name or path to load from',
405
+ )
406
+ parser.add_argument('--use_flash_attention', action='store_true', help='Use Flash Attention')
407
+ parser.add_argument('--output_dir', type=str, default='./output/', help='Output directory')
408
+ parser.add_argument('--batch_size', type=int, default=16, help='Batch size')
409
+ parser.add_argument(
410
+ '--batch_size_per_gpu',
411
+ type=int,
412
+ default=1,
413
+ help='Batch size per GPU (adjust this to fit in GPU memory)',
414
+ )
415
+ parser.add_argument(
416
+ '--dynamic_hd',
417
+ type=int,
418
+ default=36,
419
+ help='Number of maximum image crops',
420
+ )
421
+ parser.add_argument(
422
+ '--num_train_epochs', type=int, default=1, help='Number of training epochs'
423
+ )
424
+ parser.add_argument('--learning_rate', type=float, default=4.0e-5, help='Learning rate')
425
+ parser.add_argument('--wd', type=float, default=0.01, help='Weight decay')
426
+ parser.add_argument('--no_tqdm', dest='tqdm', action='store_false', help='Disable tqdm')
427
+ parser.add_argument('--full_run', action='store_true', help='Run the full training and eval')
428
+ args = parser.parse_args()
429
+
430
+ accelerator = Accelerator()
431
+
432
+ with accelerator.local_main_process_first():
433
+ processor = AutoProcessor.from_pretrained(
434
+ args.model_name_or_path,
435
+ trust_remote_code=True,
436
+ dynamic_hd=args.dynamic_hd,
437
+ )
438
+ model = create_model(
439
+ args.model_name_or_path,
440
+ use_flash_attention=args.use_flash_attention,
441
+ )
442
+ # tune vision encoder and lora
443
+ model.set_lora_adapter('vision')
444
+ for param in model.model.embed_tokens_extend.image_embed.parameters():
445
+ param.requires_grad = True
446
+
447
+ rank = int(os.environ.get('RANK', 0))
448
+ world_size = int(os.environ.get('WORLD_SIZE', 1))
449
+
450
+ train_dataset = PmcVqaTrainDataset(processor, data_size=None if args.full_run else _TRAIN_SIZE)
451
+ eval_dataset = PmcVqaEvalDataset(
452
+ processor,
453
+ data_size=None if args.full_run else _EVAL_SIZE,
454
+ rank=rank,
455
+ world_size=world_size,
456
+ )
457
+
458
+ num_gpus = accelerator.num_processes
459
+ print(f'training on {num_gpus} GPUs')
460
+ assert (
461
+ args.batch_size % (num_gpus * args.batch_size_per_gpu) == 0
462
+ ), 'Batch size must be divisible by the number of GPUs'
463
+ gradient_accumulation_steps = args.batch_size // (num_gpus * args.batch_size_per_gpu)
464
+
465
+ if args.use_flash_attention:
466
+ fp16 = False
467
+ bf16 = True
468
+ else:
469
+ fp16 = True
470
+ bf16 = False
471
+
472
+ # hard coded training args
473
+ training_args = TrainingArguments(
474
+ num_train_epochs=args.num_train_epochs,
475
+ per_device_train_batch_size=args.batch_size_per_gpu,
476
+ gradient_checkpointing=True,
477
+ gradient_checkpointing_kwargs={'use_reentrant': False},
478
+ gradient_accumulation_steps=gradient_accumulation_steps,
479
+ optim='adamw_torch',
480
+ adam_beta1=0.9,
481
+ adam_beta2=0.95,
482
+ adam_epsilon=1e-7,
483
+ learning_rate=args.learning_rate,
484
+ weight_decay=args.wd,
485
+ max_grad_norm=1.0,
486
+ lr_scheduler_type='linear',
487
+ warmup_steps=50,
488
+ logging_steps=10,
489
+ output_dir=args.output_dir,
490
+ save_strategy='no',
491
+ save_total_limit=10,
492
+ save_only_model=True,
493
+ bf16=bf16,
494
+ fp16=fp16,
495
+ remove_unused_columns=False,
496
+ report_to='none',
497
+ deepspeed=None,
498
+ disable_tqdm=not args.tqdm,
499
+ dataloader_num_workers=4,
500
+ ddp_find_unused_parameters=True, # for unused SigLIP layers
501
+ )
502
+
503
+ # eval before fine-tuning
504
+ out_path = Path(training_args.output_dir)
505
+ out_path.mkdir(parents=True, exist_ok=True)
506
+
507
+ acc = evaluate(
508
+ model,
509
+ processor,
510
+ eval_dataset,
511
+ save_path=out_path / 'eval_before.json',
512
+ disable_tqdm=not args.tqdm,
513
+ eval_batch_size=args.batch_size_per_gpu,
514
+ )
515
+ if accelerator.is_main_process:
516
+ print(f'Accuracy before finetuning: {acc}')
517
+
518
+ trainer = Trainer(
519
+ model=model,
520
+ args=training_args,
521
+ data_collator=pmc_vqa_collate_fn,
522
+ train_dataset=train_dataset,
523
+ )
524
+ trainer.train()
525
+ trainer.save_model()
526
+ accelerator.wait_for_everyone()
527
+
528
+ # eval after fine-tuning (load saved checkpoint)
529
+ # first try to clear GPU memory
530
+ del model
531
+ del trainer
532
+ __import__('gc').collect()
533
+ torch.cuda.empty_cache()
534
+
535
+ # reload the model for inference
536
+ model = AutoModelForCausalLM.from_pretrained(
537
+ training_args.output_dir,
538
+ torch_dtype=torch.bfloat16 if args.use_flash_attention else torch.float32,
539
+ trust_remote_code=True,
540
+ _attn_implementation='flash_attention_2' if args.use_flash_attention else 'sdpa',
541
+ ).to('cuda')
542
+
543
+ acc = evaluate(
544
+ model,
545
+ processor,
546
+ eval_dataset,
547
+ save_path=out_path / 'eval_after.json',
548
+ disable_tqdm=not args.tqdm,
549
+ eval_batch_size=args.batch_size_per_gpu,
550
+ )
551
+ if accelerator.is_main_process:
552
+ print(f'Accuracy after finetuning: {acc}')
553
+
554
+
555
+ if __name__ == '__main__':
556
+ main()
models/Phi-4-multimodal-instruct/sample_inference_phi4mm.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import torch
4
+ from PIL import Image
5
+ import soundfile
6
+ from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
7
+
8
+ model_path = './'
9
+
10
+ kwargs = {}
11
+ kwargs['torch_dtype'] = torch.bfloat16
12
+
13
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
14
+ print(processor.tokenizer)
15
+
16
+ model = AutoModelForCausalLM.from_pretrained(
17
+ model_path,
18
+ trust_remote_code=True,
19
+ torch_dtype='auto',
20
+ _attn_implementation='flash_attention_2',
21
+ ).cuda()
22
+ print("model.config._attn_implementation:", model.config._attn_implementation)
23
+
24
+ generation_config = GenerationConfig.from_pretrained(model_path, 'generation_config.json')
25
+
26
+ user_prompt = '<|user|>'
27
+ assistant_prompt = '<|assistant|>'
28
+ prompt_suffix = '<|end|>'
29
+
30
+ #################################################### text-only ####################################################
31
+ prompt = f'{user_prompt}what is the answer for 1+1? Explain it.{prompt_suffix}{assistant_prompt}'
32
+ print(f'>>> Prompt\n{prompt}')
33
+ inputs = processor(prompt, images=None, return_tensors='pt').to('cuda:0')
34
+
35
+ generate_ids = model.generate(
36
+ **inputs,
37
+ max_new_tokens=1000,
38
+ generation_config=generation_config,
39
+ )
40
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
41
+ response = processor.batch_decode(
42
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
43
+ )[0]
44
+
45
+ print(f'>>> Response\n{response}')
46
+
47
+ #################################################### vision (single-turn) ####################################################
48
+ # single-image prompt
49
+ prompt = f'{user_prompt}<|image_1|>What is shown in this image?{prompt_suffix}{assistant_prompt}'
50
+ url = 'https://www.ilankelman.org/stopsigns/australia.jpg'
51
+ print(f'>>> Prompt\n{prompt}')
52
+ image = Image.open(requests.get(url, stream=True).raw)
53
+ inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')
54
+ generate_ids = model.generate(
55
+ **inputs,
56
+ max_new_tokens=1000,
57
+ generation_config=generation_config,
58
+ )
59
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
60
+ response = processor.batch_decode(
61
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
62
+ )[0]
63
+ print(f'>>> Response\n{response}')
64
+
65
+ #################################################### vision (multi-turn) ####################################################
66
+ # chat template
67
+ chat = [
68
+ {'role': 'user', 'content': f'<|image_1|>What is shown in this image?'},
69
+ {
70
+ 'role': 'assistant',
71
+ 'content': "The image depicts a street scene with a prominent red stop sign in the foreground. The background showcases a building with traditional Chinese architecture, characterized by its red roof and ornate decorations. There are also several statues of lions, which are common in Chinese culture, positioned in front of the building. The street is lined with various shops and businesses, and there's a car passing by.",
72
+ },
73
+ {'role': 'user', 'content': 'What is so special about this image'},
74
+ ]
75
+ url = 'https://www.ilankelman.org/stopsigns/australia.jpg'
76
+ image = Image.open(requests.get(url, stream=True).raw)
77
+ prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
78
+ # need to remove last <|endoftext|> if it is there, which is used for training, not inference. For training, make sure to add <|endoftext|> in the end.
79
+ if prompt.endswith('<|endoftext|>'):
80
+ prompt = prompt.rstrip('<|endoftext|>')
81
+
82
+ print(f'>>> Prompt\n{prompt}')
83
+
84
+ inputs = processor(prompt, [image], return_tensors='pt').to('cuda:0')
85
+ generate_ids = model.generate(
86
+ **inputs,
87
+ max_new_tokens=1000,
88
+ generation_config=generation_config,
89
+ )
90
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
91
+ response = processor.batch_decode(
92
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
93
+ )[0]
94
+ print(f'>>> Response\n{response}')
95
+
96
+ ########################### vision (multi-frame) ################################
97
+ images = []
98
+ placeholder = ''
99
+ for i in range(1, 5):
100
+ url = f'https://image.slidesharecdn.com/azureintroduction-191206101932/75/Introduction-to-Microsoft-Azure-Cloud-{i}-2048.jpg'
101
+ images.append(Image.open(requests.get(url, stream=True).raw))
102
+ placeholder += f'<|image_{i}|>'
103
+
104
+ messages = [
105
+ {'role': 'user', 'content': placeholder + 'Summarize the deck of slides.'},
106
+ ]
107
+
108
+ prompt = processor.tokenizer.apply_chat_template(
109
+ messages, tokenize=False, add_generation_prompt=True
110
+ )
111
+
112
+ print(f'>>> Prompt\n{prompt}')
113
+
114
+ inputs = processor(prompt, images, return_tensors='pt').to('cuda:0')
115
+
116
+ generation_args = {
117
+ 'max_new_tokens': 1000,
118
+ 'temperature': 0.0,
119
+ 'do_sample': False,
120
+ }
121
+
122
+ generate_ids = model.generate(
123
+ **inputs, **generation_args, generation_config=generation_config,
124
+ )
125
+
126
+ # remove input tokens
127
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
128
+ response = processor.batch_decode(
129
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
130
+ )[0]
131
+
132
+ print(response)
133
+
134
+ # NOTE: Please prepare the audio file 'examples/what_is_the_traffic_sign_in_the_image.wav'
135
+ # and audio file 'examples/what_is_shown_in_this_image.wav' before running the following code
136
+ # Basically you can record your own voice for the question "What is the traffic sign in the image?" in "examples/what_is_the_traffic_sign_in_the_image.wav".
137
+ # And you can record your own voice for the question "What is shown in this image?" in "examples/what_is_shown_in_this_image.wav".
138
+
139
+ AUDIO_FILE_1 = 'examples/what_is_the_traffic_sign_in_the_image.wav'
140
+ AUDIO_FILE_2 = 'examples/what_is_shown_in_this_image.wav'
141
+
142
+ if not os.path.exists(AUDIO_FILE_1):
143
+ raise FileNotFoundError(f'Please prepare the audio file {AUDIO_FILE_1} before running the following code.')
144
+ ########################## vision-speech ################################
145
+ prompt = f'{user_prompt}<|image_1|><|audio_1|>{prompt_suffix}{assistant_prompt}'
146
+ url = 'https://www.ilankelman.org/stopsigns/australia.jpg'
147
+ print(f'>>> Prompt\n{prompt}')
148
+ image = Image.open(requests.get(url, stream=True).raw)
149
+ audio = soundfile.read(AUDIO_FILE_1)
150
+ inputs = processor(text=prompt, images=[image], audios=[audio], return_tensors='pt').to('cuda:0')
151
+ generate_ids = model.generate(
152
+ **inputs,
153
+ max_new_tokens=1000,
154
+ generation_config=generation_config,
155
+ )
156
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
157
+ response = processor.batch_decode(
158
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
159
+ )[0]
160
+ print(f'>>> Response\n{response}')
161
+
162
+ ########################## speech only ################################
163
+ speech_prompt = "Based on the attached audio, generate a comprehensive text transcription of the spoken content."
164
+ prompt = f'{user_prompt}<|audio_1|>{speech_prompt}{prompt_suffix}{assistant_prompt}'
165
+
166
+ print(f'>>> Prompt\n{prompt}')
167
+ audio = soundfile.read(AUDIO_FILE_1)
168
+ inputs = processor(text=prompt, audios=[audio], return_tensors='pt').to('cuda:0')
169
+ generate_ids = model.generate(
170
+ **inputs,
171
+ max_new_tokens=1000,
172
+ generation_config=generation_config,
173
+ )
174
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
175
+ response = processor.batch_decode(
176
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
177
+ )[0]
178
+ print(f'>>> Response\n{response}')
179
+
180
+ if not os.path.exists(AUDIO_FILE_2):
181
+ raise FileNotFoundError(f'Please prepare the audio file {AUDIO_FILE_2} before running the following code.')
182
+ ########################### speech only (multi-turn) ################################
183
+ audio_1 = soundfile.read(AUDIO_FILE_2)
184
+ audio_2 = soundfile.read(AUDIO_FILE_1)
185
+ chat = [
186
+ {'role': 'user', 'content': f'<|audio_1|>Based on the attached audio, generate a comprehensive text transcription of the spoken content.'},
187
+ {
188
+ 'role': 'assistant',
189
+ 'content': "What is shown in this image.",
190
+ },
191
+ {'role': 'user', 'content': f'<|audio_2|>Based on the attached audio, generate a comprehensive text transcription of the spoken content.'},
192
+ ]
193
+ prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
194
+ # need to remove last <|endoftext|> if it is there, which is used for training, not inference. For training, make sure to add <|endoftext|> in the end.
195
+ if prompt.endswith('<|endoftext|>'):
196
+ prompt = prompt.rstrip('<|endoftext|>')
197
+
198
+ print(f'>>> Prompt\n{prompt}')
199
+
200
+ inputs = processor(text=prompt, audios=[audio_1, audio_2], return_tensors='pt').to('cuda:0')
201
+ generate_ids = model.generate(
202
+ **inputs,
203
+ max_new_tokens=1000,
204
+ generation_config=generation_config,
205
+ )
206
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
207
+ response = processor.batch_decode(
208
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
209
+ )[0]
210
+ print(f'>>> Response\n{response}')
211
+
212
+ #################################################### vision-speech (multi-turn) ####################################################
213
+ # chat template
214
+ audio_1 = soundfile.read(AUDIO_FILE_2)
215
+ audio_2 = soundfile.read(AUDIO_FILE_1)
216
+ chat = [
217
+ {'role': 'user', 'content': f'<|image_1|><|audio_1|>'},
218
+ {
219
+ 'role': 'assistant',
220
+ 'content': "The image depicts a street scene with a prominent red stop sign in the foreground. The background showcases a building with traditional Chinese architecture, characterized by its red roof and ornate decorations. There are also several statues of lions, which are common in Chinese culture, positioned in front of the building. The street is lined with various shops and businesses, and there's a car passing by.",
221
+ },
222
+ {'role': 'user', 'content': f'<|audio_2|>'},
223
+ ]
224
+ url = 'https://www.ilankelman.org/stopsigns/australia.jpg'
225
+ image = Image.open(requests.get(url, stream=True).raw)
226
+ prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
227
+ # need to remove last <|endoftext|> if it is there, which is used for training, not inference. For training, make sure to add <|endoftext|> in the end.
228
+ if prompt.endswith('<|endoftext|>'):
229
+ prompt = prompt.rstrip('<|endoftext|>')
230
+
231
+ print(f'>>> Prompt\n{prompt}')
232
+
233
+ inputs = processor(text=prompt, images=[image], audios=[audio_1, audio_2], return_tensors='pt').to('cuda:0')
234
+ generate_ids = model.generate(
235
+ **inputs,
236
+ max_new_tokens=1000,
237
+ generation_config=generation_config,
238
+ )
239
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]
240
+ response = processor.batch_decode(
241
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
242
+ )[0]
243
+ print(f'>>> Response\n{response}')
models/Phi-4-multimodal-instruct/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
models/Phi-4-multimodal-instruct/speech-lora/adapter_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_mapping": null,
3
+ "base_model_name_or_path": "TBA",
4
+ "bias": "none",
5
+ "fan_in_fan_out": false,
6
+ "inference_mode": true,
7
+ "init_lora_weights": true,
8
+ "layers_pattern": null,
9
+ "layers_to_transform": null,
10
+ "lora_alpha": 640,
11
+ "lora_dropout": 0.01,
12
+ "modules_to_save": [],
13
+ "peft_type": "LORA",
14
+ "r": 320,
15
+ "revision": null,
16
+ "target_modules": [
17
+ "qkv_proj",
18
+ "o_proj",
19
+ "gate_up_proj",
20
+ "down_proj"
21
+ ],
22
+ "task_type": "CAUSAL_LM"
23
+ }
models/Phi-4-multimodal-instruct/speech-lora/added_tokens.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|/tool_call|>": 200026,
3
+ "<|/tool|>": 200024,
4
+ "<|assistant|>": 200019,
5
+ "<|end|>": 200020,
6
+ "<|system|>": 200022,
7
+ "<|tag|>": 200028,
8
+ "<|tool_call|>": 200025,
9
+ "<|tool_response|>": 200027,
10
+ "<|tool|>": 200023,
11
+ "<|user|>": 200021
12
+ }
models/Phi-4-multimodal-instruct/speech-lora/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
models/Phi-4-multimodal-instruct/speech-lora/tokenizer_config.json ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "200010": {
5
+ "content": "<|endoftext10|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "200011": {
13
+ "content": "<|endoftext11|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "199999": {
21
+ "content": "<|endoftext|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "200018": {
29
+ "content": "<|endofprompt|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "200019": {
37
+ "content": "<|assistant|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": true,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "200020": {
45
+ "content": "<|end|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": true,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "200021": {
53
+ "content": "<|user|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": true,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "200022": {
61
+ "content": "<|system|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": true,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "200023": {
69
+ "content": "<|tool|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": true,
73
+ "single_word": false,
74
+ "special": false
75
+ },
76
+ "200024": {
77
+ "content": "<|/tool|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": true,
81
+ "single_word": false,
82
+ "special": false
83
+ },
84
+ "200025": {
85
+ "content": "<|tool_call|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": true,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "200026": {
93
+ "content": "<|/tool_call|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": true,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "200027": {
101
+ "content": "<|tool_response|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": true,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "200028": {
109
+ "content": "<|tag|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": true,
113
+ "single_word": false,
114
+ "special": true
115
+ }
116
+ },
117
+ "bos_token": "<|endoftext|>",
118
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' and 'tools' in message and message['tools'] is not none %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|tool|>' + message['tools'] + '<|/tool|>' + '<|end|>' }}{% else %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|end|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>' }}{% else %}{{ eos_token }}{% endif %}",
119
+ "clean_up_tokenization_spaces": false,
120
+ "eos_token": "<|endoftext|>",
121
+ "model_max_length": 128000,
122
+ "pad_token": "<|endoftext|>",
123
+ "tokenizer_class": "GPT2TokenizerFast",
124
+ "unk_token": "<|endoftext|>"
125
+ }
models/Phi-4-multimodal-instruct/speech-lora/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/Phi-4-multimodal-instruct/speech_conformer_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
models/Phi-4-multimodal-instruct/tokenizer_config.json ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "200010": {
5
+ "content": "<|endoftext10|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "200011": {
13
+ "content": "<|endoftext11|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "199999": {
21
+ "content": "<|endoftext|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "200018": {
29
+ "content": "<|endofprompt|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "200019": {
37
+ "content": "<|assistant|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": true,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "200020": {
45
+ "content": "<|end|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": true,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "200021": {
53
+ "content": "<|user|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": true,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "200022": {
61
+ "content": "<|system|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": true,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "200023": {
69
+ "content": "<|tool|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": true,
73
+ "single_word": false,
74
+ "special": false
75
+ },
76
+ "200024": {
77
+ "content": "<|/tool|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": true,
81
+ "single_word": false,
82
+ "special": false
83
+ },
84
+ "200025": {
85
+ "content": "<|tool_call|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": true,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "200026": {
93
+ "content": "<|/tool_call|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": true,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "200027": {
101
+ "content": "<|tool_response|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": true,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "200028": {
109
+ "content": "<|tag|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": true,
113
+ "single_word": false,
114
+ "special": true
115
+ }
116
+ },
117
+ "bos_token": "<|endoftext|>",
118
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' and 'tools' in message and message['tools'] is not none %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|tool|>' + message['tools'] + '<|/tool|>' + '<|end|>' }}{% else %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|end|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>' }}{% else %}{{ eos_token }}{% endif %}",
119
+ "clean_up_tokenization_spaces": false,
120
+ "eos_token": "<|endoftext|>",
121
+ "model_max_length": 131072,
122
+ "pad_token": "<|endoftext|>",
123
+ "tokenizer_class": "GPT2TokenizerFast",
124
+ "unk_token": "<|endoftext|>"
125
+ }
models/Phi-4-multimodal-instruct/vision-lora/adapter_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_mapping": null,
3
+ "base_model_name_or_path": "TBA",
4
+ "bias": "none",
5
+ "fan_in_fan_out": false,
6
+ "inference_mode": true,
7
+ "init_lora_weights": true,
8
+ "layers_pattern": null,
9
+ "layers_to_transform": null,
10
+ "lora_alpha": 512,
11
+ "lora_dropout": 0.0,
12
+ "modules_to_save": [],
13
+ "peft_type": "LORA",
14
+ "r": 256,
15
+ "revision": null,
16
+ "target_modules": [
17
+ "qkv_proj",
18
+ "o_proj",
19
+ "gate_up_proj",
20
+ "down_proj"
21
+ ],
22
+ "task_type": "CAUSAL_LM"
23
+ }
models/Phi-4-multimodal-instruct/vision-lora/added_tokens.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|/tool_call|>": 200026,
3
+ "<|/tool|>": 200024,
4
+ "<|assistant|>": 200019,
5
+ "<|end|>": 200020,
6
+ "<|system|>": 200022,
7
+ "<|tag|>": 200028,
8
+ "<|tool_call|>": 200025,
9
+ "<|tool_response|>": 200027,
10
+ "<|tool|>": 200023,
11
+ "<|user|>": 200021
12
+ }
models/Phi-4-multimodal-instruct/vision-lora/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
models/Phi-4-multimodal-instruct/vision-lora/tokenizer_config.json ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "200010": {
5
+ "content": "<|endoftext10|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "200011": {
13
+ "content": "<|endoftext11|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "199999": {
21
+ "content": "<|endoftext|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "200018": {
29
+ "content": "<|endofprompt|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "200019": {
37
+ "content": "<|assistant|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": true,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "200020": {
45
+ "content": "<|end|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": true,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "200021": {
53
+ "content": "<|user|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": true,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "200022": {
61
+ "content": "<|system|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": true,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "200023": {
69
+ "content": "<|tool|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": true,
73
+ "single_word": false,
74
+ "special": false
75
+ },
76
+ "200024": {
77
+ "content": "<|/tool|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": true,
81
+ "single_word": false,
82
+ "special": false
83
+ },
84
+ "200025": {
85
+ "content": "<|tool_call|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": true,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "200026": {
93
+ "content": "<|/tool_call|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": true,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "200027": {
101
+ "content": "<|tool_response|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": true,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "200028": {
109
+ "content": "<|tag|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": true,
113
+ "single_word": false,
114
+ "special": true
115
+ }
116
+ },
117
+ "bos_token": "<|endoftext|>",
118
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' and 'tools' in message and message['tools'] is not none %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|tool|>' + message['tools'] + '<|/tool|>' + '<|end|>' }}{% else %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|end|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>' }}{% else %}{{ eos_token }}{% endif %}",
119
+ "clean_up_tokenization_spaces": false,
120
+ "eos_token": "<|endoftext|>",
121
+ "model_max_length": 128000,
122
+ "pad_token": "<|endoftext|>",
123
+ "tokenizer_class": "GPT2TokenizerFast",
124
+ "unk_token": "<|endoftext|>"
125
+ }
models/Phi-4-multimodal-instruct/vision-lora/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/Phi-4-multimodal-instruct/vision_siglip_navit.py ADDED
@@ -0,0 +1,1717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """ Siglip model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ SIGLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "google/siglip-base-patch16-224": "https://huggingface.co/google/siglip-base-patch16-224/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class SiglipTextConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`SiglipTextModel`]. It is used to instantiate a
34
+ Siglip text encoder according to the specified arguments, defining the model architecture. Instantiating a
35
+ configuration with the defaults will yield a similar configuration to that of the text encoder of the Siglip
36
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32000):
41
+ Vocabulary size of the Siglip text model. Defines the number of different tokens that can be represented by
42
+ the `inputs_ids` passed when calling [`SiglipModel`].
43
+ hidden_size (`int`, *optional*, defaults to 768):
44
+ Dimensionality of the encoder layers and the pooler layer.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ max_position_embeddings (`int`, *optional*, defaults to 64):
52
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
53
+ just in case (e.g., 512 or 1024 or 2048).
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
55
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
56
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
57
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
58
+ The epsilon used by the layer normalization layers.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for the attention probabilities.
61
+ pad_token_id (`int`, *optional*, defaults to 1):
62
+ The id of the padding token in the vocabulary.
63
+ bos_token_id (`int`, *optional*, defaults to 49406):
64
+ The id of the beginning-of-sequence token in the vocabulary.
65
+ eos_token_id (`int`, *optional*, defaults to 49407):
66
+ The id of the end-of-sequence token in the vocabulary.
67
+ Example:
68
+ ```python
69
+ >>> from transformers import SiglipTextConfig, SiglipTextModel
70
+ >>> # Initializing a SiglipTextConfig with google/siglip-base-patch16-224 style configuration
71
+ >>> configuration = SiglipTextConfig()
72
+ >>> # Initializing a SiglipTextModel (with random weights) from the google/siglip-base-patch16-224 style configuration
73
+ >>> model = SiglipTextModel(configuration)
74
+ >>> # Accessing the model configuration
75
+ >>> configuration = model.config
76
+ ```"""
77
+
78
+ model_type = "siglip_text_model"
79
+
80
+ def __init__(
81
+ self,
82
+ vocab_size=32000,
83
+ hidden_size=768,
84
+ intermediate_size=3072,
85
+ num_hidden_layers=12,
86
+ num_attention_heads=12,
87
+ max_position_embeddings=64,
88
+ hidden_act="gelu_pytorch_tanh",
89
+ layer_norm_eps=1e-6,
90
+ attention_dropout=0.0,
91
+ # This differs from `CLIPTokenizer`'s default and from openai/siglip
92
+ # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
93
+ pad_token_id=1,
94
+ bos_token_id=49406,
95
+ eos_token_id=49407,
96
+ _flash_attn_2_enabled=True,
97
+ **kwargs,
98
+ ):
99
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
100
+
101
+ self.vocab_size = vocab_size
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.layer_norm_eps = layer_norm_eps
108
+ self.hidden_act = hidden_act
109
+ self.attention_dropout = attention_dropout
110
+ self._flash_attn_2_enabled = _flash_attn_2_enabled
111
+
112
+ @classmethod
113
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
114
+ cls._set_token_in_kwargs(kwargs)
115
+
116
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
117
+
118
+ # get the text config dict if we are loading from SiglipConfig
119
+ if config_dict.get("model_type") == "siglip":
120
+ config_dict = config_dict["text_config"]
121
+
122
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
123
+ logger.warning(
124
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
125
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
126
+ )
127
+
128
+ return cls.from_dict(config_dict, **kwargs)
129
+
130
+
131
+ class SiglipVisionConfig(PretrainedConfig):
132
+ r"""
133
+ This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
134
+ Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
135
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
136
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
137
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
138
+ documentation from [`PretrainedConfig`] for more information.
139
+ Args:
140
+ hidden_size (`int`, *optional*, defaults to 768):
141
+ Dimensionality of the encoder layers and the pooler layer.
142
+ intermediate_size (`int`, *optional*, defaults to 3072):
143
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
144
+ num_hidden_layers (`int`, *optional*, defaults to 12):
145
+ Number of hidden layers in the Transformer encoder.
146
+ num_attention_heads (`int`, *optional*, defaults to 12):
147
+ Number of attention heads for each attention layer in the Transformer encoder.
148
+ num_channels (`int`, *optional*, defaults to 3):
149
+ Number of channels in the input images.
150
+ image_size (`int`, *optional*, defaults to 224):
151
+ The size (resolution) of each image.
152
+ patch_size (`int`, *optional*, defaults to 16):
153
+ The size (resolution) of each patch.
154
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
155
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
156
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
157
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
158
+ The epsilon used by the layer normalization layers.
159
+ attention_dropout (`float`, *optional*, defaults to 0.0):
160
+ The dropout ratio for the attention probabilities.
161
+ Example:
162
+ ```python
163
+ >>> from transformers import SiglipVisionConfig, SiglipVisionModel
164
+ >>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
165
+ >>> configuration = SiglipVisionConfig()
166
+ >>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
167
+ >>> model = SiglipVisionModel(configuration)
168
+ >>> # Accessing the model configuration
169
+ >>> configuration = model.config
170
+ ```"""
171
+
172
+ model_type = "siglip_vision_model"
173
+
174
+ def __init__(
175
+ self,
176
+ hidden_size=768,
177
+ intermediate_size=3072,
178
+ num_hidden_layers=12,
179
+ num_attention_heads=12,
180
+ num_channels=3,
181
+ image_size=224,
182
+ patch_size=16,
183
+ hidden_act="gelu_pytorch_tanh",
184
+ layer_norm_eps=1e-6,
185
+ attention_dropout=0.0,
186
+ _flash_attn_2_enabled=True,
187
+ **kwargs,
188
+ ):
189
+ super().__init__(**kwargs)
190
+
191
+ self.hidden_size = hidden_size
192
+ self.intermediate_size = intermediate_size
193
+ self.num_hidden_layers = num_hidden_layers
194
+ self.num_attention_heads = num_attention_heads
195
+ self.num_channels = num_channels
196
+ self.patch_size = patch_size
197
+ self.image_size = image_size
198
+ self.attention_dropout = attention_dropout
199
+ self.layer_norm_eps = layer_norm_eps
200
+ self.hidden_act = hidden_act
201
+ self._flash_attn_2_enabled = _flash_attn_2_enabled
202
+
203
+ @classmethod
204
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
205
+ cls._set_token_in_kwargs(kwargs)
206
+
207
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
208
+
209
+ # get the vision config dict if we are loading from SiglipConfig
210
+ if config_dict.get("model_type") == "siglip":
211
+ config_dict = config_dict["vision_config"]
212
+
213
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
214
+ logger.warning(
215
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
216
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
217
+ )
218
+
219
+ return cls.from_dict(config_dict, **kwargs)
220
+
221
+
222
+ class SiglipConfig(PretrainedConfig):
223
+ r"""
224
+ [`SiglipConfig`] is the configuration class to store the configuration of a [`SiglipModel`]. It is used to
225
+ instantiate a Siglip model according to the specified arguments, defining the text model and vision model configs.
226
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Siglip
227
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
228
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
229
+ documentation from [`PretrainedConfig`] for more information.
230
+ Args:
231
+ text_config (`dict`, *optional*):
232
+ Dictionary of configuration options used to initialize [`SiglipTextConfig`].
233
+ vision_config (`dict`, *optional*):
234
+ Dictionary of configuration options used to initialize [`SiglipVisionConfig`].
235
+ kwargs (*optional*):
236
+ Dictionary of keyword arguments.
237
+ Example:
238
+ ```python
239
+ >>> from transformers import SiglipConfig, SiglipModel
240
+ >>> # Initializing a SiglipConfig with google/siglip-base-patch16-224 style configuration
241
+ >>> configuration = SiglipConfig()
242
+ >>> # Initializing a SiglipModel (with random weights) from the google/siglip-base-patch16-224 style configuration
243
+ >>> model = SiglipModel(configuration)
244
+ >>> # Accessing the model configuration
245
+ >>> configuration = model.config
246
+ >>> # We can also initialize a SiglipConfig from a SiglipTextConfig and a SiglipVisionConfig
247
+ >>> from transformers import SiglipTextConfig, SiglipVisionConfig
248
+ >>> # Initializing a SiglipText and SiglipVision configuration
249
+ >>> config_text = SiglipTextConfig()
250
+ >>> config_vision = SiglipVisionConfig()
251
+ >>> config = SiglipConfig.from_text_vision_configs(config_text, config_vision)
252
+ ```"""
253
+
254
+ model_type = "siglip"
255
+
256
+ def __init__(self, text_config=None, vision_config=None, **kwargs):
257
+ super().__init__(**kwargs)
258
+
259
+ if text_config is None:
260
+ text_config = {}
261
+ logger.info("`text_config` is `None`. Initializing the `SiglipTextConfig` with default values.")
262
+
263
+ if vision_config is None:
264
+ vision_config = {}
265
+ logger.info("`vision_config` is `None`. initializing the `SiglipVisionConfig` with default values.")
266
+
267
+ self.text_config = SiglipTextConfig(**text_config)
268
+ self.vision_config = SiglipVisionConfig(**vision_config)
269
+
270
+ self.initializer_factor = 1.0
271
+
272
+ @classmethod
273
+ def from_text_vision_configs(cls, text_config: SiglipTextConfig, vision_config: SiglipVisionConfig, **kwargs):
274
+ r"""
275
+ Instantiate a [`SiglipConfig`] (or a derived class) from siglip text model configuration and siglip vision
276
+ model configuration.
277
+ Returns:
278
+ [`SiglipConfig`]: An instance of a configuration object
279
+ """
280
+
281
+ return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
282
+
283
+ # coding=utf-8
284
+ # Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
285
+ #
286
+ # Licensed under the Apache License, Version 2.0 (the "License");
287
+ # you may not use this file except in compliance with the License.
288
+ # You may obtain a copy of the License at
289
+ #
290
+ # http://www.apache.org/licenses/LICENSE-2.0
291
+ #
292
+ # Unless required by applicable law or agreed to in writing, software
293
+ # distributed under the License is distributed on an "AS IS" BASIS,
294
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
295
+ # See the License for the specific language governing permissions and
296
+ # limitations under the License.
297
+ """ PyTorch Siglip model."""
298
+
299
+
300
+ import math
301
+ import warnings
302
+ from dataclasses import dataclass
303
+ from typing import Any, Optional, Tuple, Union
304
+
305
+ import numpy as np
306
+ import torch
307
+ import torch.nn.functional as F
308
+ import torch.utils.checkpoint
309
+ from torch import nn
310
+ from torch.nn.init import _calculate_fan_in_and_fan_out
311
+
312
+ from transformers.activations import ACT2FN
313
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
314
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
315
+ from transformers.modeling_utils import PreTrainedModel
316
+ from transformers.utils import (
317
+ ModelOutput,
318
+ add_start_docstrings,
319
+ add_start_docstrings_to_model_forward,
320
+ is_flash_attn_2_available,
321
+ logging,
322
+ replace_return_docstrings,
323
+ )
324
+
325
+ logger = logging.get_logger(__name__)
326
+
327
+ _CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
328
+
329
+ SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
330
+ "google/siglip-base-patch16-224",
331
+ # See all SigLIP models at https://huggingface.co/models?filter=siglip
332
+ ]
333
+
334
+ if is_flash_attn_2_available():
335
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
336
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
337
+
338
+
339
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
340
+ def _get_unpad_data(attention_mask):
341
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
342
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
343
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
344
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
345
+ return (
346
+ indices,
347
+ cu_seqlens,
348
+ max_seqlen_in_batch,
349
+ )
350
+
351
+
352
+ def _trunc_normal_(tensor, mean, std, a, b):
353
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
354
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
355
+ def norm_cdf(x):
356
+ # Computes standard normal cumulative distribution function
357
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
358
+
359
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
360
+ warnings.warn(
361
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
362
+ "The distribution of values may be incorrect.",
363
+ stacklevel=2,
364
+ )
365
+
366
+ # Values are generated by using a truncated uniform distribution and
367
+ # then using the inverse CDF for the normal distribution.
368
+ # Get upper and lower cdf values
369
+ l = norm_cdf((a - mean) / std)
370
+ u = norm_cdf((b - mean) / std)
371
+
372
+ # Uniformly fill tensor with values from [l, u], then translate to
373
+ # [2l-1, 2u-1].
374
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
375
+
376
+ # Use inverse cdf transform for normal distribution to get truncated
377
+ # standard normal
378
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
379
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
380
+ og_dtype = tensor.dtype
381
+ tensor = tensor.to(torch.float32)
382
+ tensor.erfinv_()
383
+ tensor = tensor.to(og_dtype)
384
+ else:
385
+ tensor.erfinv_()
386
+
387
+ # Transform to proper mean, std
388
+ tensor.mul_(std * math.sqrt(2.0))
389
+ tensor.add_(mean)
390
+
391
+ # Clamp to ensure it's in the proper range
392
+ if tensor.dtype == torch.float16:
393
+ # The `clamp_` op is not (yet?) defined in float16+cpu
394
+ tensor = tensor.to(torch.float32)
395
+ tensor.clamp_(min=a, max=b)
396
+ tensor = tensor.to(torch.float16)
397
+ else:
398
+ tensor.clamp_(min=a, max=b)
399
+
400
+
401
+ def trunc_normal_tf_(
402
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
403
+ ) -> torch.Tensor:
404
+ """Fills the input Tensor with values drawn from a truncated
405
+ normal distribution. The values are effectively drawn from the
406
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
407
+ with values outside :math:`[a, b]` redrawn until they are within
408
+ the bounds. The method used for generating the random values works
409
+ best when :math:`a \\leq \text{mean} \\leq b`.
410
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
411
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
412
+ and the result is subsquently scaled and shifted by the mean and std args.
413
+ Args:
414
+ tensor: an n-dimensional `torch.Tensor`
415
+ mean: the mean of the normal distribution
416
+ std: the standard deviation of the normal distribution
417
+ a: the minimum cutoff value
418
+ b: the maximum cutoff value
419
+ """
420
+ with torch.no_grad():
421
+ _trunc_normal_(tensor, 0, 1.0, a, b)
422
+ tensor.mul_(std).add_(mean)
423
+
424
+
425
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
426
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
427
+ if mode == "fan_in":
428
+ denom = fan_in
429
+ elif mode == "fan_out":
430
+ denom = fan_out
431
+ elif mode == "fan_avg":
432
+ denom = (fan_in + fan_out) / 2
433
+
434
+ variance = scale / denom
435
+
436
+ if distribution == "truncated_normal":
437
+ # constant is stddev of standard normal truncated to (-2, 2)
438
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
439
+ elif distribution == "normal":
440
+ with torch.no_grad():
441
+ tensor.normal_(std=math.sqrt(variance))
442
+ elif distribution == "uniform":
443
+ bound = math.sqrt(3 * variance)
444
+ with torch.no_grad():
445
+ tensor.uniform_(-bound, bound)
446
+ else:
447
+ raise ValueError(f"invalid distribution {distribution}")
448
+
449
+
450
+ def lecun_normal_(tensor):
451
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
452
+
453
+
454
+ def default_flax_embed_init(tensor):
455
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
456
+
457
+
458
+ @dataclass
459
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
460
+ class SiglipVisionModelOutput(ModelOutput):
461
+ """
462
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
463
+ Args:
464
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
465
+ The image embeddings obtained by applying the projection layer to the pooler_output.
466
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
467
+ Sequence of hidden-states at the output of the last layer of the model.
468
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
469
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
470
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
471
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
472
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
473
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
474
+ sequence_length)`.
475
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
476
+ heads.
477
+ """
478
+
479
+ image_embeds: Optional[torch.FloatTensor] = None
480
+ last_hidden_state: torch.FloatTensor = None
481
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
482
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
483
+
484
+
485
+ @dataclass
486
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglip
487
+ class SiglipTextModelOutput(ModelOutput):
488
+ """
489
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
490
+ Args:
491
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
492
+ The text embeddings obtained by applying the projection layer to the pooler_output.
493
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
494
+ Sequence of hidden-states at the output of the last layer of the model.
495
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
496
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
497
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
498
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
499
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
500
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
501
+ sequence_length)`.
502
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
503
+ heads.
504
+ """
505
+
506
+ text_embeds: Optional[torch.FloatTensor] = None
507
+ last_hidden_state: torch.FloatTensor = None
508
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
509
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
510
+
511
+
512
+ @dataclass
513
+ # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglip
514
+ class SiglipOutput(ModelOutput):
515
+ """
516
+ Args:
517
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
518
+ Contrastive loss for image-text similarity.
519
+ logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
520
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
521
+ similarity scores.
522
+ logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
523
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
524
+ similarity scores.
525
+ text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
526
+ The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
527
+ image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
528
+ The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
529
+ text_model_output(`BaseModelOutputWithPooling`):
530
+ The output of the [`SiglipTextModel`].
531
+ vision_model_output(`BaseModelOutputWithPooling`):
532
+ The output of the [`SiglipVisionModel`].
533
+ """
534
+
535
+ loss: Optional[torch.FloatTensor] = None
536
+ logits_per_image: torch.FloatTensor = None
537
+ logits_per_text: torch.FloatTensor = None
538
+ text_embeds: torch.FloatTensor = None
539
+ image_embeds: torch.FloatTensor = None
540
+ text_model_output: BaseModelOutputWithPooling = None
541
+ vision_model_output: BaseModelOutputWithPooling = None
542
+
543
+ def to_tuple(self) -> Tuple[Any]:
544
+ return tuple(
545
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
546
+ for k in self.keys()
547
+ )
548
+
549
+
550
+ class SiglipVisionEmbeddings(nn.Module):
551
+ def __init__(self, config: SiglipVisionConfig):
552
+ super().__init__()
553
+ self.config = config
554
+ self.embed_dim = config.hidden_size
555
+ self.image_size = config.image_size
556
+ self.patch_size = config.patch_size
557
+
558
+ self.patch_embedding = nn.Conv2d(
559
+ in_channels=config.num_channels,
560
+ out_channels=self.embed_dim,
561
+ kernel_size=self.patch_size,
562
+ stride=self.patch_size,
563
+ padding="valid",
564
+ )
565
+
566
+ self.num_patches_per_side = self.image_size // self.patch_size
567
+ self.num_patches = self.num_patches_per_side**2
568
+ self.num_positions = self.num_patches
569
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
570
+
571
+ def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor:
572
+ batch_size = pixel_values.size(0)
573
+
574
+ patch_embeds = self.patch_embedding(pixel_values)
575
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
576
+
577
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
578
+ max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
579
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
580
+ position_ids = torch.full(
581
+ size=(
582
+ batch_size,
583
+ max_nb_patches_h * max_nb_patches_w,
584
+ ),
585
+ fill_value=0,
586
+ )
587
+
588
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
589
+ nb_patches_h = p_attn_mask[:, 0].sum()
590
+ nb_patches_w = p_attn_mask[0].sum()
591
+
592
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
593
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
594
+
595
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
596
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
597
+
598
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
599
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
600
+
601
+ position_ids = position_ids.to(self.position_embedding.weight.device)
602
+
603
+ embeddings = embeddings + self.position_embedding(position_ids)
604
+ return embeddings
605
+
606
+
607
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglip
608
+ class SiglipTextEmbeddings(nn.Module):
609
+ def __init__(self, config: SiglipTextConfig):
610
+ super().__init__()
611
+ embed_dim = config.hidden_size
612
+
613
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
614
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
615
+
616
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
617
+ self.register_buffer(
618
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
619
+ )
620
+
621
+ def forward(
622
+ self,
623
+ input_ids: Optional[torch.LongTensor] = None,
624
+ position_ids: Optional[torch.LongTensor] = None,
625
+ inputs_embeds: Optional[torch.FloatTensor] = None,
626
+ ) -> torch.Tensor:
627
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
628
+
629
+ if position_ids is None:
630
+ position_ids = self.position_ids[:, :seq_length]
631
+
632
+ if inputs_embeds is None:
633
+ inputs_embeds = self.token_embedding(input_ids)
634
+
635
+ position_embeddings = self.position_embedding(position_ids)
636
+ embeddings = inputs_embeds + position_embeddings
637
+
638
+ return embeddings
639
+
640
+
641
+ class SiglipAttention(nn.Module):
642
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
643
+
644
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.config = config
648
+ self.embed_dim = config.hidden_size
649
+ self.num_heads = config.num_attention_heads
650
+ self.head_dim = self.embed_dim // self.num_heads
651
+ if self.head_dim * self.num_heads != self.embed_dim:
652
+ raise ValueError(
653
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
654
+ f" {self.num_heads})."
655
+ )
656
+ self.scale = self.head_dim**-0.5
657
+ self.dropout = config.attention_dropout
658
+
659
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
660
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
661
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
662
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
663
+
664
+ def forward(
665
+ self,
666
+ hidden_states: torch.Tensor,
667
+ attention_mask: Optional[torch.Tensor] = None,
668
+ output_attentions: Optional[bool] = False,
669
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
670
+ """Input shape: Batch x Time x Channel"""
671
+
672
+ batch_size, q_len, _ = hidden_states.size()
673
+
674
+ query_states = self.q_proj(hidden_states)
675
+ key_states = self.k_proj(hidden_states)
676
+ value_states = self.v_proj(hidden_states)
677
+
678
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
679
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
680
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
681
+
682
+ k_v_seq_len = key_states.shape[-2]
683
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
684
+
685
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
686
+ raise ValueError(
687
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
688
+ f" {attn_weights.size()}"
689
+ )
690
+
691
+ if attention_mask is not None:
692
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
693
+ raise ValueError(
694
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
695
+ )
696
+ attn_weights = attn_weights + attention_mask
697
+
698
+ # upcast attention to fp32
699
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
700
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
701
+ attn_output = torch.matmul(attn_weights, value_states)
702
+
703
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
704
+ raise ValueError(
705
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
706
+ f" {attn_output.size()}"
707
+ )
708
+
709
+ attn_output = attn_output.transpose(1, 2).contiguous()
710
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
711
+
712
+ attn_output = self.out_proj(attn_output)
713
+
714
+ return attn_output, attn_weights
715
+
716
+
717
+ class SiglipFlashAttention2(SiglipAttention):
718
+ """
719
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
720
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
721
+ flash attention and deal with padding tokens in case the input contains any of them.
722
+ """
723
+
724
+ def __init__(self, *args, **kwargs):
725
+ super().__init__(*args, **kwargs)
726
+ self.is_causal = False # Hack to make sure we don't use a causal mask
727
+
728
+ def forward(
729
+ self,
730
+ hidden_states: torch.Tensor,
731
+ attention_mask: Optional[torch.LongTensor] = None,
732
+ position_ids: Optional[torch.LongTensor] = None,
733
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
734
+ output_attentions: bool = False,
735
+ use_cache: bool = False,
736
+ **kwargs,
737
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
738
+ output_attentions = False
739
+
740
+ bsz, q_len, _ = hidden_states.size()
741
+
742
+ query_states = self.q_proj(hidden_states)
743
+ key_states = self.k_proj(hidden_states)
744
+ value_states = self.v_proj(hidden_states)
745
+
746
+ # Flash attention requires the input to have the shape
747
+ # batch_size x seq_length x head_dim x hidden_dim
748
+ # therefore we just need to keep the original shape
749
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
750
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
751
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
752
+
753
+ kv_seq_len = key_states.shape[-2]
754
+ if past_key_value is not None:
755
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
756
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
757
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
758
+
759
+ # if past_key_value is not None:
760
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
761
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
762
+
763
+ # 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
764
+ # to be able to avoid many of these transpose/reshape/view.
765
+ query_states = query_states.transpose(1, 2)
766
+ key_states = key_states.transpose(1, 2)
767
+ value_states = value_states.transpose(1, 2)
768
+
769
+ dropout_rate = self.dropout if self.training else 0.0
770
+
771
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
772
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
773
+ # cast them back in the correct dtype just to be sure everything works as expected.
774
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
775
+ # in fp32. (LlamaRMSNorm handles it correctly)
776
+
777
+ input_dtype = query_states.dtype
778
+ if input_dtype == torch.float32:
779
+ if torch.is_autocast_enabled():
780
+ target_dtype = torch.get_autocast_gpu_dtype()
781
+ # Handle the case where the model is quantized
782
+ elif hasattr(self.config, "_pre_quantization_dtype"):
783
+ target_dtype = self.config._pre_quantization_dtype
784
+ else:
785
+ target_dtype = self.q_proj.weight.dtype
786
+
787
+ logger.warning_once(
788
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
789
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
790
+ f" {target_dtype}."
791
+ )
792
+
793
+ query_states = query_states.to(target_dtype)
794
+ key_states = key_states.to(target_dtype)
795
+ value_states = value_states.to(target_dtype)
796
+
797
+ attn_output = self._flash_attention_forward(
798
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
799
+ )
800
+
801
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
802
+ attn_output = self.out_proj(attn_output)
803
+
804
+ if not output_attentions:
805
+ attn_weights = None
806
+
807
+ return attn_output, attn_weights
808
+
809
+ def _flash_attention_forward(
810
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
811
+ ):
812
+ """
813
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
814
+ first unpad the input, then computes the attention scores and pad the final attention scores.
815
+ Args:
816
+ query_states (`torch.Tensor`):
817
+ Input query states to be passed to Flash Attention API
818
+ key_states (`torch.Tensor`):
819
+ Input key states to be passed to Flash Attention API
820
+ value_states (`torch.Tensor`):
821
+ Input value states to be passed to Flash Attention API
822
+ attention_mask (`torch.Tensor`):
823
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
824
+ position of padding tokens and 1 for the position of non-padding tokens.
825
+ dropout (`int`, *optional*):
826
+ Attention dropout
827
+ softmax_scale (`float`, *optional*):
828
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
829
+ """
830
+
831
+ # 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__.
832
+ causal = self.is_causal and query_length != 1
833
+
834
+ # Contains at least one padding token in the sequence
835
+ if attention_mask is not None:
836
+ batch_size = query_states.shape[0]
837
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
838
+ query_states, key_states, value_states, attention_mask, query_length
839
+ )
840
+
841
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
842
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
843
+
844
+ attn_output_unpad = flash_attn_varlen_func(
845
+ query_states,
846
+ key_states,
847
+ value_states,
848
+ cu_seqlens_q=cu_seqlens_q,
849
+ cu_seqlens_k=cu_seqlens_k,
850
+ max_seqlen_q=max_seqlen_in_batch_q,
851
+ max_seqlen_k=max_seqlen_in_batch_k,
852
+ dropout_p=dropout,
853
+ softmax_scale=softmax_scale,
854
+ causal=causal,
855
+ )
856
+
857
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
858
+ else:
859
+ attn_output = flash_attn_func(
860
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
861
+ )
862
+
863
+ return attn_output
864
+
865
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
866
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
867
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
868
+
869
+ key_layer = index_first_axis(
870
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
871
+ )
872
+ value_layer = index_first_axis(
873
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
874
+ )
875
+ if query_length == kv_seq_len:
876
+ query_layer = index_first_axis(
877
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
878
+ )
879
+ cu_seqlens_q = cu_seqlens_k
880
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
881
+ indices_q = indices_k
882
+ elif query_length == 1:
883
+ max_seqlen_in_batch_q = 1
884
+ cu_seqlens_q = torch.arange(
885
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
886
+ ) # There is a memcpy here, that is very bad.
887
+ indices_q = cu_seqlens_q[:-1]
888
+ query_layer = query_layer.squeeze(1)
889
+ else:
890
+ # The -q_len: slice assumes left padding.
891
+ attention_mask = attention_mask[:, -query_length:]
892
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
893
+
894
+ return (
895
+ query_layer,
896
+ key_layer,
897
+ value_layer,
898
+ indices_q,
899
+ (cu_seqlens_q, cu_seqlens_k),
900
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
901
+ )
902
+
903
+
904
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
905
+ class SiglipMLP(nn.Module):
906
+ def __init__(self, config):
907
+ super().__init__()
908
+ self.config = config
909
+ self.activation_fn = ACT2FN[config.hidden_act]
910
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
911
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
912
+
913
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
914
+ hidden_states = self.fc1(hidden_states)
915
+ hidden_states = self.activation_fn(hidden_states)
916
+ hidden_states = self.fc2(hidden_states)
917
+ return hidden_states
918
+
919
+
920
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
921
+ class SiglipEncoderLayer(nn.Module):
922
+ def __init__(self, config: SiglipConfig):
923
+ super().__init__()
924
+ self.embed_dim = config.hidden_size
925
+ self.self_attn = (
926
+ SiglipAttention(config)
927
+ if not getattr(config, "_flash_attn_2_enabled", False)
928
+ else SiglipFlashAttention2(config)
929
+ )
930
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
931
+ self.mlp = SiglipMLP(config)
932
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
933
+
934
+ def forward(
935
+ self,
936
+ hidden_states: torch.Tensor,
937
+ attention_mask: torch.Tensor,
938
+ output_attentions: Optional[bool] = False,
939
+ ) -> Tuple[torch.FloatTensor]:
940
+ """
941
+ Args:
942
+ hidden_states (`torch.FloatTensor`):
943
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
944
+ attention_mask (`torch.FloatTensor`):
945
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
946
+ output_attentions (`bool`, *optional*, defaults to `False`):
947
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
948
+ returned tensors for more detail.
949
+ """
950
+ residual = hidden_states
951
+
952
+ hidden_states = self.layer_norm1(hidden_states)
953
+ hidden_states, attn_weights = self.self_attn(
954
+ hidden_states=hidden_states,
955
+ attention_mask=attention_mask,
956
+ output_attentions=output_attentions,
957
+ )
958
+ hidden_states = residual + hidden_states
959
+
960
+ residual = hidden_states
961
+ hidden_states = self.layer_norm2(hidden_states)
962
+ hidden_states = self.mlp(hidden_states)
963
+ hidden_states = residual + hidden_states
964
+
965
+ outputs = (hidden_states,)
966
+
967
+ if output_attentions:
968
+ outputs += (attn_weights,)
969
+
970
+ return outputs
971
+
972
+
973
+ class SiglipPreTrainedModel(PreTrainedModel):
974
+ """
975
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
976
+ models.
977
+ """
978
+
979
+ config_class = SiglipConfig
980
+ base_model_prefix = "siglip"
981
+ supports_gradient_checkpointing = True
982
+
983
+ def _init_weights(self, module):
984
+ """Initialize the weights"""
985
+
986
+ if isinstance(module, SiglipVisionEmbeddings):
987
+ width = (
988
+ self.config.vision_config.hidden_size
989
+ if isinstance(self.config, SiglipConfig)
990
+ else self.config.hidden_size
991
+ )
992
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
993
+ elif isinstance(module, nn.Embedding):
994
+ default_flax_embed_init(module.weight)
995
+ elif isinstance(module, SiglipAttention):
996
+ nn.init.normal_(module.q_proj.weight)
997
+ nn.init.normal_(module.k_proj.weight)
998
+ nn.init.normal_(module.v_proj.weight)
999
+ nn.init.normal_(module.out_proj.weight)
1000
+ nn.init.zeros_(module.q_proj.bias)
1001
+ nn.init.zeros_(module.k_proj.bias)
1002
+ nn.init.zeros_(module.v_proj.bias)
1003
+ nn.init.zeros_(module.out_proj.bias)
1004
+ elif isinstance(module, SiglipMLP):
1005
+ nn.init.normal_(module.fc1.weight)
1006
+ nn.init.normal_(module.fc2.weight)
1007
+ nn.init.normal_(module.fc1.bias, std=1e-6)
1008
+ nn.init.normal_(module.fc2.bias, std=1e-6)
1009
+ elif isinstance(module, SiglipMultiheadAttentionPoolingHead):
1010
+ nn.init.normal_(module.probe.data)
1011
+ nn.init.normal_(module.attention.in_proj_weight.data)
1012
+ nn.init.zeros_(module.attention.in_proj_bias.data)
1013
+ elif isinstance(module, SiglipModel):
1014
+ logit_scale_init = torch.tensor(0.0)
1015
+ module.logit_scale.data.fill_(logit_scale_init)
1016
+ module.logit_bias.data.zero_()
1017
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
1018
+ lecun_normal_(module.weight)
1019
+ if module.bias is not None:
1020
+ nn.init.zeros_(module.bias)
1021
+ elif isinstance(module, nn.LayerNorm):
1022
+ module.bias.data.zero_()
1023
+ module.weight.data.fill_(1.0)
1024
+
1025
+
1026
+ SIGLIP_START_DOCSTRING = r"""
1027
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1028
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1029
+ etc.)
1030
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1031
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1032
+ and behavior.
1033
+ Parameters:
1034
+ config ([`SiglipConfig`]): Model configuration class with all the parameters of the model.
1035
+ Initializing with a config file does not load the weights associated with the model, only the
1036
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1037
+ """
1038
+
1039
+ SIGLIP_TEXT_INPUTS_DOCSTRING = r"""
1040
+ Args:
1041
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1042
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1043
+ it.
1044
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1045
+ [`PreTrainedTokenizer.__call__`] for details.
1046
+ [What are input IDs?](../glossary#input-ids)
1047
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1048
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1049
+ - 1 for tokens that are **not masked**,
1050
+ - 0 for tokens that are **masked**.
1051
+ [What are attention masks?](../glossary#attention-mask)
1052
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1053
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1054
+ config.max_position_embeddings - 1]`.
1055
+ [What are position IDs?](../glossary#position-ids)
1056
+ output_attentions (`bool`, *optional*):
1057
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1058
+ tensors for more detail.
1059
+ output_hidden_states (`bool`, *optional*):
1060
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1061
+ more detail.
1062
+ return_dict (`bool`, *optional*):
1063
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1064
+ """
1065
+
1066
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
1067
+ Args:
1068
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1069
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
1070
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
1071
+ output_attentions (`bool`, *optional*):
1072
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1073
+ tensors for more detail.
1074
+ output_hidden_states (`bool`, *optional*):
1075
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1076
+ more detail.
1077
+ return_dict (`bool`, *optional*):
1078
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1079
+ """
1080
+
1081
+ SIGLIP_INPUTS_DOCSTRING = r"""
1082
+ Args:
1083
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1084
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1085
+ it.
1086
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1087
+ [`PreTrainedTokenizer.__call__`] for details.
1088
+ [What are input IDs?](../glossary#input-ids)
1089
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1090
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1091
+ - 1 for tokens that are **not masked**,
1092
+ - 0 for tokens that are **masked**.
1093
+ [What are attention masks?](../glossary#attention-mask)
1094
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1095
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1096
+ config.max_position_embeddings - 1]`.
1097
+ [What are position IDs?](../glossary#position-ids)
1098
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1099
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
1100
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
1101
+ return_loss (`bool`, *optional*):
1102
+ Whether or not to return the contrastive loss.
1103
+ output_attentions (`bool`, *optional*):
1104
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1105
+ tensors for more detail.
1106
+ output_hidden_states (`bool`, *optional*):
1107
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1108
+ more detail.
1109
+ return_dict (`bool`, *optional*):
1110
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1111
+ """
1112
+
1113
+
1114
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
1115
+ class SiglipEncoder(nn.Module):
1116
+ """
1117
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
1118
+ [`SiglipEncoderLayer`].
1119
+ Args:
1120
+ config: SiglipConfig
1121
+ """
1122
+
1123
+ def __init__(self, config: SiglipConfig):
1124
+ super().__init__()
1125
+ self.config = config
1126
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
1127
+ self.gradient_checkpointing = False
1128
+
1129
+ # Ignore copy
1130
+ def forward(
1131
+ self,
1132
+ inputs_embeds,
1133
+ attention_mask: Optional[torch.Tensor] = None,
1134
+ output_attentions: Optional[bool] = None,
1135
+ output_hidden_states: Optional[bool] = None,
1136
+ return_dict: Optional[bool] = None,
1137
+ ) -> Union[Tuple, BaseModelOutput]:
1138
+ r"""
1139
+ Args:
1140
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1141
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1142
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1143
+ than the model's internal embedding lookup matrix.
1144
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1145
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1146
+ - 1 for tokens that are **not masked**,
1147
+ - 0 for tokens that are **masked**.
1148
+ [What are attention masks?](../glossary#attention-mask)
1149
+ output_attentions (`bool`, *optional*):
1150
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1151
+ returned tensors for more detail.
1152
+ output_hidden_states (`bool`, *optional*):
1153
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1154
+ for more detail.
1155
+ return_dict (`bool`, *optional*):
1156
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1157
+ """
1158
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1159
+ output_hidden_states = (
1160
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1161
+ )
1162
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1163
+
1164
+ encoder_states = () if output_hidden_states else None
1165
+ all_attentions = () if output_attentions else None
1166
+
1167
+ hidden_states = inputs_embeds
1168
+ for encoder_layer in self.layers:
1169
+ if output_hidden_states:
1170
+ encoder_states = encoder_states + (hidden_states,)
1171
+ if self.gradient_checkpointing and self.training:
1172
+ layer_outputs = self._gradient_checkpointing_func(
1173
+ encoder_layer.__call__,
1174
+ hidden_states,
1175
+ attention_mask,
1176
+ output_attentions,
1177
+ )
1178
+ else:
1179
+ layer_outputs = encoder_layer(
1180
+ hidden_states,
1181
+ attention_mask,
1182
+ output_attentions=output_attentions,
1183
+ )
1184
+
1185
+ hidden_states = layer_outputs[0]
1186
+
1187
+ if output_attentions:
1188
+ all_attentions = all_attentions + (layer_outputs[1],)
1189
+
1190
+ if output_hidden_states:
1191
+ encoder_states = encoder_states + (hidden_states,)
1192
+
1193
+ if not return_dict:
1194
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
1195
+ return BaseModelOutput(
1196
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
1197
+ )
1198
+
1199
+
1200
+ class SiglipTextTransformer(nn.Module):
1201
+ def __init__(self, config: SiglipTextConfig):
1202
+ super().__init__()
1203
+ self.config = config
1204
+ embed_dim = config.hidden_size
1205
+ self.embeddings = SiglipTextEmbeddings(config)
1206
+ self.encoder = SiglipEncoder(config)
1207
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1208
+
1209
+ self.head = nn.Linear(embed_dim, embed_dim)
1210
+
1211
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
1212
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig)
1213
+ def forward(
1214
+ self,
1215
+ input_ids: Optional[torch.Tensor] = None,
1216
+ attention_mask: Optional[torch.Tensor] = None,
1217
+ position_ids: Optional[torch.Tensor] = None,
1218
+ output_attentions: Optional[bool] = None,
1219
+ output_hidden_states: Optional[bool] = None,
1220
+ return_dict: Optional[bool] = None,
1221
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1222
+ r"""
1223
+ Returns:
1224
+ """
1225
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1226
+ output_hidden_states = (
1227
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1228
+ )
1229
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1230
+
1231
+ if input_ids is None:
1232
+ raise ValueError("You have to specify input_ids")
1233
+
1234
+ input_shape = input_ids.size()
1235
+ input_ids = input_ids.view(-1, input_shape[-1])
1236
+
1237
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
1238
+
1239
+ # note: SigLIP's text model does not use a causal mask, unlike the original CLIP model.
1240
+ # expand attention_mask
1241
+ if attention_mask is not None:
1242
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
1243
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
1244
+
1245
+ encoder_outputs = self.encoder(
1246
+ inputs_embeds=hidden_states,
1247
+ attention_mask=attention_mask,
1248
+ output_attentions=output_attentions,
1249
+ output_hidden_states=output_hidden_states,
1250
+ return_dict=return_dict,
1251
+ )
1252
+
1253
+ last_hidden_state = encoder_outputs[0]
1254
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
1255
+
1256
+ # Assuming "sticky" EOS tokenization, last token is always EOS.
1257
+ pooled_output = last_hidden_state[:, -1, :]
1258
+ pooled_output = self.head(pooled_output)
1259
+
1260
+ if not return_dict:
1261
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1262
+
1263
+ return BaseModelOutputWithPooling(
1264
+ last_hidden_state=last_hidden_state,
1265
+ pooler_output=pooled_output,
1266
+ hidden_states=encoder_outputs.hidden_states,
1267
+ attentions=encoder_outputs.attentions,
1268
+ )
1269
+
1270
+
1271
+ @add_start_docstrings(
1272
+ """The text model from SigLIP without any head or projection on top.""",
1273
+ SIGLIP_START_DOCSTRING,
1274
+ )
1275
+ class SiglipTextModel(SiglipPreTrainedModel):
1276
+ config_class = SiglipTextConfig
1277
+
1278
+ _no_split_modules = ["SiglipTextEmbeddings", "SiglipEncoderLayer"]
1279
+
1280
+ def __init__(self, config: SiglipTextConfig):
1281
+ super().__init__(config)
1282
+ self.text_model = SiglipTextTransformer(config)
1283
+ # Initialize weights and apply final processing
1284
+ self.post_init()
1285
+
1286
+ def get_input_embeddings(self) -> nn.Module:
1287
+ return self.text_model.embeddings.token_embedding
1288
+
1289
+ def set_input_embeddings(self, value):
1290
+ self.text_model.embeddings.token_embedding = value
1291
+
1292
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
1293
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig)
1294
+ def forward(
1295
+ self,
1296
+ input_ids: Optional[torch.Tensor] = None,
1297
+ attention_mask: Optional[torch.Tensor] = None,
1298
+ position_ids: Optional[torch.Tensor] = None,
1299
+ output_attentions: Optional[bool] = None,
1300
+ output_hidden_states: Optional[bool] = None,
1301
+ return_dict: Optional[bool] = None,
1302
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1303
+ r"""
1304
+ Returns:
1305
+ Examples:
1306
+ ```python
1307
+ >>> from transformers import AutoTokenizer, SiglipTextModel
1308
+ >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
1309
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
1310
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
1311
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
1312
+ >>> outputs = model(**inputs)
1313
+ >>> last_hidden_state = outputs.last_hidden_state
1314
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
1315
+ ```"""
1316
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1317
+
1318
+ return self.text_model(
1319
+ input_ids=input_ids,
1320
+ attention_mask=attention_mask,
1321
+ position_ids=position_ids,
1322
+ output_attentions=output_attentions,
1323
+ output_hidden_states=output_hidden_states,
1324
+ return_dict=return_dict,
1325
+ )
1326
+
1327
+
1328
+ class SiglipVisionTransformer(nn.Module):
1329
+ def __init__(self, config: SiglipVisionConfig):
1330
+ super().__init__()
1331
+ self.config = config
1332
+ embed_dim = config.hidden_size
1333
+
1334
+ self.embeddings = SiglipVisionEmbeddings(config)
1335
+ self.encoder = SiglipEncoder(config)
1336
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1337
+ self.head = SiglipMultiheadAttentionPoolingHead(config)
1338
+
1339
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1340
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
1341
+ def forward(
1342
+ self,
1343
+ pixel_values,
1344
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
1345
+ output_attentions: Optional[bool] = None,
1346
+ output_hidden_states: Optional[bool] = None,
1347
+ return_dict: Optional[bool] = None,
1348
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1349
+ r"""
1350
+ Returns:
1351
+ """
1352
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1353
+ output_hidden_states = (
1354
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1355
+ )
1356
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1357
+
1358
+ batch_size = pixel_values.size(0)
1359
+ if patch_attention_mask is None:
1360
+ patch_attention_mask = torch.ones(
1361
+ size=(
1362
+ batch_size,
1363
+ pixel_values.size(2) // self.config.patch_size,
1364
+ pixel_values.size(3) // self.config.patch_size,
1365
+ ),
1366
+ dtype=torch.bool,
1367
+ device=pixel_values.device,
1368
+ )
1369
+
1370
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
1371
+
1372
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
1373
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
1374
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
1375
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
1376
+ if not torch.any(~patch_attention_mask):
1377
+ attention_mask=None
1378
+ else:
1379
+ attention_mask = (
1380
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
1381
+ if not self.config._flash_attn_2_enabled
1382
+ else patch_attention_mask
1383
+ )
1384
+
1385
+ encoder_outputs = self.encoder(
1386
+ inputs_embeds=hidden_states,
1387
+ attention_mask=attention_mask,
1388
+ output_attentions=output_attentions,
1389
+ output_hidden_states=output_hidden_states,
1390
+ return_dict=return_dict,
1391
+ )
1392
+
1393
+ last_hidden_state = encoder_outputs[0]
1394
+ last_hidden_state = self.post_layernorm(last_hidden_state)
1395
+
1396
+ pooled_output = self.head(
1397
+ hidden_state=last_hidden_state,
1398
+ attention_mask=patch_attention_mask,
1399
+ )
1400
+
1401
+ if not return_dict:
1402
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1403
+
1404
+ return BaseModelOutputWithPooling(
1405
+ last_hidden_state=last_hidden_state,
1406
+ pooler_output=pooled_output,
1407
+ hidden_states=encoder_outputs.hidden_states,
1408
+ attentions=encoder_outputs.attentions,
1409
+ )
1410
+
1411
+
1412
+ class SiglipMultiheadAttentionPoolingHead(nn.Module):
1413
+ """Multihead Attention Pooling."""
1414
+
1415
+ def __init__(self, config: SiglipVisionConfig):
1416
+ super().__init__()
1417
+
1418
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
1419
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
1420
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1421
+ self.mlp = SiglipMLP(config)
1422
+
1423
+ def forward(self, hidden_state, attention_mask):
1424
+ batch_size = hidden_state.shape[0]
1425
+ probe = self.probe.repeat(batch_size, 1, 1)
1426
+
1427
+ hidden_state = self.attention(
1428
+ query=probe, key=hidden_state, value=hidden_state, key_padding_mask=~attention_mask
1429
+ )[0]
1430
+
1431
+ residual = hidden_state
1432
+ hidden_state = self.layernorm(hidden_state)
1433
+ hidden_state = residual + self.mlp(hidden_state)
1434
+
1435
+ return hidden_state[:, 0]
1436
+
1437
+
1438
+ @add_start_docstrings(
1439
+ """The vision model from SigLIP without any head or projection on top.""",
1440
+ SIGLIP_START_DOCSTRING,
1441
+ )
1442
+ class SiglipVisionModel(SiglipPreTrainedModel):
1443
+ config_class = SiglipVisionConfig
1444
+ main_input_name = "pixel_values"
1445
+
1446
+ def __init__(self, config: SiglipVisionConfig):
1447
+ super().__init__(config)
1448
+
1449
+ self.vision_model = SiglipVisionTransformer(config)
1450
+
1451
+ # Initialize weights and apply final processing
1452
+ self.post_init()
1453
+
1454
+ def get_input_embeddings(self) -> nn.Module:
1455
+ return self.vision_model.embeddings.patch_embedding
1456
+
1457
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1458
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
1459
+ def forward(
1460
+ self,
1461
+ pixel_values,
1462
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
1463
+ output_attentions: Optional[bool] = None,
1464
+ output_hidden_states: Optional[bool] = None,
1465
+ return_dict: Optional[bool] = None,
1466
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1467
+ r"""
1468
+ Returns:
1469
+ Examples:
1470
+ ```python
1471
+ >>> from PIL import Image
1472
+ >>> import requests
1473
+ >>> from transformers import AutoProcessor, SiglipVisionModel
1474
+ >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
1475
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1476
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1477
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1478
+ >>> inputs = processor(images=image, return_tensors="pt")
1479
+ >>> outputs = model(**inputs)
1480
+ >>> last_hidden_state = outputs.last_hidden_state
1481
+ >>> pooled_output = outputs.pooler_output # pooled features
1482
+ ```"""
1483
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1484
+
1485
+ return self.vision_model(
1486
+ pixel_values=pixel_values,
1487
+ patch_attention_mask=patch_attention_mask,
1488
+ output_attentions=output_attentions,
1489
+ output_hidden_states=output_hidden_states,
1490
+ return_dict=return_dict,
1491
+ )
1492
+
1493
+
1494
+ @add_start_docstrings(SIGLIP_START_DOCSTRING)
1495
+ class SiglipModel(SiglipPreTrainedModel):
1496
+ config_class = SiglipConfig
1497
+
1498
+ def __init__(self, config: SiglipConfig):
1499
+ super().__init__(config)
1500
+
1501
+ if not isinstance(config.text_config, SiglipTextConfig):
1502
+ raise ValueError(
1503
+ "config.text_config is expected to be of type SiglipTextConfig but is of type"
1504
+ f" {type(config.text_config)}."
1505
+ )
1506
+
1507
+ if not isinstance(config.vision_config, SiglipVisionConfig):
1508
+ raise ValueError(
1509
+ "config.vision_config is expected to be of type SiglipVisionConfig but is of type"
1510
+ f" {type(config.vision_config)}."
1511
+ )
1512
+
1513
+ text_config = config.text_config
1514
+ vision_config = config.vision_config
1515
+
1516
+ self.text_model = SiglipTextTransformer(text_config)
1517
+ self.vision_model = SiglipVisionTransformer(vision_config)
1518
+
1519
+ self.logit_scale = nn.Parameter(torch.randn(1))
1520
+ self.logit_bias = nn.Parameter(torch.randn(1))
1521
+
1522
+ # Initialize weights and apply final processing
1523
+ self.post_init()
1524
+
1525
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
1526
+ def get_text_features(
1527
+ self,
1528
+ input_ids: Optional[torch.Tensor] = None,
1529
+ attention_mask: Optional[torch.Tensor] = None,
1530
+ position_ids: Optional[torch.Tensor] = None,
1531
+ output_attentions: Optional[bool] = None,
1532
+ output_hidden_states: Optional[bool] = None,
1533
+ return_dict: Optional[bool] = None,
1534
+ ) -> torch.FloatTensor:
1535
+ r"""
1536
+ Returns:
1537
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1538
+ applying the projection layer to the pooled output of [`SiglipTextModel`].
1539
+ Examples:
1540
+ ```python
1541
+ >>> from transformers import AutoTokenizer, AutoModel
1542
+ >>> import torch
1543
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1544
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
1545
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
1546
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
1547
+ >>> with torch.no_grad():
1548
+ ... text_features = model.get_text_features(**inputs)
1549
+ ```"""
1550
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
1551
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1552
+ output_hidden_states = (
1553
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1554
+ )
1555
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1556
+
1557
+ text_outputs = self.text_model(
1558
+ input_ids=input_ids,
1559
+ attention_mask=attention_mask,
1560
+ position_ids=position_ids,
1561
+ output_attentions=output_attentions,
1562
+ output_hidden_states=output_hidden_states,
1563
+ return_dict=return_dict,
1564
+ )
1565
+
1566
+ pooled_output = text_outputs[1]
1567
+
1568
+ return pooled_output
1569
+
1570
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1571
+ def get_image_features(
1572
+ self,
1573
+ pixel_values: Optional[torch.FloatTensor] = None,
1574
+ output_attentions: Optional[bool] = None,
1575
+ output_hidden_states: Optional[bool] = None,
1576
+ return_dict: Optional[bool] = None,
1577
+ ) -> torch.FloatTensor:
1578
+ r"""
1579
+ Returns:
1580
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1581
+ applying the projection layer to the pooled output of [`SiglipVisionModel`].
1582
+ Examples:
1583
+ ```python
1584
+ >>> from PIL import Image
1585
+ >>> import requests
1586
+ >>> from transformers import AutoProcessor, AutoModel
1587
+ >>> import torch
1588
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1589
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1590
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1591
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1592
+ >>> inputs = processor(images=image, return_tensors="pt")
1593
+ >>> with torch.no_grad():
1594
+ ... image_features = model.get_image_features(**inputs)
1595
+ ```"""
1596
+ # Use SiglipModel's config for some fields (if specified) instead of those of vision & text components.
1597
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1598
+ output_hidden_states = (
1599
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1600
+ )
1601
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1602
+
1603
+ vision_outputs = self.vision_model(
1604
+ pixel_values=pixel_values,
1605
+ output_attentions=output_attentions,
1606
+ output_hidden_states=output_hidden_states,
1607
+ return_dict=return_dict,
1608
+ )
1609
+
1610
+ pooled_output = vision_outputs[1]
1611
+
1612
+ return pooled_output
1613
+
1614
+ @add_start_docstrings_to_model_forward(SIGLIP_INPUTS_DOCSTRING)
1615
+ @replace_return_docstrings(output_type=SiglipOutput, config_class=SiglipConfig)
1616
+ def forward(
1617
+ self,
1618
+ input_ids: Optional[torch.LongTensor] = None,
1619
+ pixel_values: Optional[torch.FloatTensor] = None,
1620
+ attention_mask: Optional[torch.Tensor] = None,
1621
+ position_ids: Optional[torch.LongTensor] = None,
1622
+ return_loss: Optional[bool] = None,
1623
+ output_attentions: Optional[bool] = None,
1624
+ output_hidden_states: Optional[bool] = None,
1625
+ return_dict: Optional[bool] = None,
1626
+ ) -> Union[Tuple, SiglipOutput]:
1627
+ r"""
1628
+ Returns:
1629
+ Examples:
1630
+ ```python
1631
+ >>> from PIL import Image
1632
+ >>> import requests
1633
+ >>> from transformers import AutoProcessor, AutoModel
1634
+ >>> import torch
1635
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1636
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1637
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1638
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1639
+ >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
1640
+ >>> # important: we pass `padding=max_length` since the model was trained with this
1641
+ >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
1642
+ >>> with torch.no_grad():
1643
+ ... outputs = model(**inputs)
1644
+ >>> logits_per_image = outputs.logits_per_image
1645
+ >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
1646
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
1647
+ 31.9% that image 0 is 'a photo of 2 cats'
1648
+ ```"""
1649
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
1650
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1651
+ output_hidden_states = (
1652
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1653
+ )
1654
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1655
+
1656
+ vision_outputs = self.vision_model(
1657
+ pixel_values=pixel_values,
1658
+ output_attentions=output_attentions,
1659
+ output_hidden_states=output_hidden_states,
1660
+ return_dict=return_dict,
1661
+ )
1662
+
1663
+ text_outputs = self.text_model(
1664
+ input_ids=input_ids,
1665
+ attention_mask=attention_mask,
1666
+ position_ids=position_ids,
1667
+ output_attentions=output_attentions,
1668
+ output_hidden_states=output_hidden_states,
1669
+ return_dict=return_dict,
1670
+ )
1671
+
1672
+ image_embeds = vision_outputs[1]
1673
+ text_embeds = text_outputs[1]
1674
+
1675
+ # normalized features
1676
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1677
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1678
+
1679
+ # cosine similarity as logits
1680
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * self.logit_scale.exp() + self.logit_bias
1681
+ logits_per_image = logits_per_text.t()
1682
+
1683
+ loss = None
1684
+ if return_loss:
1685
+ raise NotImplementedError("SigLIP loss to be implemented")
1686
+
1687
+ if not return_dict:
1688
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1689
+ return ((loss,) + output) if loss is not None else output
1690
+
1691
+ return SiglipOutput(
1692
+ loss=loss,
1693
+ logits_per_image=logits_per_image,
1694
+ logits_per_text=logits_per_text,
1695
+ text_embeds=text_embeds,
1696
+ image_embeds=image_embeds,
1697
+ text_model_output=text_outputs,
1698
+ vision_model_output=vision_outputs,
1699
+ )
1700
+
1701
+
1702
+ def get_siglip_vision_model(_flash_attn_2_enabled=True, **kwargs):
1703
+ siglip_vision_config = {
1704
+ "hidden_size": 1152,
1705
+ "image_size": 448,
1706
+ "intermediate_size": 4304,
1707
+ "model_type": "siglip_vision_model",
1708
+ "num_attention_heads": 16,
1709
+ "num_hidden_layers": 27,
1710
+ "patch_size": 14,
1711
+ }
1712
+
1713
+ model_config = SiglipVisionConfig(**siglip_vision_config, _flash_attn_2_enabled=_flash_attn_2_enabled, **kwargs)
1714
+
1715
+ vision_model = SiglipVisionModel(model_config).vision_model
1716
+
1717
+ return vision_model
models/Phi-4-multimodal-instruct/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/Pixtral-12B-2409/.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tekken.json filter=lfs diff=lfs merge=lfs -text
models/Pixtral-12B-2409/README.md ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: vllm
3
+ language:
4
+ - en
5
+ - fr
6
+ - de
7
+ - es
8
+ - it
9
+ - pt
10
+ - ru
11
+ - zh
12
+ - ja
13
+ license: apache-2.0
14
+ base_model:
15
+ - mistralai/Pixtral-12B-Base-2409
16
+ inference: false
17
+ extra_gated_description: >-
18
+ If you want to learn more about how we process your personal data, please read
19
+ our <a href="https://mistral.ai/terms/">Privacy Policy</a>.
20
+ tags:
21
+ - mistral-common
22
+ ---
23
+
24
+ # Model Card for Pixtral-12B-2409
25
+
26
+ The Pixtral-12B-2409 is a Multimodal Model of 12B parameters plus a 400M parameter vision encoder.
27
+
28
+ For more details about this model please refer to our release [blog post](https://mistral.ai/news/pixtral-12b/).
29
+
30
+ Feel free to try it [here](https://chat.mistral.ai/chat)
31
+
32
+ ## Key features
33
+ - Natively multimodal, trained with interleaved image and text data
34
+ - 12B parameter Multimodal Decoder + 400M parameter Vision Encoder
35
+ - Supports variable image sizes
36
+ - Leading performance in its weight class on multimodal tasks
37
+ - Maintains state-of-the-art performance on text-only benchmarks
38
+ - Sequence length: 128k
39
+ - License: Apache 2.0
40
+
41
+ ## Benchmarks
42
+ The performance of Pixtral-12B-2409 compared to multimodal models.
43
+ All models were re-evaluated and benchmarked through the same evaluation pipeline.
44
+
45
+ ### Multimodal Benchmarks
46
+
47
+ | | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision |
48
+ |:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|
49
+ | **MMMU** *(CoT)* | <ins>**52.5**</ins> | 47.6 | 45.1 | 40.3 | 38.3 |
50
+ | **Mathvista** *(CoT)* | <ins>**58.0**</ins> | 54.4 | 36.1 | 36.4 | 39.3 |
51
+ | **ChartQA** *(CoT)* | <ins>**81.8**</ins> | 38.6 | 67.1 | 72.0 | 67.7 |
52
+ | **DocVQA** *(ANLS)* | 90.7 | <ins>**94.5**</ins> | 90.5 | 84.9 | 74.4 |
53
+ | **VQAv2** *(VQA Match)* | <ins>**78.6**</ins> | 75.9 | 78.3 | 42.4 | 56.1 |
54
+
55
+ ### Instruction Following
56
+
57
+ | | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision |
58
+ |:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|
59
+ | **MM MT-Bench** | <ins>**6.05**</ins> | 5.43 | 4.12 | 3.70 |4.46 |
60
+ | **Text MT-Bench** | <ins>**7.68**</ins> | 6.41 | 6.94 | 6.27 |6.31 |
61
+ | **MM IF-Eval** | <ins>**52.7**</ins> | 38.9 | 42.5 | 41.2 |31.4 |
62
+ | **Text IF-Eval** | <ins>**61.3**</ins> | 50.1 | 51.4 | 50.9 |47.4 |
63
+
64
+ ### Text Benchmarks
65
+
66
+ | | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision |
67
+ |:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|
68
+ | **MMLU** *(5-shot)* | <ins>**69.2**</ins> | 68.5 | 67.9 | 63.5 | 63.6 |
69
+ | **Math** *(Pass@1)* | <ins>**48.1**</ins> | 27.8 | 38.6 | 29.2 | 28.4 |
70
+ | **Human Eval** *(Pass@1)* | <ins>**72.0**</ins> | 64.6 | 65.9 | 48.8 | 49.4 |
71
+
72
+ ### Comparison with Closed Source and Larger Models
73
+ | | Pixtral 12B | Claude-3 Haiku | Gemini-1.5 Flash 8B *(0827)* | . |*LLaVA-OV 72B* | *GPT-4o* | *Claude-3.5 Sonnet* |
74
+ |:-------------------:|:-------------:|:----------------:|:----------------------:|:--------:|:----:|:-------------------:|:-------------------:|
75
+ | **MMMU** *(CoT)* | **52.5** | 50.4 | 50.7 | |*54.4* |<ins>*68.6*</ins> | *68.0* |
76
+ | **Mathvista** *(CoT)* | **58.0** | 44.8 | 56.9 | |*57.2* |<ins>*64.6*</ins> | *64.4* |
77
+ | **ChartQA** *(CoT)* | **81.8** | 69.6 | 78.0 | |*66.9* |*85.1* | <ins>*87.6*</ins> |
78
+ | **DocVQA** *(ANLS)* | **90.7**</ins> | 74.6 | 79.5 | |<ins>*91.6*</ins> |*88.9* | *90.3* |
79
+ | **VQAv2** *(VQA Match)* | **78.6** | 68.4 | 65.5 | |<ins>*83.8*</ins> |*77.8* | *70.7* |
80
+
81
+ ## Usage Examples
82
+
83
+ ### vLLM (recommended)
84
+
85
+ We recommend using Pixtral with the [vLLM library](https://github.com/vllm-project/vllm)
86
+ to implement production-ready inference pipelines with Pixtral.
87
+
88
+ **_Installation_**
89
+
90
+ Make sure you install `vLLM >= v0.6.2`:
91
+
92
+ ```
93
+ pip install --upgrade vllm
94
+ ```
95
+
96
+ Also make sure you have `mistral_common >= 1.4.4` installed:
97
+
98
+ ```
99
+ pip install --upgrade mistral_common
100
+ ```
101
+
102
+ You can also make use of a ready-to-go [docker image](https://hub.docker.com/layers/vllm/vllm-openai/latest/images/sha256-de9032a92ffea7b5c007dad80b38fd44aac11eddc31c435f8e52f3b7404bbf39?context=explore).
103
+
104
+ **_Simple Example_**
105
+
106
+ ```py
107
+ from vllm import LLM
108
+ from vllm.sampling_params import SamplingParams
109
+
110
+ model_name = "mistralai/Pixtral-12B-2409"
111
+
112
+ sampling_params = SamplingParams(max_tokens=8192)
113
+
114
+ llm = LLM(model=model_name, tokenizer_mode="mistral")
115
+
116
+ prompt = "Describe this image in one sentence."
117
+ image_url = "https://picsum.photos/id/237/200/300"
118
+
119
+ messages = [
120
+ {
121
+ "role": "user",
122
+ "content": [{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": image_url}}]
123
+ },
124
+ ]
125
+
126
+ outputs = llm.chat(messages, sampling_params=sampling_params)
127
+
128
+ print(outputs[0].outputs[0].text)
129
+ ```
130
+
131
+ **_Advanced Example_**
132
+
133
+ You can also pass multiple images per message and/or pass multi-turn conversations
134
+
135
+ ```py
136
+ from vllm import LLM
137
+ from vllm.sampling_params import SamplingParams
138
+
139
+ model_name = "mistralai/Pixtral-12B-2409"
140
+ max_img_per_msg = 5
141
+
142
+ sampling_params = SamplingParams(max_tokens=8192, temperature=0.7)
143
+
144
+ # Lower max_num_seqs or max_model_len on low-VRAM GPUs.
145
+ llm = LLM(model=model_name, tokenizer_mode="mistral", limit_mm_per_prompt={"image": max_img_per_msg}, max_model_len=32768)
146
+
147
+ prompt = "Describe the following image."
148
+
149
+ url_1 = "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"
150
+ url_2 = "https://picsum.photos/seed/picsum/200/300"
151
+ url_3 = "https://picsum.photos/id/32/512/512"
152
+
153
+ messages = [
154
+ {
155
+ "role": "user",
156
+ "content": [{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": url_1}}, {"type": "image_url", "image_url": {"url": url_2}}],
157
+ },
158
+ {
159
+ "role": "assistant",
160
+ "content": "The images shows nature.",
161
+ },
162
+ {
163
+ "role": "user",
164
+ "content": "More details please and answer only in French!."
165
+ },
166
+ {
167
+ "role": "user",
168
+ "content": [{"type": "image_url", "image_url": {"url": url_3}}],
169
+ }
170
+ ]
171
+
172
+ outputs = llm.chat(messages=messages, sampling_params=sampling_params)
173
+ print(outputs[0].outputs[0].text)
174
+ ```
175
+
176
+ You can find more examples and tests directly in vLLM.
177
+ - [Examples](https://github.com/vllm-project/vllm/blob/main/examples/offline_inference_pixtral.py)
178
+ - [Tests](https://github.com/vllm-project/vllm/blob/main/tests/models/test_pixtral.py)
179
+
180
+ **_Server_**
181
+
182
+ You can also use pixtral in a server/client setting.
183
+
184
+ 1. Spin up a server:
185
+
186
+ ```
187
+ vllm serve mistralai/Pixtral-12B-2409 --tokenizer_mode mistral --limit_mm_per_prompt 'image=4'
188
+ ```
189
+
190
+ 2. And ping the client:
191
+
192
+ ```
193
+ curl --location 'http://<your-node-url>:8000/v1/chat/completions' \
194
+ --header 'Content-Type: application/json' \
195
+ --header 'Authorization: Bearer token' \
196
+ --data '{
197
+ "model": "mistralai/Pixtral-12B-2409",
198
+ "messages": [
199
+ {
200
+ "role": "user",
201
+ "content": [
202
+ {"type" : "text", "text": "Describe this image in detail please."},
203
+ {"type": "image_url", "image_url": {"url": "https://s3.amazonaws.com/cms.ipressroom.com/338/files/201808/5b894ee1a138352221103195_A680%7Ejogging-edit/A680%7Ejogging-edit_hero.jpg"}},
204
+ {"type" : "text", "text": "and this one as well. Answer in French."},
205
+ {"type": "image_url", "image_url": {"url": "https://www.wolframcloud.com/obj/resourcesystem/images/a0e/a0ee3983-46c6-4c92-b85d-059044639928/6af8cfb971db031b.png"}}
206
+ ]
207
+ }
208
+ ]
209
+ }'
210
+ ```
211
+
212
+ ### Mistral-inference
213
+
214
+ We recommend using [mistral-inference](https://github.com/mistralai/mistral-inference) to quickly try out / "vibe-check" Pixtral.
215
+
216
+
217
+ **_Install_**
218
+
219
+ Make sure to have `mistral_inference >= 1.4.1` installed.
220
+
221
+ ```
222
+ pip install mistral_inference --upgrade
223
+ ```
224
+
225
+ **_Download_**
226
+
227
+ ```py
228
+ from huggingface_hub import snapshot_download
229
+ from pathlib import Path
230
+
231
+ mistral_models_path = Path.home().joinpath('mistral_models', 'Pixtral')
232
+ mistral_models_path.mkdir(parents=True, exist_ok=True)
233
+
234
+ snapshot_download(repo_id="mistralai/Pixtral-12B-2409", allow_patterns=["params.json", "consolidated.safetensors", "tekken.json"], local_dir=mistral_models_path)
235
+ ```
236
+
237
+ **_Chat_**
238
+
239
+ After installing `mistral_inference`, a `mistral-chat` CLI command should be available in your environment.
240
+ You can pass text and images or image urls to the model in *instruction-following* mode as follows:
241
+
242
+ ```
243
+ mistral-chat $HOME/mistral_models/Pixtral --instruct --max_tokens 256 --temperature 0.35
244
+ ```
245
+
246
+ *E.g.* Try out something like:
247
+
248
+ ```
249
+ Text prompt: What can you see on the following picture?
250
+ [You can input zero, one or more images now.]
251
+ Image path or url [Leave empty and press enter to finish image input]: https://picsum.photos/id/237/200/300
252
+ Image path or url [Leave empty and press enter to finish image input]:
253
+ I see a black dog lying on a wooden surface. The dog appears to be looking up, and its eyes are clearly visible.
254
+ ```
255
+
256
+ **_Python_**
257
+
258
+ You can also run the model in a Python shell as follows.
259
+
260
+ ```py
261
+ from mistral_inference.transformer import Transformer
262
+ from mistral_inference.generate import generate
263
+
264
+ from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
265
+ from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageURLChunk
266
+ from mistral_common.protocol.instruct.request import ChatCompletionRequest
267
+
268
+ tokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json")
269
+ model = Transformer.from_folder(mistral_models_path)
270
+
271
+ url = "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"
272
+ prompt = "Describe the image."
273
+
274
+ completion_request = ChatCompletionRequest(messages=[UserMessage(content=[ImageURLChunk(image_url=url), TextChunk(text=prompt)])])
275
+
276
+ encoded = tokenizer.encode_chat_completion(completion_request)
277
+
278
+ images = encoded.images
279
+ tokens = encoded.tokens
280
+
281
+ out_tokens, _ = generate([tokens], model, images=[images], max_tokens=256, temperature=0.35, eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id)
282
+ result = tokenizer.decode(out_tokens[0])
283
+
284
+ print(result)
285
+ ```
286
+
287
+ ## Limitations
288
+
289
+ The Pixtral model does not have any moderation mechanisms. We're looking forward to engaging with the community on ways to
290
+ make the model finely respect guardrails, allowing for deployment in environments requiring moderated outputs.
291
+
292
+ ## The Mistral AI Team
293
+
294
+ Albert Jiang, Alexandre Sablayrolles, Alexis Tacnet, Alok Kothari, Antoine Roux, Arthur Mensch, Audrey Herblin-Stoop, Augustin Garreau, Austin Birky, Bam4d, Baptiste Bout, Baudouin de Monicault, Blanche Savary, Carole Rambaud, Caroline Feldman, Devendra Singh Chaplot, Diego de las Casas, Diogo Costa, Eleonore Arcelin, Emma Bou Hanna, Etienne Metzger, Gaspard Blanchet, Gianna Lengyel, Guillaume Bour, Guillaume Lample, Harizo Rajaona, Henri Roussez, Hichem Sattouf, Ian Mack, Jean-Malo Delignon, Jessica Chudnovsky, Justus Murke, Kartik Khandelwal, Lawrence Stewart, Louis Martin, Louis Ternon, Lucile Saulnier, Lélio Renard Lavaud, Margaret Jennings, Marie Pellat, Marie Torelli, Marie-Anne Lachaux, Marjorie Janiewicz, Mickaël Seznec, Nicolas Schuhl, Niklas Muhs, Olivier de Garrigues, Patrick von Platen, Paul Jacob, Pauline Buche, Pavan Kumar Reddy, Perry Savas, Pierre Stock, Romain Sauvestre, Sagar Vaze, Sandeep Subramanian, Saurabh Garg, Sophia Yang, Szymon Antoniak, Teven Le Scao, Thibault Schueller, Thibaut Lavril, Thomas Wang, Théophile Gervet, Timothée Lacroix, Valera Nemychnikova, Wendy Shang, William El Sayed, William Marshall
models/Pixtral-12B-2409/params.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dim": 5120,
3
+ "n_layers": 40,
4
+ "head_dim": 128,
5
+ "hidden_dim": 14336,
6
+ "n_heads": 32,
7
+ "n_kv_heads": 8,
8
+ "rope_theta": 1000000000.0,
9
+ "norm_eps": 1e-05,
10
+ "vocab_size": 131072,
11
+ "max_position_embeddings": 131072,
12
+ "vision_encoder": {
13
+ "hidden_size": 1024,
14
+ "num_channels": 3,
15
+ "image_size": 1024,
16
+ "patch_size": 16,
17
+ "rope_theta": 10000.0,
18
+ "intermediate_size": 4096,
19
+ "num_hidden_layers": 24,
20
+ "num_attention_heads": 16,
21
+ "image_token_id": 10,
22
+ "image_break_token_id": 12,
23
+ "image_end_token_id": 13
24
+ }
25
+ }
models/Qwen2-VL-7B-Instruct/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/Qwen2-VL-7B-Instruct/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
models/Qwen2-VL-7B-Instruct/README.md ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ pipeline_tag: image-text-to-text
6
+ tags:
7
+ - multimodal
8
+ library_name: transformers
9
+ base_model:
10
+ - Qwen/Qwen2-VL-7B
11
+ new_version: Qwen/Qwen2.5-VL-7B-Instruct
12
+ ---
13
+
14
+ # Qwen2-VL-7B-Instruct
15
+ <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
16
+ <img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
17
+ </a>
18
+
19
+ ## Introduction
20
+
21
+ We're excited to unveil **Qwen2-VL**, the latest iteration of our Qwen-VL model, representing nearly a year of innovation.
22
+
23
+ ### What’s New in Qwen2-VL?
24
+
25
+ #### Key Enhancements:
26
+
27
+
28
+ * **SoTA understanding of images of various resolution & ratio**: Qwen2-VL achieves state-of-the-art performance on visual understanding benchmarks, including MathVista, DocVQA, RealWorldQA, MTVQA, etc.
29
+
30
+ * **Understanding videos of 20min+**: Qwen2-VL can understand videos over 20 minutes for high-quality video-based question answering, dialog, content creation, etc.
31
+
32
+ * **Agent that can operate your mobiles, robots, etc.**: with the abilities of complex reasoning and decision making, Qwen2-VL can be integrated with devices like mobile phones, robots, etc., for automatic operation based on visual environment and text instructions.
33
+
34
+ * **Multilingual Support**: to serve global users, besides English and Chinese, Qwen2-VL now supports the understanding of texts in different languages inside images, including most European languages, Japanese, Korean, Arabic, Vietnamese, etc.
35
+
36
+
37
+ #### Model Architecture Updates:
38
+
39
+ * **Naive Dynamic Resolution**: Unlike before, Qwen2-VL can handle arbitrary image resolutions, mapping them into a dynamic number of visual tokens, offering a more human-like visual processing experience.
40
+
41
+ <p align="center">
42
+ <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/qwen2_vl.jpg" width="80%"/>
43
+ <p>
44
+
45
+ * **Multimodal Rotary Position Embedding (M-ROPE)**: Decomposes positional embedding into parts to capture 1D textual, 2D visual, and 3D video positional information, enhancing its multimodal processing capabilities.
46
+
47
+ <p align="center">
48
+ <img src="http://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/mrope.png" width="80%"/>
49
+ <p>
50
+
51
+ We have three models with 2, 7 and 72 billion parameters. This repo contains the instruction-tuned 7B Qwen2-VL model. For more information, visit our [Blog](https://qwenlm.github.io/blog/qwen2-vl/) and [GitHub](https://github.com/QwenLM/Qwen2-VL).
52
+
53
+
54
+
55
+ ## Evaluation
56
+
57
+ ### Image Benchmarks
58
+
59
+ | Benchmark | InternVL2-8B | MiniCPM-V 2.6 | GPT-4o-mini | **Qwen2-VL-7B** |
60
+ | :--- | :---: | :---: | :---: | :---: |
61
+ | MMMU<sub>val</sub> | 51.8 | 49.8 | **60**| 54.1 |
62
+ | DocVQA<sub>test</sub> | 91.6 | 90.8 | - | **94.5** |
63
+ | InfoVQA<sub>test</sub> | 74.8 | - | - |**76.5** |
64
+ | ChartQA<sub>test</sub> | **83.3** | - |- | 83.0 |
65
+ | TextVQA<sub>val</sub> | 77.4 | 80.1 | -| **84.3** |
66
+ | OCRBench | 794 | **852** | 785 | 845 |
67
+ | MTVQA | - | - | -| **26.3** |
68
+ | VCR<sub>en easy</sub> | - | 73.88 | 83.60 | **89.70** |
69
+ | VCR<sub>zh easy</sub> | - | 10.18| 1.10 | **59.94** |
70
+ | RealWorldQA | 64.4 | - | - | **70.1** |
71
+ | MME<sub>sum</sub> | 2210.3 | **2348.4** | 2003.4| 2326.8 |
72
+ | MMBench-EN<sub>test</sub> | 81.7 | - | - | **83.0** |
73
+ | MMBench-CN<sub>test</sub> | **81.2** | - | - | 80.5 |
74
+ | MMBench-V1.1<sub>test</sub> | 79.4 | 78.0 | 76.0| **80.7** |
75
+ | MMT-Bench<sub>test</sub> | - | - | - |**63.7** |
76
+ | MMStar | **61.5** | 57.5 | 54.8 | 60.7 |
77
+ | MMVet<sub>GPT-4-Turbo</sub> | 54.2 | 60.0 | **66.9** | 62.0 |
78
+ | HallBench<sub>avg</sub> | 45.2 | 48.1 | 46.1| **50.6** |
79
+ | MathVista<sub>testmini</sub> | 58.3 | **60.6** | 52.4 | 58.2 |
80
+ | MathVision | - | - | - | **16.3** |
81
+
82
+ ### Video Benchmarks
83
+
84
+ | Benchmark | Internvl2-8B | LLaVA-OneVision-7B | MiniCPM-V 2.6 | **Qwen2-VL-7B** |
85
+ | :--- | :---: | :---: | :---: | :---: |
86
+ | MVBench | 66.4 | 56.7 | - | **67.0** |
87
+ | PerceptionTest<sub>test</sub> | - | 57.1 | - | **62.3** |
88
+ | EgoSchema<sub>test</sub> | - | 60.1 | - | **66.7** |
89
+ | Video-MME<sub>wo/w subs</sub> | 54.0/56.9 | 58.2/- | 60.9/63.6 | **63.3**/**69.0** |
90
+
91
+
92
+
93
+
94
+ ## Requirements
95
+ The code of Qwen2-VL has been in the latest Hugging face transformers and we advise you to build from source with command `pip install git+https://github.com/huggingface/transformers`, or you might encounter the following error:
96
+ ```
97
+ KeyError: 'qwen2_vl'
98
+ ```
99
+
100
+ ## Quickstart
101
+ We offer a toolkit to help you handle various types of visual input more conveniently. This includes base64, URLs, and interleaved images and videos. You can install it using the following command:
102
+
103
+ ```bash
104
+ pip install qwen-vl-utils
105
+ ```
106
+
107
+ Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
108
+
109
+ ```python
110
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
111
+ from qwen_vl_utils import process_vision_info
112
+
113
+ # default: Load the model on the available device(s)
114
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
115
+ "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
116
+ )
117
+
118
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
119
+ # model = Qwen2VLForConditionalGeneration.from_pretrained(
120
+ # "Qwen/Qwen2-VL-7B-Instruct",
121
+ # torch_dtype=torch.bfloat16,
122
+ # attn_implementation="flash_attention_2",
123
+ # device_map="auto",
124
+ # )
125
+
126
+ # default processer
127
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
128
+
129
+ # The default range for the number of visual tokens per image in the model is 4-16384. You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-1280, to balance speed and memory usage.
130
+ # min_pixels = 256*28*28
131
+ # max_pixels = 1280*28*28
132
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
133
+
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [
138
+ {
139
+ "type": "image",
140
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
141
+ },
142
+ {"type": "text", "text": "Describe this image."},
143
+ ],
144
+ }
145
+ ]
146
+
147
+ # Preparation for inference
148
+ text = processor.apply_chat_template(
149
+ messages, tokenize=False, add_generation_prompt=True
150
+ )
151
+ image_inputs, video_inputs = process_vision_info(messages)
152
+ inputs = processor(
153
+ text=[text],
154
+ images=image_inputs,
155
+ videos=video_inputs,
156
+ padding=True,
157
+ return_tensors="pt",
158
+ )
159
+ inputs = inputs.to("cuda")
160
+
161
+ # Inference: Generation of the output
162
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
163
+ generated_ids_trimmed = [
164
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
165
+ ]
166
+ output_text = processor.batch_decode(
167
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
168
+ )
169
+ print(output_text)
170
+ ```
171
+ <details>
172
+ <summary>Without qwen_vl_utils</summary>
173
+
174
+ ```python
175
+ from PIL import Image
176
+ import requests
177
+ import torch
178
+ from torchvision import io
179
+ from typing import Dict
180
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
181
+
182
+ # Load the model in half-precision on the available device(s)
183
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
184
+ "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
185
+ )
186
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
187
+
188
+ # Image
189
+ url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
190
+ image = Image.open(requests.get(url, stream=True).raw)
191
+
192
+ conversation = [
193
+ {
194
+ "role": "user",
195
+ "content": [
196
+ {
197
+ "type": "image",
198
+ },
199
+ {"type": "text", "text": "Describe this image."},
200
+ ],
201
+ }
202
+ ]
203
+
204
+
205
+ # Preprocess the inputs
206
+ text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
207
+ # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>\n<|im_start|>assistant\n'
208
+
209
+ inputs = processor(
210
+ text=[text_prompt], images=[image], padding=True, return_tensors="pt"
211
+ )
212
+ inputs = inputs.to("cuda")
213
+
214
+ # Inference: Generation of the output
215
+ output_ids = model.generate(**inputs, max_new_tokens=128)
216
+ generated_ids = [
217
+ output_ids[len(input_ids) :]
218
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
219
+ ]
220
+ output_text = processor.batch_decode(
221
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
222
+ )
223
+ print(output_text)
224
+ ```
225
+ </details>
226
+ <details>
227
+ <summary>Multi image inference</summary>
228
+
229
+ ```python
230
+ # Messages containing multiple images and a text query
231
+ messages = [
232
+ {
233
+ "role": "user",
234
+ "content": [
235
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
236
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
237
+ {"type": "text", "text": "Identify the similarities between these images."},
238
+ ],
239
+ }
240
+ ]
241
+
242
+ # Preparation for inference
243
+ text = processor.apply_chat_template(
244
+ messages, tokenize=False, add_generation_prompt=True
245
+ )
246
+ image_inputs, video_inputs = process_vision_info(messages)
247
+ inputs = processor(
248
+ text=[text],
249
+ images=image_inputs,
250
+ videos=video_inputs,
251
+ padding=True,
252
+ return_tensors="pt",
253
+ )
254
+ inputs = inputs.to("cuda")
255
+
256
+ # Inference
257
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
258
+ generated_ids_trimmed = [
259
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
260
+ ]
261
+ output_text = processor.batch_decode(
262
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
263
+ )
264
+ print(output_text)
265
+ ```
266
+ </details>
267
+
268
+ <details>
269
+ <summary>Video inference</summary>
270
+
271
+ ```python
272
+ # Messages containing a images list as a video and a text query
273
+ messages = [
274
+ {
275
+ "role": "user",
276
+ "content": [
277
+ {
278
+ "type": "video",
279
+ "video": [
280
+ "file:///path/to/frame1.jpg",
281
+ "file:///path/to/frame2.jpg",
282
+ "file:///path/to/frame3.jpg",
283
+ "file:///path/to/frame4.jpg",
284
+ ],
285
+ "fps": 1.0,
286
+ },
287
+ {"type": "text", "text": "Describe this video."},
288
+ ],
289
+ }
290
+ ]
291
+ # Messages containing a video and a text query
292
+ messages = [
293
+ {
294
+ "role": "user",
295
+ "content": [
296
+ {
297
+ "type": "video",
298
+ "video": "file:///path/to/video1.mp4",
299
+ "max_pixels": 360 * 420,
300
+ "fps": 1.0,
301
+ },
302
+ {"type": "text", "text": "Describe this video."},
303
+ ],
304
+ }
305
+ ]
306
+
307
+ # Preparation for inference
308
+ text = processor.apply_chat_template(
309
+ messages, tokenize=False, add_generation_prompt=True
310
+ )
311
+ image_inputs, video_inputs = process_vision_info(messages)
312
+ inputs = processor(
313
+ text=[text],
314
+ images=image_inputs,
315
+ videos=video_inputs,
316
+ padding=True,
317
+ return_tensors="pt",
318
+ )
319
+ inputs = inputs.to("cuda")
320
+
321
+ # Inference
322
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
323
+ generated_ids_trimmed = [
324
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
325
+ ]
326
+ output_text = processor.batch_decode(
327
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
328
+ )
329
+ print(output_text)
330
+ ```
331
+ </details>
332
+
333
+ <details>
334
+ <summary>Batch inference</summary>
335
+
336
+ ```python
337
+ # Sample messages for batch inference
338
+ messages1 = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
343
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
344
+ {"type": "text", "text": "What are the common elements in these pictures?"},
345
+ ],
346
+ }
347
+ ]
348
+ messages2 = [
349
+ {"role": "system", "content": "You are a helpful assistant."},
350
+ {"role": "user", "content": "Who are you?"},
351
+ ]
352
+ # Combine messages for batch processing
353
+ messages = [messages1, messages1]
354
+
355
+ # Preparation for batch inference
356
+ texts = [
357
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
358
+ for msg in messages
359
+ ]
360
+ image_inputs, video_inputs = process_vision_info(messages)
361
+ inputs = processor(
362
+ text=texts,
363
+ images=image_inputs,
364
+ videos=video_inputs,
365
+ padding=True,
366
+ return_tensors="pt",
367
+ )
368
+ inputs = inputs.to("cuda")
369
+
370
+ # Batch Inference
371
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
372
+ generated_ids_trimmed = [
373
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
374
+ ]
375
+ output_texts = processor.batch_decode(
376
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
377
+ )
378
+ print(output_texts)
379
+ ```
380
+ </details>
381
+
382
+ ### More Usage Tips
383
+
384
+ For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
385
+
386
+ ```python
387
+ # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
388
+ ## Local file path
389
+ messages = [
390
+ {
391
+ "role": "user",
392
+ "content": [
393
+ {"type": "image", "image": "file:///path/to/your/image.jpg"},
394
+ {"type": "text", "text": "Describe this image."},
395
+ ],
396
+ }
397
+ ]
398
+ ## Image URL
399
+ messages = [
400
+ {
401
+ "role": "user",
402
+ "content": [
403
+ {"type": "image", "image": "http://path/to/your/image.jpg"},
404
+ {"type": "text", "text": "Describe this image."},
405
+ ],
406
+ }
407
+ ]
408
+ ## Base64 encoded image
409
+ messages = [
410
+ {
411
+ "role": "user",
412
+ "content": [
413
+ {"type": "image", "image": "data:image;base64,/9j/..."},
414
+ {"type": "text", "text": "Describe this image."},
415
+ ],
416
+ }
417
+ ]
418
+ ```
419
+ #### Image Resolution for performance boost
420
+
421
+ The model supports a wide range of resolution inputs. By default, it uses the native resolution for input, but higher resolutions can enhance performance at the cost of more computation. Users can set the minimum and maximum number of pixels to achieve an optimal configuration for their needs, such as a token count range of 256-1280, to balance speed and memory usage.
422
+
423
+ ```python
424
+ min_pixels = 256 * 28 * 28
425
+ max_pixels = 1280 * 28 * 28
426
+ processor = AutoProcessor.from_pretrained(
427
+ "Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
428
+ )
429
+ ```
430
+
431
+ Besides, We provide two methods for fine-grained control over the image size input to the model:
432
+
433
+ 1. Define min_pixels and max_pixels: Images will be resized to maintain their aspect ratio within the range of min_pixels and max_pixels.
434
+
435
+ 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
436
+
437
+ ```python
438
+ # min_pixels and max_pixels
439
+ messages = [
440
+ {
441
+ "role": "user",
442
+ "content": [
443
+ {
444
+ "type": "image",
445
+ "image": "file:///path/to/your/image.jpg",
446
+ "resized_height": 280,
447
+ "resized_width": 420,
448
+ },
449
+ {"type": "text", "text": "Describe this image."},
450
+ ],
451
+ }
452
+ ]
453
+ # resized_height and resized_width
454
+ messages = [
455
+ {
456
+ "role": "user",
457
+ "content": [
458
+ {
459
+ "type": "image",
460
+ "image": "file:///path/to/your/image.jpg",
461
+ "min_pixels": 50176,
462
+ "max_pixels": 50176,
463
+ },
464
+ {"type": "text", "text": "Describe this image."},
465
+ ],
466
+ }
467
+ ]
468
+ ```
469
+
470
+ ## Limitations
471
+
472
+ While Qwen2-VL are applicable to a wide range of visual tasks, it is equally important to understand its limitations. Here are some known restrictions:
473
+
474
+ 1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.
475
+ 2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.
476
+ 3. Constraints in Individuals and Intellectual Property (IP): The model's capacity to recognize specific individuals or IPs is limited, potentially failing to comprehensively cover all well-known personalities or brands.
477
+ 4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.
478
+ 5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.
479
+ 6. Weak Spatial Reasoning Skills: Especially in 3D spaces, the model's inference of object positional relationships is inadequate, making it difficult to precisely judge the relative positions of objects.
480
+
481
+ These limitations serve as ongoing directions for model optimization and improvement, and we are committed to continually enhancing the model's performance and scope of application.
482
+
483
+
484
+ ## Citation
485
+
486
+ If you find our work helpful, feel free to give us a cite.
487
+
488
+ ```
489
+ @article{Qwen2VL,
490
+ title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
491
+ author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang},
492
+ journal={arXiv preprint arXiv:2409.12191},
493
+ year={2024}
494
+ }
495
+
496
+ @article{Qwen-VL,
497
+ title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
498
+ author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren},
499
+ journal={arXiv preprint arXiv:2308.12966},
500
+ year={2023}
501
+ }
502
+ ```
models/Qwen2-VL-7B-Instruct/chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
3
+ }
models/Qwen2-VL-7B-Instruct/config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2VLForConditionalGeneration"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "eos_token_id": 151645,
8
+ "vision_start_token_id": 151652,
9
+ "vision_end_token_id": 151653,
10
+ "vision_token_id": 151654,
11
+ "image_token_id": 151655,
12
+ "video_token_id": 151656,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 3584,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 18944,
17
+ "max_position_embeddings": 32768,
18
+ "max_window_layers": 28,
19
+ "model_type": "qwen2_vl",
20
+ "num_attention_heads": 28,
21
+ "num_hidden_layers": 28,
22
+ "num_key_value_heads": 4,
23
+ "rms_norm_eps": 1e-06,
24
+ "rope_theta": 1000000.0,
25
+ "sliding_window": 32768,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "bfloat16",
28
+ "transformers_version": "4.41.2",
29
+ "use_cache": true,
30
+ "use_sliding_window": false,
31
+ "vision_config": {
32
+ "depth": 32,
33
+ "embed_dim": 1280,
34
+ "mlp_ratio": 4,
35
+ "num_heads": 16,
36
+ "in_chans": 3,
37
+ "hidden_size": 3584,
38
+ "patch_size": 14,
39
+ "spatial_merge_size": 2,
40
+ "spatial_patch_size": 14,
41
+ "temporal_patch_size": 2
42
+ },
43
+ "rope_scaling": {
44
+ "type": "mrope",
45
+ "mrope_section": [
46
+ 16,
47
+ 24,
48
+ 24
49
+ ]
50
+ },
51
+ "vocab_size": 152064
52
+ }
models/Qwen2-VL-7B-Instruct/generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "pad_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "repetition_penalty": 1.0,
10
+ "temperature": 0.01,
11
+ "top_p": 0.001,
12
+ "top_k": 1,
13
+ "transformers_version": "4.37.0"
14
+ }
models/Qwen2-VL-7B-Instruct/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/Qwen2-VL-7B-Instruct/model.safetensors.index.json ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16582751232
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00005-of-00005.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00005.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
16
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
18
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
25
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
28
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
30
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
31
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00005.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
37
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
40
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
41
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
42
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
43
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
44
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00005.safetensors",
45
+ "model.layers.11.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
49
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
52
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
53
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
54
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
55
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
56
+ "model.layers.12.input_layernorm.weight": "model-00003-of-00005.safetensors",
57
+ "model.layers.12.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
61
+ "model.layers.12.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
64
+ "model.layers.12.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
65
+ "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
66
+ "model.layers.12.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
67
+ "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
68
+ "model.layers.13.input_layernorm.weight": "model-00003-of-00005.safetensors",
69
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
73
+ "model.layers.13.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
76
+ "model.layers.13.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
77
+ "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
78
+ "model.layers.13.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
79
+ "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
80
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00005.safetensors",
81
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
85
+ "model.layers.14.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
88
+ "model.layers.14.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
89
+ "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
90
+ "model.layers.14.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
91
+ "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
92
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00005.safetensors",
93
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
97
+ "model.layers.15.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
100
+ "model.layers.15.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
101
+ "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
102
+ "model.layers.15.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
103
+ "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
104
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00005.safetensors",
105
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
109
+ "model.layers.16.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
112
+ "model.layers.16.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
113
+ "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
114
+ "model.layers.16.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00005.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
121
+ "model.layers.17.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
124
+ "model.layers.17.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
126
+ "model.layers.17.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
127
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
128
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00005.safetensors",
129
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
133
+ "model.layers.18.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
136
+ "model.layers.18.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
137
+ "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
138
+ "model.layers.18.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
139
+ "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
140
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00005.safetensors",
141
+ "model.layers.19.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
145
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
148
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
149
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
150
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
151
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
152
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors",
153
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
157
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
160
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
161
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
162
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
163
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
164
+ "model.layers.20.input_layernorm.weight": "model-00004-of-00005.safetensors",
165
+ "model.layers.20.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
169
+ "model.layers.20.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
172
+ "model.layers.20.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
173
+ "model.layers.20.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
174
+ "model.layers.20.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
175
+ "model.layers.20.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
176
+ "model.layers.21.input_layernorm.weight": "model-00004-of-00005.safetensors",
177
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
181
+ "model.layers.21.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
184
+ "model.layers.21.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
185
+ "model.layers.21.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
186
+ "model.layers.21.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
187
+ "model.layers.21.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
188
+ "model.layers.22.input_layernorm.weight": "model-00004-of-00005.safetensors",
189
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
193
+ "model.layers.22.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
196
+ "model.layers.22.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
197
+ "model.layers.22.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
198
+ "model.layers.22.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
199
+ "model.layers.22.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
200
+ "model.layers.23.input_layernorm.weight": "model-00004-of-00005.safetensors",
201
+ "model.layers.23.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
205
+ "model.layers.23.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
208
+ "model.layers.23.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
209
+ "model.layers.23.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
210
+ "model.layers.23.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
211
+ "model.layers.23.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
212
+ "model.layers.24.input_layernorm.weight": "model-00004-of-00005.safetensors",
213
+ "model.layers.24.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
214
+ "model.layers.24.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
215
+ "model.layers.24.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
216
+ "model.layers.24.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
217
+ "model.layers.24.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
220
+ "model.layers.24.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
221
+ "model.layers.24.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
222
+ "model.layers.24.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
223
+ "model.layers.24.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
224
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00005.safetensors",
225
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
226
+ "model.layers.25.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
227
+ "model.layers.25.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
228
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
229
+ "model.layers.25.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
232
+ "model.layers.25.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
233
+ "model.layers.25.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
234
+ "model.layers.25.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
235
+ "model.layers.25.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
236
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00005.safetensors",
237
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
238
+ "model.layers.26.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
239
+ "model.layers.26.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
240
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
241
+ "model.layers.26.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
242
+ "model.layers.26.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
244
+ "model.layers.26.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
245
+ "model.layers.26.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
246
+ "model.layers.26.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
247
+ "model.layers.26.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
248
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00005.safetensors",
249
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
250
+ "model.layers.27.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
251
+ "model.layers.27.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
252
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
253
+ "model.layers.27.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
254
+ "model.layers.27.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
255
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
256
+ "model.layers.27.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
257
+ "model.layers.27.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
258
+ "model.layers.27.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
259
+ "model.layers.27.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
260
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00005.safetensors",
261
+ "model.layers.3.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
262
+ "model.layers.3.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
263
+ "model.layers.3.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
264
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
265
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
266
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
267
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
268
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
269
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
270
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
271
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
272
+ "model.layers.4.input_layernorm.weight": "model-00002-of-00005.safetensors",
273
+ "model.layers.4.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
274
+ "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
275
+ "model.layers.4.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
276
+ "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
277
+ "model.layers.4.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
278
+ "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
279
+ "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
280
+ "model.layers.4.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
281
+ "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
282
+ "model.layers.4.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
283
+ "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
284
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00005.safetensors",
285
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
286
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
287
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
288
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
289
+ "model.layers.5.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
290
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
291
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
292
+ "model.layers.5.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
293
+ "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
294
+ "model.layers.5.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
295
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
296
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00005.safetensors",
297
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
298
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
299
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
300
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
301
+ "model.layers.6.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
302
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
303
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
304
+ "model.layers.6.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
305
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
306
+ "model.layers.6.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
307
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
308
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00005.safetensors",
309
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
310
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
311
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
312
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
313
+ "model.layers.7.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
314
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
315
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
316
+ "model.layers.7.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
317
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
318
+ "model.layers.7.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
319
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
320
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00005.safetensors",
321
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
322
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
323
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
324
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
325
+ "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
326
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
327
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
328
+ "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
329
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
330
+ "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
331
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
332
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00005.safetensors",
333
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
334
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
335
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
336
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
337
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
338
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
339
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
340
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
341
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
342
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
343
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
344
+ "model.norm.weight": "model-00004-of-00005.safetensors",
345
+ "visual.blocks.0.attn.proj.bias": "model-00001-of-00005.safetensors",
346
+ "visual.blocks.0.attn.proj.weight": "model-00001-of-00005.safetensors",
347
+ "visual.blocks.0.attn.qkv.bias": "model-00001-of-00005.safetensors",
348
+ "visual.blocks.0.attn.qkv.weight": "model-00001-of-00005.safetensors",
349
+ "visual.blocks.0.mlp.fc1.bias": "model-00001-of-00005.safetensors",
350
+ "visual.blocks.0.mlp.fc1.weight": "model-00001-of-00005.safetensors",
351
+ "visual.blocks.0.mlp.fc2.bias": "model-00001-of-00005.safetensors",
352
+ "visual.blocks.0.mlp.fc2.weight": "model-00001-of-00005.safetensors",
353
+ "visual.blocks.0.norm1.bias": "model-00001-of-00005.safetensors",
354
+ "visual.blocks.0.norm1.weight": "model-00001-of-00005.safetensors",
355
+ "visual.blocks.0.norm2.bias": "model-00001-of-00005.safetensors",
356
+ "visual.blocks.0.norm2.weight": "model-00001-of-00005.safetensors",
357
+ "visual.blocks.1.attn.proj.bias": "model-00001-of-00005.safetensors",
358
+ "visual.blocks.1.attn.proj.weight": "model-00001-of-00005.safetensors",
359
+ "visual.blocks.1.attn.qkv.bias": "model-00001-of-00005.safetensors",
360
+ "visual.blocks.1.attn.qkv.weight": "model-00001-of-00005.safetensors",
361
+ "visual.blocks.1.mlp.fc1.bias": "model-00001-of-00005.safetensors",
362
+ "visual.blocks.1.mlp.fc1.weight": "model-00001-of-00005.safetensors",
363
+ "visual.blocks.1.mlp.fc2.bias": "model-00001-of-00005.safetensors",
364
+ "visual.blocks.1.mlp.fc2.weight": "model-00001-of-00005.safetensors",
365
+ "visual.blocks.1.norm1.bias": "model-00001-of-00005.safetensors",
366
+ "visual.blocks.1.norm1.weight": "model-00001-of-00005.safetensors",
367
+ "visual.blocks.1.norm2.bias": "model-00001-of-00005.safetensors",
368
+ "visual.blocks.1.norm2.weight": "model-00001-of-00005.safetensors",
369
+ "visual.blocks.10.attn.proj.bias": "model-00001-of-00005.safetensors",
370
+ "visual.blocks.10.attn.proj.weight": "model-00001-of-00005.safetensors",
371
+ "visual.blocks.10.attn.qkv.bias": "model-00001-of-00005.safetensors",
372
+ "visual.blocks.10.attn.qkv.weight": "model-00001-of-00005.safetensors",
373
+ "visual.blocks.10.mlp.fc1.bias": "model-00001-of-00005.safetensors",
374
+ "visual.blocks.10.mlp.fc1.weight": "model-00001-of-00005.safetensors",
375
+ "visual.blocks.10.mlp.fc2.bias": "model-00001-of-00005.safetensors",
376
+ "visual.blocks.10.mlp.fc2.weight": "model-00001-of-00005.safetensors",
377
+ "visual.blocks.10.norm1.bias": "model-00001-of-00005.safetensors",
378
+ "visual.blocks.10.norm1.weight": "model-00001-of-00005.safetensors",
379
+ "visual.blocks.10.norm2.bias": "model-00001-of-00005.safetensors",
380
+ "visual.blocks.10.norm2.weight": "model-00001-of-00005.safetensors",
381
+ "visual.blocks.11.attn.proj.bias": "model-00001-of-00005.safetensors",
382
+ "visual.blocks.11.attn.proj.weight": "model-00001-of-00005.safetensors",
383
+ "visual.blocks.11.attn.qkv.bias": "model-00001-of-00005.safetensors",
384
+ "visual.blocks.11.attn.qkv.weight": "model-00001-of-00005.safetensors",
385
+ "visual.blocks.11.mlp.fc1.bias": "model-00001-of-00005.safetensors",
386
+ "visual.blocks.11.mlp.fc1.weight": "model-00001-of-00005.safetensors",
387
+ "visual.blocks.11.mlp.fc2.bias": "model-00001-of-00005.safetensors",
388
+ "visual.blocks.11.mlp.fc2.weight": "model-00001-of-00005.safetensors",
389
+ "visual.blocks.11.norm1.bias": "model-00001-of-00005.safetensors",
390
+ "visual.blocks.11.norm1.weight": "model-00001-of-00005.safetensors",
391
+ "visual.blocks.11.norm2.bias": "model-00001-of-00005.safetensors",
392
+ "visual.blocks.11.norm2.weight": "model-00001-of-00005.safetensors",
393
+ "visual.blocks.12.attn.proj.bias": "model-00001-of-00005.safetensors",
394
+ "visual.blocks.12.attn.proj.weight": "model-00001-of-00005.safetensors",
395
+ "visual.blocks.12.attn.qkv.bias": "model-00001-of-00005.safetensors",
396
+ "visual.blocks.12.attn.qkv.weight": "model-00001-of-00005.safetensors",
397
+ "visual.blocks.12.mlp.fc1.bias": "model-00001-of-00005.safetensors",
398
+ "visual.blocks.12.mlp.fc1.weight": "model-00001-of-00005.safetensors",
399
+ "visual.blocks.12.mlp.fc2.bias": "model-00001-of-00005.safetensors",
400
+ "visual.blocks.12.mlp.fc2.weight": "model-00001-of-00005.safetensors",
401
+ "visual.blocks.12.norm1.bias": "model-00001-of-00005.safetensors",
402
+ "visual.blocks.12.norm1.weight": "model-00001-of-00005.safetensors",
403
+ "visual.blocks.12.norm2.bias": "model-00001-of-00005.safetensors",
404
+ "visual.blocks.12.norm2.weight": "model-00001-of-00005.safetensors",
405
+ "visual.blocks.13.attn.proj.bias": "model-00001-of-00005.safetensors",
406
+ "visual.blocks.13.attn.proj.weight": "model-00001-of-00005.safetensors",
407
+ "visual.blocks.13.attn.qkv.bias": "model-00001-of-00005.safetensors",
408
+ "visual.blocks.13.attn.qkv.weight": "model-00001-of-00005.safetensors",
409
+ "visual.blocks.13.mlp.fc1.bias": "model-00001-of-00005.safetensors",
410
+ "visual.blocks.13.mlp.fc1.weight": "model-00001-of-00005.safetensors",
411
+ "visual.blocks.13.mlp.fc2.bias": "model-00001-of-00005.safetensors",
412
+ "visual.blocks.13.mlp.fc2.weight": "model-00001-of-00005.safetensors",
413
+ "visual.blocks.13.norm1.bias": "model-00001-of-00005.safetensors",
414
+ "visual.blocks.13.norm1.weight": "model-00001-of-00005.safetensors",
415
+ "visual.blocks.13.norm2.bias": "model-00001-of-00005.safetensors",
416
+ "visual.blocks.13.norm2.weight": "model-00001-of-00005.safetensors",
417
+ "visual.blocks.14.attn.proj.bias": "model-00001-of-00005.safetensors",
418
+ "visual.blocks.14.attn.proj.weight": "model-00001-of-00005.safetensors",
419
+ "visual.blocks.14.attn.qkv.bias": "model-00001-of-00005.safetensors",
420
+ "visual.blocks.14.attn.qkv.weight": "model-00001-of-00005.safetensors",
421
+ "visual.blocks.14.mlp.fc1.bias": "model-00001-of-00005.safetensors",
422
+ "visual.blocks.14.mlp.fc1.weight": "model-00001-of-00005.safetensors",
423
+ "visual.blocks.14.mlp.fc2.bias": "model-00001-of-00005.safetensors",
424
+ "visual.blocks.14.mlp.fc2.weight": "model-00001-of-00005.safetensors",
425
+ "visual.blocks.14.norm1.bias": "model-00001-of-00005.safetensors",
426
+ "visual.blocks.14.norm1.weight": "model-00001-of-00005.safetensors",
427
+ "visual.blocks.14.norm2.bias": "model-00001-of-00005.safetensors",
428
+ "visual.blocks.14.norm2.weight": "model-00001-of-00005.safetensors",
429
+ "visual.blocks.15.attn.proj.bias": "model-00001-of-00005.safetensors",
430
+ "visual.blocks.15.attn.proj.weight": "model-00001-of-00005.safetensors",
431
+ "visual.blocks.15.attn.qkv.bias": "model-00001-of-00005.safetensors",
432
+ "visual.blocks.15.attn.qkv.weight": "model-00001-of-00005.safetensors",
433
+ "visual.blocks.15.mlp.fc1.bias": "model-00001-of-00005.safetensors",
434
+ "visual.blocks.15.mlp.fc1.weight": "model-00001-of-00005.safetensors",
435
+ "visual.blocks.15.mlp.fc2.bias": "model-00001-of-00005.safetensors",
436
+ "visual.blocks.15.mlp.fc2.weight": "model-00001-of-00005.safetensors",
437
+ "visual.blocks.15.norm1.bias": "model-00001-of-00005.safetensors",
438
+ "visual.blocks.15.norm1.weight": "model-00001-of-00005.safetensors",
439
+ "visual.blocks.15.norm2.bias": "model-00001-of-00005.safetensors",
440
+ "visual.blocks.15.norm2.weight": "model-00001-of-00005.safetensors",
441
+ "visual.blocks.16.attn.proj.bias": "model-00001-of-00005.safetensors",
442
+ "visual.blocks.16.attn.proj.weight": "model-00001-of-00005.safetensors",
443
+ "visual.blocks.16.attn.qkv.bias": "model-00001-of-00005.safetensors",
444
+ "visual.blocks.16.attn.qkv.weight": "model-00001-of-00005.safetensors",
445
+ "visual.blocks.16.mlp.fc1.bias": "model-00001-of-00005.safetensors",
446
+ "visual.blocks.16.mlp.fc1.weight": "model-00001-of-00005.safetensors",
447
+ "visual.blocks.16.mlp.fc2.bias": "model-00001-of-00005.safetensors",
448
+ "visual.blocks.16.mlp.fc2.weight": "model-00001-of-00005.safetensors",
449
+ "visual.blocks.16.norm1.bias": "model-00001-of-00005.safetensors",
450
+ "visual.blocks.16.norm1.weight": "model-00001-of-00005.safetensors",
451
+ "visual.blocks.16.norm2.bias": "model-00001-of-00005.safetensors",
452
+ "visual.blocks.16.norm2.weight": "model-00001-of-00005.safetensors",
453
+ "visual.blocks.17.attn.proj.bias": "model-00001-of-00005.safetensors",
454
+ "visual.blocks.17.attn.proj.weight": "model-00001-of-00005.safetensors",
455
+ "visual.blocks.17.attn.qkv.bias": "model-00001-of-00005.safetensors",
456
+ "visual.blocks.17.attn.qkv.weight": "model-00001-of-00005.safetensors",
457
+ "visual.blocks.17.mlp.fc1.bias": "model-00001-of-00005.safetensors",
458
+ "visual.blocks.17.mlp.fc1.weight": "model-00001-of-00005.safetensors",
459
+ "visual.blocks.17.mlp.fc2.bias": "model-00001-of-00005.safetensors",
460
+ "visual.blocks.17.mlp.fc2.weight": "model-00001-of-00005.safetensors",
461
+ "visual.blocks.17.norm1.bias": "model-00001-of-00005.safetensors",
462
+ "visual.blocks.17.norm1.weight": "model-00001-of-00005.safetensors",
463
+ "visual.blocks.17.norm2.bias": "model-00001-of-00005.safetensors",
464
+ "visual.blocks.17.norm2.weight": "model-00001-of-00005.safetensors",
465
+ "visual.blocks.18.attn.proj.bias": "model-00001-of-00005.safetensors",
466
+ "visual.blocks.18.attn.proj.weight": "model-00001-of-00005.safetensors",
467
+ "visual.blocks.18.attn.qkv.bias": "model-00001-of-00005.safetensors",
468
+ "visual.blocks.18.attn.qkv.weight": "model-00001-of-00005.safetensors",
469
+ "visual.blocks.18.mlp.fc1.bias": "model-00001-of-00005.safetensors",
470
+ "visual.blocks.18.mlp.fc1.weight": "model-00001-of-00005.safetensors",
471
+ "visual.blocks.18.mlp.fc2.bias": "model-00001-of-00005.safetensors",
472
+ "visual.blocks.18.mlp.fc2.weight": "model-00001-of-00005.safetensors",
473
+ "visual.blocks.18.norm1.bias": "model-00001-of-00005.safetensors",
474
+ "visual.blocks.18.norm1.weight": "model-00001-of-00005.safetensors",
475
+ "visual.blocks.18.norm2.bias": "model-00001-of-00005.safetensors",
476
+ "visual.blocks.18.norm2.weight": "model-00001-of-00005.safetensors",
477
+ "visual.blocks.19.attn.proj.bias": "model-00001-of-00005.safetensors",
478
+ "visual.blocks.19.attn.proj.weight": "model-00001-of-00005.safetensors",
479
+ "visual.blocks.19.attn.qkv.bias": "model-00001-of-00005.safetensors",
480
+ "visual.blocks.19.attn.qkv.weight": "model-00001-of-00005.safetensors",
481
+ "visual.blocks.19.mlp.fc1.bias": "model-00001-of-00005.safetensors",
482
+ "visual.blocks.19.mlp.fc1.weight": "model-00001-of-00005.safetensors",
483
+ "visual.blocks.19.mlp.fc2.bias": "model-00001-of-00005.safetensors",
484
+ "visual.blocks.19.mlp.fc2.weight": "model-00001-of-00005.safetensors",
485
+ "visual.blocks.19.norm1.bias": "model-00001-of-00005.safetensors",
486
+ "visual.blocks.19.norm1.weight": "model-00001-of-00005.safetensors",
487
+ "visual.blocks.19.norm2.bias": "model-00001-of-00005.safetensors",
488
+ "visual.blocks.19.norm2.weight": "model-00001-of-00005.safetensors",
489
+ "visual.blocks.2.attn.proj.bias": "model-00001-of-00005.safetensors",
490
+ "visual.blocks.2.attn.proj.weight": "model-00001-of-00005.safetensors",
491
+ "visual.blocks.2.attn.qkv.bias": "model-00001-of-00005.safetensors",
492
+ "visual.blocks.2.attn.qkv.weight": "model-00001-of-00005.safetensors",
493
+ "visual.blocks.2.mlp.fc1.bias": "model-00001-of-00005.safetensors",
494
+ "visual.blocks.2.mlp.fc1.weight": "model-00001-of-00005.safetensors",
495
+ "visual.blocks.2.mlp.fc2.bias": "model-00001-of-00005.safetensors",
496
+ "visual.blocks.2.mlp.fc2.weight": "model-00001-of-00005.safetensors",
497
+ "visual.blocks.2.norm1.bias": "model-00001-of-00005.safetensors",
498
+ "visual.blocks.2.norm1.weight": "model-00001-of-00005.safetensors",
499
+ "visual.blocks.2.norm2.bias": "model-00001-of-00005.safetensors",
500
+ "visual.blocks.2.norm2.weight": "model-00001-of-00005.safetensors",
501
+ "visual.blocks.20.attn.proj.bias": "model-00001-of-00005.safetensors",
502
+ "visual.blocks.20.attn.proj.weight": "model-00001-of-00005.safetensors",
503
+ "visual.blocks.20.attn.qkv.bias": "model-00001-of-00005.safetensors",
504
+ "visual.blocks.20.attn.qkv.weight": "model-00001-of-00005.safetensors",
505
+ "visual.blocks.20.mlp.fc1.bias": "model-00001-of-00005.safetensors",
506
+ "visual.blocks.20.mlp.fc1.weight": "model-00001-of-00005.safetensors",
507
+ "visual.blocks.20.mlp.fc2.bias": "model-00001-of-00005.safetensors",
508
+ "visual.blocks.20.mlp.fc2.weight": "model-00001-of-00005.safetensors",
509
+ "visual.blocks.20.norm1.bias": "model-00001-of-00005.safetensors",
510
+ "visual.blocks.20.norm1.weight": "model-00001-of-00005.safetensors",
511
+ "visual.blocks.20.norm2.bias": "model-00001-of-00005.safetensors",
512
+ "visual.blocks.20.norm2.weight": "model-00001-of-00005.safetensors",
513
+ "visual.blocks.21.attn.proj.bias": "model-00001-of-00005.safetensors",
514
+ "visual.blocks.21.attn.proj.weight": "model-00001-of-00005.safetensors",
515
+ "visual.blocks.21.attn.qkv.bias": "model-00001-of-00005.safetensors",
516
+ "visual.blocks.21.attn.qkv.weight": "model-00001-of-00005.safetensors",
517
+ "visual.blocks.21.mlp.fc1.bias": "model-00001-of-00005.safetensors",
518
+ "visual.blocks.21.mlp.fc1.weight": "model-00001-of-00005.safetensors",
519
+ "visual.blocks.21.mlp.fc2.bias": "model-00001-of-00005.safetensors",
520
+ "visual.blocks.21.mlp.fc2.weight": "model-00001-of-00005.safetensors",
521
+ "visual.blocks.21.norm1.bias": "model-00001-of-00005.safetensors",
522
+ "visual.blocks.21.norm1.weight": "model-00001-of-00005.safetensors",
523
+ "visual.blocks.21.norm2.bias": "model-00001-of-00005.safetensors",
524
+ "visual.blocks.21.norm2.weight": "model-00001-of-00005.safetensors",
525
+ "visual.blocks.22.attn.proj.bias": "model-00001-of-00005.safetensors",
526
+ "visual.blocks.22.attn.proj.weight": "model-00001-of-00005.safetensors",
527
+ "visual.blocks.22.attn.qkv.bias": "model-00001-of-00005.safetensors",
528
+ "visual.blocks.22.attn.qkv.weight": "model-00001-of-00005.safetensors",
529
+ "visual.blocks.22.mlp.fc1.bias": "model-00001-of-00005.safetensors",
530
+ "visual.blocks.22.mlp.fc1.weight": "model-00001-of-00005.safetensors",
531
+ "visual.blocks.22.mlp.fc2.bias": "model-00001-of-00005.safetensors",
532
+ "visual.blocks.22.mlp.fc2.weight": "model-00001-of-00005.safetensors",
533
+ "visual.blocks.22.norm1.bias": "model-00001-of-00005.safetensors",
534
+ "visual.blocks.22.norm1.weight": "model-00001-of-00005.safetensors",
535
+ "visual.blocks.22.norm2.bias": "model-00001-of-00005.safetensors",
536
+ "visual.blocks.22.norm2.weight": "model-00001-of-00005.safetensors",
537
+ "visual.blocks.23.attn.proj.bias": "model-00001-of-00005.safetensors",
538
+ "visual.blocks.23.attn.proj.weight": "model-00001-of-00005.safetensors",
539
+ "visual.blocks.23.attn.qkv.bias": "model-00001-of-00005.safetensors",
540
+ "visual.blocks.23.attn.qkv.weight": "model-00001-of-00005.safetensors",
541
+ "visual.blocks.23.mlp.fc1.bias": "model-00001-of-00005.safetensors",
542
+ "visual.blocks.23.mlp.fc1.weight": "model-00001-of-00005.safetensors",
543
+ "visual.blocks.23.mlp.fc2.bias": "model-00001-of-00005.safetensors",
544
+ "visual.blocks.23.mlp.fc2.weight": "model-00001-of-00005.safetensors",
545
+ "visual.blocks.23.norm1.bias": "model-00001-of-00005.safetensors",
546
+ "visual.blocks.23.norm1.weight": "model-00001-of-00005.safetensors",
547
+ "visual.blocks.23.norm2.bias": "model-00001-of-00005.safetensors",
548
+ "visual.blocks.23.norm2.weight": "model-00001-of-00005.safetensors",
549
+ "visual.blocks.24.attn.proj.bias": "model-00001-of-00005.safetensors",
550
+ "visual.blocks.24.attn.proj.weight": "model-00001-of-00005.safetensors",
551
+ "visual.blocks.24.attn.qkv.bias": "model-00001-of-00005.safetensors",
552
+ "visual.blocks.24.attn.qkv.weight": "model-00001-of-00005.safetensors",
553
+ "visual.blocks.24.mlp.fc1.bias": "model-00001-of-00005.safetensors",
554
+ "visual.blocks.24.mlp.fc1.weight": "model-00001-of-00005.safetensors",
555
+ "visual.blocks.24.mlp.fc2.bias": "model-00001-of-00005.safetensors",
556
+ "visual.blocks.24.mlp.fc2.weight": "model-00001-of-00005.safetensors",
557
+ "visual.blocks.24.norm1.bias": "model-00001-of-00005.safetensors",
558
+ "visual.blocks.24.norm1.weight": "model-00001-of-00005.safetensors",
559
+ "visual.blocks.24.norm2.bias": "model-00001-of-00005.safetensors",
560
+ "visual.blocks.24.norm2.weight": "model-00001-of-00005.safetensors",
561
+ "visual.blocks.25.attn.proj.bias": "model-00001-of-00005.safetensors",
562
+ "visual.blocks.25.attn.proj.weight": "model-00001-of-00005.safetensors",
563
+ "visual.blocks.25.attn.qkv.bias": "model-00001-of-00005.safetensors",
564
+ "visual.blocks.25.attn.qkv.weight": "model-00001-of-00005.safetensors",
565
+ "visual.blocks.25.mlp.fc1.bias": "model-00001-of-00005.safetensors",
566
+ "visual.blocks.25.mlp.fc1.weight": "model-00001-of-00005.safetensors",
567
+ "visual.blocks.25.mlp.fc2.bias": "model-00001-of-00005.safetensors",
568
+ "visual.blocks.25.mlp.fc2.weight": "model-00001-of-00005.safetensors",
569
+ "visual.blocks.25.norm1.bias": "model-00001-of-00005.safetensors",
570
+ "visual.blocks.25.norm1.weight": "model-00001-of-00005.safetensors",
571
+ "visual.blocks.25.norm2.bias": "model-00001-of-00005.safetensors",
572
+ "visual.blocks.25.norm2.weight": "model-00001-of-00005.safetensors",
573
+ "visual.blocks.26.attn.proj.bias": "model-00001-of-00005.safetensors",
574
+ "visual.blocks.26.attn.proj.weight": "model-00001-of-00005.safetensors",
575
+ "visual.blocks.26.attn.qkv.bias": "model-00001-of-00005.safetensors",
576
+ "visual.blocks.26.attn.qkv.weight": "model-00001-of-00005.safetensors",
577
+ "visual.blocks.26.mlp.fc1.bias": "model-00001-of-00005.safetensors",
578
+ "visual.blocks.26.mlp.fc1.weight": "model-00001-of-00005.safetensors",
579
+ "visual.blocks.26.mlp.fc2.bias": "model-00001-of-00005.safetensors",
580
+ "visual.blocks.26.mlp.fc2.weight": "model-00001-of-00005.safetensors",
581
+ "visual.blocks.26.norm1.bias": "model-00001-of-00005.safetensors",
582
+ "visual.blocks.26.norm1.weight": "model-00001-of-00005.safetensors",
583
+ "visual.blocks.26.norm2.bias": "model-00001-of-00005.safetensors",
584
+ "visual.blocks.26.norm2.weight": "model-00001-of-00005.safetensors",
585
+ "visual.blocks.27.attn.proj.bias": "model-00001-of-00005.safetensors",
586
+ "visual.blocks.27.attn.proj.weight": "model-00001-of-00005.safetensors",
587
+ "visual.blocks.27.attn.qkv.bias": "model-00001-of-00005.safetensors",
588
+ "visual.blocks.27.attn.qkv.weight": "model-00001-of-00005.safetensors",
589
+ "visual.blocks.27.mlp.fc1.bias": "model-00001-of-00005.safetensors",
590
+ "visual.blocks.27.mlp.fc1.weight": "model-00001-of-00005.safetensors",
591
+ "visual.blocks.27.mlp.fc2.bias": "model-00001-of-00005.safetensors",
592
+ "visual.blocks.27.mlp.fc2.weight": "model-00001-of-00005.safetensors",
593
+ "visual.blocks.27.norm1.bias": "model-00001-of-00005.safetensors",
594
+ "visual.blocks.27.norm1.weight": "model-00001-of-00005.safetensors",
595
+ "visual.blocks.27.norm2.bias": "model-00001-of-00005.safetensors",
596
+ "visual.blocks.27.norm2.weight": "model-00001-of-00005.safetensors",
597
+ "visual.blocks.28.attn.proj.bias": "model-00001-of-00005.safetensors",
598
+ "visual.blocks.28.attn.proj.weight": "model-00001-of-00005.safetensors",
599
+ "visual.blocks.28.attn.qkv.bias": "model-00001-of-00005.safetensors",
600
+ "visual.blocks.28.attn.qkv.weight": "model-00001-of-00005.safetensors",
601
+ "visual.blocks.28.mlp.fc1.bias": "model-00001-of-00005.safetensors",
602
+ "visual.blocks.28.mlp.fc1.weight": "model-00001-of-00005.safetensors",
603
+ "visual.blocks.28.mlp.fc2.bias": "model-00001-of-00005.safetensors",
604
+ "visual.blocks.28.mlp.fc2.weight": "model-00001-of-00005.safetensors",
605
+ "visual.blocks.28.norm1.bias": "model-00001-of-00005.safetensors",
606
+ "visual.blocks.28.norm1.weight": "model-00001-of-00005.safetensors",
607
+ "visual.blocks.28.norm2.bias": "model-00001-of-00005.safetensors",
608
+ "visual.blocks.28.norm2.weight": "model-00001-of-00005.safetensors",
609
+ "visual.blocks.29.attn.proj.bias": "model-00001-of-00005.safetensors",
610
+ "visual.blocks.29.attn.proj.weight": "model-00001-of-00005.safetensors",
611
+ "visual.blocks.29.attn.qkv.bias": "model-00001-of-00005.safetensors",
612
+ "visual.blocks.29.attn.qkv.weight": "model-00001-of-00005.safetensors",
613
+ "visual.blocks.29.mlp.fc1.bias": "model-00001-of-00005.safetensors",
614
+ "visual.blocks.29.mlp.fc1.weight": "model-00001-of-00005.safetensors",
615
+ "visual.blocks.29.mlp.fc2.bias": "model-00001-of-00005.safetensors",
616
+ "visual.blocks.29.mlp.fc2.weight": "model-00001-of-00005.safetensors",
617
+ "visual.blocks.29.norm1.bias": "model-00001-of-00005.safetensors",
618
+ "visual.blocks.29.norm1.weight": "model-00001-of-00005.safetensors",
619
+ "visual.blocks.29.norm2.bias": "model-00001-of-00005.safetensors",
620
+ "visual.blocks.29.norm2.weight": "model-00001-of-00005.safetensors",
621
+ "visual.blocks.3.attn.proj.bias": "model-00001-of-00005.safetensors",
622
+ "visual.blocks.3.attn.proj.weight": "model-00001-of-00005.safetensors",
623
+ "visual.blocks.3.attn.qkv.bias": "model-00001-of-00005.safetensors",
624
+ "visual.blocks.3.attn.qkv.weight": "model-00001-of-00005.safetensors",
625
+ "visual.blocks.3.mlp.fc1.bias": "model-00001-of-00005.safetensors",
626
+ "visual.blocks.3.mlp.fc1.weight": "model-00001-of-00005.safetensors",
627
+ "visual.blocks.3.mlp.fc2.bias": "model-00001-of-00005.safetensors",
628
+ "visual.blocks.3.mlp.fc2.weight": "model-00001-of-00005.safetensors",
629
+ "visual.blocks.3.norm1.bias": "model-00001-of-00005.safetensors",
630
+ "visual.blocks.3.norm1.weight": "model-00001-of-00005.safetensors",
631
+ "visual.blocks.3.norm2.bias": "model-00001-of-00005.safetensors",
632
+ "visual.blocks.3.norm2.weight": "model-00001-of-00005.safetensors",
633
+ "visual.blocks.30.attn.proj.bias": "model-00001-of-00005.safetensors",
634
+ "visual.blocks.30.attn.proj.weight": "model-00001-of-00005.safetensors",
635
+ "visual.blocks.30.attn.qkv.bias": "model-00001-of-00005.safetensors",
636
+ "visual.blocks.30.attn.qkv.weight": "model-00001-of-00005.safetensors",
637
+ "visual.blocks.30.mlp.fc1.bias": "model-00001-of-00005.safetensors",
638
+ "visual.blocks.30.mlp.fc1.weight": "model-00001-of-00005.safetensors",
639
+ "visual.blocks.30.mlp.fc2.bias": "model-00001-of-00005.safetensors",
640
+ "visual.blocks.30.mlp.fc2.weight": "model-00001-of-00005.safetensors",
641
+ "visual.blocks.30.norm1.bias": "model-00001-of-00005.safetensors",
642
+ "visual.blocks.30.norm1.weight": "model-00001-of-00005.safetensors",
643
+ "visual.blocks.30.norm2.bias": "model-00001-of-00005.safetensors",
644
+ "visual.blocks.30.norm2.weight": "model-00001-of-00005.safetensors",
645
+ "visual.blocks.31.attn.proj.bias": "model-00001-of-00005.safetensors",
646
+ "visual.blocks.31.attn.proj.weight": "model-00001-of-00005.safetensors",
647
+ "visual.blocks.31.attn.qkv.bias": "model-00001-of-00005.safetensors",
648
+ "visual.blocks.31.attn.qkv.weight": "model-00001-of-00005.safetensors",
649
+ "visual.blocks.31.mlp.fc1.bias": "model-00001-of-00005.safetensors",
650
+ "visual.blocks.31.mlp.fc1.weight": "model-00001-of-00005.safetensors",
651
+ "visual.blocks.31.mlp.fc2.bias": "model-00001-of-00005.safetensors",
652
+ "visual.blocks.31.mlp.fc2.weight": "model-00001-of-00005.safetensors",
653
+ "visual.blocks.31.norm1.bias": "model-00001-of-00005.safetensors",
654
+ "visual.blocks.31.norm1.weight": "model-00001-of-00005.safetensors",
655
+ "visual.blocks.31.norm2.bias": "model-00001-of-00005.safetensors",
656
+ "visual.blocks.31.norm2.weight": "model-00001-of-00005.safetensors",
657
+ "visual.blocks.4.attn.proj.bias": "model-00001-of-00005.safetensors",
658
+ "visual.blocks.4.attn.proj.weight": "model-00001-of-00005.safetensors",
659
+ "visual.blocks.4.attn.qkv.bias": "model-00001-of-00005.safetensors",
660
+ "visual.blocks.4.attn.qkv.weight": "model-00001-of-00005.safetensors",
661
+ "visual.blocks.4.mlp.fc1.bias": "model-00001-of-00005.safetensors",
662
+ "visual.blocks.4.mlp.fc1.weight": "model-00001-of-00005.safetensors",
663
+ "visual.blocks.4.mlp.fc2.bias": "model-00001-of-00005.safetensors",
664
+ "visual.blocks.4.mlp.fc2.weight": "model-00001-of-00005.safetensors",
665
+ "visual.blocks.4.norm1.bias": "model-00001-of-00005.safetensors",
666
+ "visual.blocks.4.norm1.weight": "model-00001-of-00005.safetensors",
667
+ "visual.blocks.4.norm2.bias": "model-00001-of-00005.safetensors",
668
+ "visual.blocks.4.norm2.weight": "model-00001-of-00005.safetensors",
669
+ "visual.blocks.5.attn.proj.bias": "model-00001-of-00005.safetensors",
670
+ "visual.blocks.5.attn.proj.weight": "model-00001-of-00005.safetensors",
671
+ "visual.blocks.5.attn.qkv.bias": "model-00001-of-00005.safetensors",
672
+ "visual.blocks.5.attn.qkv.weight": "model-00001-of-00005.safetensors",
673
+ "visual.blocks.5.mlp.fc1.bias": "model-00001-of-00005.safetensors",
674
+ "visual.blocks.5.mlp.fc1.weight": "model-00001-of-00005.safetensors",
675
+ "visual.blocks.5.mlp.fc2.bias": "model-00001-of-00005.safetensors",
676
+ "visual.blocks.5.mlp.fc2.weight": "model-00001-of-00005.safetensors",
677
+ "visual.blocks.5.norm1.bias": "model-00001-of-00005.safetensors",
678
+ "visual.blocks.5.norm1.weight": "model-00001-of-00005.safetensors",
679
+ "visual.blocks.5.norm2.bias": "model-00001-of-00005.safetensors",
680
+ "visual.blocks.5.norm2.weight": "model-00001-of-00005.safetensors",
681
+ "visual.blocks.6.attn.proj.bias": "model-00001-of-00005.safetensors",
682
+ "visual.blocks.6.attn.proj.weight": "model-00001-of-00005.safetensors",
683
+ "visual.blocks.6.attn.qkv.bias": "model-00001-of-00005.safetensors",
684
+ "visual.blocks.6.attn.qkv.weight": "model-00001-of-00005.safetensors",
685
+ "visual.blocks.6.mlp.fc1.bias": "model-00001-of-00005.safetensors",
686
+ "visual.blocks.6.mlp.fc1.weight": "model-00001-of-00005.safetensors",
687
+ "visual.blocks.6.mlp.fc2.bias": "model-00001-of-00005.safetensors",
688
+ "visual.blocks.6.mlp.fc2.weight": "model-00001-of-00005.safetensors",
689
+ "visual.blocks.6.norm1.bias": "model-00001-of-00005.safetensors",
690
+ "visual.blocks.6.norm1.weight": "model-00001-of-00005.safetensors",
691
+ "visual.blocks.6.norm2.bias": "model-00001-of-00005.safetensors",
692
+ "visual.blocks.6.norm2.weight": "model-00001-of-00005.safetensors",
693
+ "visual.blocks.7.attn.proj.bias": "model-00001-of-00005.safetensors",
694
+ "visual.blocks.7.attn.proj.weight": "model-00001-of-00005.safetensors",
695
+ "visual.blocks.7.attn.qkv.bias": "model-00001-of-00005.safetensors",
696
+ "visual.blocks.7.attn.qkv.weight": "model-00001-of-00005.safetensors",
697
+ "visual.blocks.7.mlp.fc1.bias": "model-00001-of-00005.safetensors",
698
+ "visual.blocks.7.mlp.fc1.weight": "model-00001-of-00005.safetensors",
699
+ "visual.blocks.7.mlp.fc2.bias": "model-00001-of-00005.safetensors",
700
+ "visual.blocks.7.mlp.fc2.weight": "model-00001-of-00005.safetensors",
701
+ "visual.blocks.7.norm1.bias": "model-00001-of-00005.safetensors",
702
+ "visual.blocks.7.norm1.weight": "model-00001-of-00005.safetensors",
703
+ "visual.blocks.7.norm2.bias": "model-00001-of-00005.safetensors",
704
+ "visual.blocks.7.norm2.weight": "model-00001-of-00005.safetensors",
705
+ "visual.blocks.8.attn.proj.bias": "model-00001-of-00005.safetensors",
706
+ "visual.blocks.8.attn.proj.weight": "model-00001-of-00005.safetensors",
707
+ "visual.blocks.8.attn.qkv.bias": "model-00001-of-00005.safetensors",
708
+ "visual.blocks.8.attn.qkv.weight": "model-00001-of-00005.safetensors",
709
+ "visual.blocks.8.mlp.fc1.bias": "model-00001-of-00005.safetensors",
710
+ "visual.blocks.8.mlp.fc1.weight": "model-00001-of-00005.safetensors",
711
+ "visual.blocks.8.mlp.fc2.bias": "model-00001-of-00005.safetensors",
712
+ "visual.blocks.8.mlp.fc2.weight": "model-00001-of-00005.safetensors",
713
+ "visual.blocks.8.norm1.bias": "model-00001-of-00005.safetensors",
714
+ "visual.blocks.8.norm1.weight": "model-00001-of-00005.safetensors",
715
+ "visual.blocks.8.norm2.bias": "model-00001-of-00005.safetensors",
716
+ "visual.blocks.8.norm2.weight": "model-00001-of-00005.safetensors",
717
+ "visual.blocks.9.attn.proj.bias": "model-00001-of-00005.safetensors",
718
+ "visual.blocks.9.attn.proj.weight": "model-00001-of-00005.safetensors",
719
+ "visual.blocks.9.attn.qkv.bias": "model-00001-of-00005.safetensors",
720
+ "visual.blocks.9.attn.qkv.weight": "model-00001-of-00005.safetensors",
721
+ "visual.blocks.9.mlp.fc1.bias": "model-00001-of-00005.safetensors",
722
+ "visual.blocks.9.mlp.fc1.weight": "model-00001-of-00005.safetensors",
723
+ "visual.blocks.9.mlp.fc2.bias": "model-00001-of-00005.safetensors",
724
+ "visual.blocks.9.mlp.fc2.weight": "model-00001-of-00005.safetensors",
725
+ "visual.blocks.9.norm1.bias": "model-00001-of-00005.safetensors",
726
+ "visual.blocks.9.norm1.weight": "model-00001-of-00005.safetensors",
727
+ "visual.blocks.9.norm2.bias": "model-00001-of-00005.safetensors",
728
+ "visual.blocks.9.norm2.weight": "model-00001-of-00005.safetensors",
729
+ "visual.merger.ln_q.bias": "model-00001-of-00005.safetensors",
730
+ "visual.merger.ln_q.weight": "model-00001-of-00005.safetensors",
731
+ "visual.merger.mlp.0.bias": "model-00001-of-00005.safetensors",
732
+ "visual.merger.mlp.0.weight": "model-00001-of-00005.safetensors",
733
+ "visual.merger.mlp.2.bias": "model-00001-of-00005.safetensors",
734
+ "visual.merger.mlp.2.weight": "model-00001-of-00005.safetensors",
735
+ "visual.patch_embed.proj.weight": "model-00001-of-00005.safetensors"
736
+ }
737
+ }
models/Qwen2-VL-7B-Instruct/preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "min_pixels": 3136,
3
+ "max_pixels": 12845056,
4
+ "patch_size": 14,
5
+ "temporal_patch_size": 2,
6
+ "merge_size": 2,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "image_processor_type": "Qwen2VLImageProcessor",
18
+ "processor_class": "Qwen2VLProcessor"
19
+ }
models/Qwen2-VL-7B-Instruct/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/Qwen2-VL-7B-Instruct/tokenizer_config.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|object_ref_start|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "<|object_ref_end|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|box_start|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|box_end|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|quad_start|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|quad_end|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151652": {
77
+ "content": "<|vision_start|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151653": {
85
+ "content": "<|vision_end|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151654": {
93
+ "content": "<|vision_pad|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151655": {
101
+ "content": "<|image_pad|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151656": {
109
+ "content": "<|video_pad|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ }
116
+ },
117
+ "additional_special_tokens": ["<|im_start|>", "<|im_end|>", "<|object_ref_start|>","<|object_ref_end|>","<|box_start|>","<|box_end|>","<|quad_start|>","<|quad_end|>","<|vision_start|>","<|vision_end|>","<|vision_pad|>","<|image_pad|>","<|video_pad|>"],
118
+ "bos_token": null,
119
+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
120
+ "clean_up_tokenization_spaces": false,
121
+ "eos_token": "<|im_end|>",
122
+ "padding_side": "left",
123
+ "errors": "replace",
124
+ "model_max_length": 32768,
125
+ "pad_token": "<|endoftext|>",
126
+ "split_special_tokens": false,
127
+ "tokenizer_class": "Qwen2Tokenizer",
128
+ "unk_token": null
129
+ }
models/Qwen2-VL-7B-Instruct/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
models/SmolVLM-Instruct/.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ onnx/decoder_model_merged.onnx_data filter=lfs diff=lfs merge=lfs -text
37
+ onnx/decoder_model_merged_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
models/SmolVLM-Instruct/README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ datasets:
5
+ - HuggingFaceM4/the_cauldron
6
+ - HuggingFaceM4/Docmatix
7
+ pipeline_tag: image-text-to-text
8
+ language:
9
+ - en
10
+ base_model:
11
+ - HuggingFaceTB/SmolLM2-1.7B-Instruct
12
+ - google/siglip-so400m-patch14-384
13
+ ---
14
+
15
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/SmolVLM.png" width="800" height="auto" alt="Image description">
16
+
17
+ # SmolVLM
18
+
19
+ SmolVLM is a compact open multimodal model that accepts arbitrary sequences of image and text inputs to produce text outputs. Designed for efficiency, SmolVLM can answer questions about images, describe visual content, create stories grounded on multiple images, or function as a pure language model without visual inputs. Its lightweight architecture makes it suitable for on-device applications while maintaining strong performance on multimodal tasks.
20
+
21
+ ## Model Summary
22
+
23
+ - **Developed by:** Hugging Face 🤗
24
+ - **Model type:** Multi-modal model (image+text)
25
+ - **Language(s) (NLP):** English
26
+ - **License:** Apache 2.0
27
+ - **Architecture:** Based on [Idefics3](https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3) (see technical summary)
28
+
29
+ ## Resources
30
+
31
+ - **Demo:** [SmolVLM Demo](https://huggingface.co/spaces/HuggingFaceTB/SmolVLM)
32
+ - **Blog:** [Blog post](https://huggingface.co/blog/smolvlm)
33
+
34
+ ## Uses
35
+
36
+ SmolVLM can be used for inference on multimodal (image + text) tasks where the input comprises text queries along with one or more images. Text and images can be interleaved arbitrarily, enabling tasks like image captioning, visual question answering, and storytelling based on visual content. The model does not support image generation.
37
+
38
+ To fine-tune SmolVLM on a specific task, you can follow the fine-tuning tutorial.
39
+ <!-- todo: add link to fine-tuning tutorial -->
40
+
41
+ ### Technical Summary
42
+
43
+ SmolVLM leverages the lightweight SmolLM2 language model to provide a compact yet powerful multimodal experience. It introduces several changes compared to previous Idefics models:
44
+
45
+ - **Image compression:** We introduce a more radical image compression compared to Idefics3 to enable the model to infer faster and use less RAM.
46
+ - **Visual Token Encoding:** SmolVLM uses 81 visual tokens to encode image patches of size 384×384. Larger images are divided into patches, each encoded separately, enhancing efficiency without compromising performance.
47
+
48
+ More details about the training and architecture are available in our technical report.
49
+
50
+
51
+ ### How to get started
52
+
53
+ You can use transformers to load, infer and fine-tune SmolVLM.
54
+
55
+ ```python
56
+ import torch
57
+ from PIL import Image
58
+ from transformers import AutoProcessor, AutoModelForVision2Seq
59
+ from transformers.image_utils import load_image
60
+
61
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
62
+
63
+ # Load images
64
+ image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
65
+ image2 = load_image("https://huggingface.co/spaces/merve/chameleon-7b/resolve/main/bee.jpg")
66
+
67
+ # Initialize processor and model
68
+ processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct")
69
+ model = AutoModelForVision2Seq.from_pretrained(
70
+ "HuggingFaceTB/SmolVLM-Instruct",
71
+ torch_dtype=torch.bfloat16,
72
+ _attn_implementation="flash_attention_2" if DEVICE == "cuda" else "eager",
73
+ ).to(DEVICE)
74
+
75
+ # Create input messages
76
+ messages = [
77
+ {
78
+ "role": "user",
79
+ "content": [
80
+ {"type": "image"},
81
+ {"type": "image"},
82
+ {"type": "text", "text": "Can you describe the two images?"}
83
+ ]
84
+ },
85
+ ]
86
+
87
+ # Prepare inputs
88
+ prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
89
+ inputs = processor(text=prompt, images=[image1, image2], return_tensors="pt")
90
+ inputs = inputs.to(DEVICE)
91
+
92
+ # Generate outputs
93
+ generated_ids = model.generate(**inputs, max_new_tokens=500)
94
+ generated_texts = processor.batch_decode(
95
+ generated_ids,
96
+ skip_special_tokens=True,
97
+ )
98
+
99
+ print(generated_texts[0])
100
+ """
101
+ Assistant: The first image shows a green statue of the Statue of Liberty standing on a stone pedestal in front of a body of water.
102
+ The statue is holding a torch in its right hand and a tablet in its left hand. The water is calm and there are no boats or other objects visible.
103
+ The sky is clear and there are no clouds. The second image shows a bee on a pink flower.
104
+ The bee is black and yellow and is collecting pollen from the flower. The flower is surrounded by green leaves.
105
+ """
106
+ ```
107
+
108
+
109
+ ### Model optimizations
110
+
111
+ **Precision**: For better performance, load and run the model in half-precision (`torch.float16` or `torch.bfloat16`) if your hardware supports it.
112
+
113
+ ```python
114
+ from transformers import AutoModelForVision2Seq
115
+ import torch
116
+
117
+ model = AutoModelForVision2Seq.from_pretrained(
118
+ "HuggingFaceTB/SmolVLM-Instruct",
119
+ torch_dtype=torch.bfloat16
120
+ ).to("cuda")
121
+ ```
122
+
123
+ You can also load SmolVLM with 4/8-bit quantization using bitsandbytes, torchao or Quanto. Refer to [this page](https://huggingface.co/docs/transformers/en/main_classes/quantization) for other options.
124
+
125
+ ```python
126
+ from transformers import AutoModelForVision2Seq, BitsAndBytesConfig
127
+ import torch
128
+
129
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
130
+ model = AutoModelForVision2Seq.from_pretrained(
131
+ "HuggingFaceTB/SmolVLM-Instruct",
132
+ quantization_config=quantization_config,
133
+ )
134
+ ```
135
+
136
+ **Vision Encoder Efficiency**: Adjust the image resolution by setting `size={"longest_edge": N*384}` when initializing the processor, where N is your desired value. The default `N=4` works well, which results in input images of
137
+ size 1536×1536. For documents, `N=5` might be beneficial. Decreasing N can save GPU memory and is appropriate for lower-resolution images. This is also useful if you want to fine-tune on videos.
138
+
139
+
140
+ ## Misuse and Out-of-scope Use
141
+
142
+ SmolVLM is not intended for high-stakes scenarios or critical decision-making processes that affect an individual's well-being or livelihood. The model may produce content that appears factual but may not be accurate. Misuse includes, but is not limited to:
143
+
144
+ - Prohibited Uses:
145
+ - Evaluating or scoring individuals (e.g., in employment, education, credit)
146
+ - Critical automated decision-making
147
+ - Generating unreliable factual content
148
+ - Malicious Activities:
149
+ - Spam generation
150
+ - Disinformation campaigns
151
+ - Harassment or abuse
152
+ - Unauthorized surveillance
153
+
154
+ ### License
155
+
156
+ SmolVLM is built upon [the shape-optimized SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384) as image encoder and [SmolLM2](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct) for text decoder part.
157
+
158
+ We release the SmolVLM checkpoints under the Apache 2.0 license.
159
+
160
+ ## Training Details
161
+
162
+ ### Training Data
163
+
164
+ The training data comes from [The Cauldron](https://huggingface.co/datasets/HuggingFaceM4/the_cauldron) and [Docmatix](https://huggingface.co/datasets/HuggingFaceM4/Docmatix) datasets, with emphasis on document understanding (25%) and image captioning (18%), while maintaining balanced coverage across other crucial capabilities like visual reasoning, chart comprehension, and general instruction following.
165
+ <img src="https://huggingface.co/HuggingFaceTB/SmolVLM-Instruct/resolve/main/mixture_the_cauldron.png" alt="Example Image" style="width:90%;" />
166
+
167
+
168
+
169
+
170
+ ## Evaluation
171
+
172
+ | Model | MMMU (val) | MathVista (testmini) | MMStar (val) | DocVQA (test) | TextVQA (val) | Min GPU RAM required (GB) |
173
+ |-------------------|------------|----------------------|--------------|---------------|---------------|---------------------------|
174
+ | SmolVLM | 38.8 | 44.6 | 42.1 | 81.6 | 72.7 | 5.02 |
175
+ | Qwen-VL 2B | 41.1 | 47.8 | 47.5 | 90.1 | 79.7 | 13.70 |
176
+ | InternVL2 2B | 34.3 | 46.3 | 49.8 | 86.9 | 73.4 | 10.52 |
177
+ | PaliGemma 3B 448px| 34.9 | 28.7 | 48.3 | 32.2 | 56.0 | 6.72 |
178
+ | moondream2 | 32.4 | 24.3 | 40.3 | 70.5 | 65.2 | 3.87 |
179
+ | MiniCPM-V-2 | 38.2 | 39.8 | 39.1 | 71.9 | 74.1 | 7.88 |
180
+ | MM1.5 1B | 35.8 | 37.2 | 0.0 | 81.0 | 72.5 | NaN |
181
+
182
+ # Citation information
183
+ You can cite us in the following way:
184
+ ```bibtex
185
+ @article{marafioti2025smolvlm,
186
+ title={SmolVLM: Redefining small and efficient multimodal models},
187
+ author={Andrés Marafioti and Orr Zohar and Miquel Farré and Merve Noyan and Elie Bakouch and Pedro Cuenca and Cyril Zakka and Loubna Ben Allal and Anton Lozhkov and Nouamane Tazi and Vaibhav Srivastav and Joshua Lochner and Hugo Larcher and Mathieu Morlon and Lewis Tunstall and Leandro von Werra and Thomas Wolf},
188
+ journal={arXiv preprint arXiv:2504.05299},
189
+ year={2025}
190
+ }
191
+ ```
models/SmolVLM-Instruct/added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<end_of_utterance>": 49154,
3
+ "<fake_token_around_image>": 49152,
4
+ "<image>": 49153
5
+ }
models/SmolVLM-Instruct/chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "<|im_start|>{% for message in messages %}{{message['role'] | capitalize}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"
3
+ }
models/SmolVLM-Instruct/config.json ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Idefics3ForConditionalGeneration"
4
+ ],
5
+ "image_seq_len": 81,
6
+ "image_token_id": 49153,
7
+ "model_type": "idefics3",
8
+ "scale_factor": 3,
9
+ "text_config": {
10
+ "_attn_implementation_autoset": false,
11
+ "_flash_attn_2_enabled": true,
12
+ "_name_or_path": "/fsx/m4/experiments/local_experiment_dir/s3_async_temporary_checkpoint_folder/tr_324_opt_400/unwrapped_model",
13
+ "add_cross_attention": false,
14
+ "architectures": [
15
+ "VLlama3ForCausalLM"
16
+ ],
17
+ "attention_bias": false,
18
+ "attention_dropout": 0.0,
19
+ "bad_words_ids": null,
20
+ "begin_suppress_tokens": null,
21
+ "bos_token_id": 0,
22
+ "chunk_size_feed_forward": 0,
23
+ "cross_attention_hidden_size": null,
24
+ "decoder_start_token_id": null,
25
+ "diversity_penalty": 0.0,
26
+ "do_sample": false,
27
+ "early_stopping": false,
28
+ "encoder_no_repeat_ngram_size": 0,
29
+ "eos_token_id": 0,
30
+ "exponential_decay_length_penalty": null,
31
+ "finetuning_task": null,
32
+ "forced_bos_token_id": null,
33
+ "forced_eos_token_id": null,
34
+ "head_dim": 64,
35
+ "hidden_act": "silu",
36
+ "hidden_size": 2048,
37
+ "id2label": {
38
+ "0": "LABEL_0",
39
+ "1": "LABEL_1"
40
+ },
41
+ "initializer_range": 0.02,
42
+ "intermediate_size": 8192,
43
+ "is_decoder": false,
44
+ "is_encoder_decoder": false,
45
+ "label2id": {
46
+ "LABEL_0": 0,
47
+ "LABEL_1": 1
48
+ },
49
+ "length_penalty": 1.0,
50
+ "max_length": 20,
51
+ "max_position_embeddings": 16384,
52
+ "min_length": 0,
53
+ "mlp_bias": false,
54
+ "model_type": "llama",
55
+ "neftune_noise_alpha": 0.0,
56
+ "no_repeat_ngram_size": 0,
57
+ "num_attention_heads": 32,
58
+ "num_beam_groups": 1,
59
+ "num_beams": 1,
60
+ "num_hidden_layers": 24,
61
+ "num_key_value_heads": 32,
62
+ "num_return_sequences": 1,
63
+ "output_attentions": false,
64
+ "output_hidden_states": false,
65
+ "output_scores": false,
66
+ "pad_token_id": 2,
67
+ "perceiver_config": {
68
+ "_attn_implementation_autoset": false,
69
+ "_name_or_path": "",
70
+ "add_cross_attention": false,
71
+ "architectures": null,
72
+ "attention_dropout": 0.0,
73
+ "bad_words_ids": null,
74
+ "begin_suppress_tokens": null,
75
+ "bos_token_id": null,
76
+ "chunk_size_feed_forward": 0,
77
+ "cross_attention_hidden_size": null,
78
+ "decoder_start_token_id": null,
79
+ "diversity_penalty": 0.0,
80
+ "do_sample": false,
81
+ "early_stopping": false,
82
+ "encoder_no_repeat_ngram_size": 0,
83
+ "eos_token_id": null,
84
+ "exponential_decay_length_penalty": null,
85
+ "finetuning_task": null,
86
+ "forced_bos_token_id": null,
87
+ "forced_eos_token_id": null,
88
+ "hidden_act": "silu",
89
+ "id2label": {
90
+ "0": "LABEL_0",
91
+ "1": "LABEL_1"
92
+ },
93
+ "is_decoder": false,
94
+ "is_encoder_decoder": false,
95
+ "label2id": {
96
+ "LABEL_0": 0,
97
+ "LABEL_1": 1
98
+ },
99
+ "length_penalty": 1.0,
100
+ "max_length": 20,
101
+ "min_length": 0,
102
+ "model_type": "vllama3",
103
+ "no_repeat_ngram_size": 0,
104
+ "num_beam_groups": 1,
105
+ "num_beams": 1,
106
+ "num_key_value_heads": 1,
107
+ "num_return_sequences": 1,
108
+ "output_attentions": false,
109
+ "output_hidden_states": false,
110
+ "output_scores": false,
111
+ "pad_token_id": null,
112
+ "prefix": null,
113
+ "problem_type": null,
114
+ "pruned_heads": {},
115
+ "qk_layer_norms_perceiver": false,
116
+ "remove_invalid_values": false,
117
+ "repetition_penalty": 1.0,
118
+ "resampler_depth": 6,
119
+ "resampler_head_dim": 96,
120
+ "resampler_n_heads": 16,
121
+ "resampler_n_latents": 64,
122
+ "return_dict": true,
123
+ "return_dict_in_generate": false,
124
+ "sep_token_id": null,
125
+ "suppress_tokens": null,
126
+ "task_specific_params": null,
127
+ "temperature": 1.0,
128
+ "tf_legacy_loss": false,
129
+ "tie_encoder_decoder": false,
130
+ "tie_word_embeddings": true,
131
+ "tokenizer_class": null,
132
+ "top_k": 50,
133
+ "top_p": 1.0,
134
+ "torch_dtype": null,
135
+ "torchscript": false,
136
+ "transformers_version": "4.46.0",
137
+ "typical_p": 1.0,
138
+ "use_bfloat16": false
139
+ },
140
+ "prefix": null,
141
+ "pretraining_tp": 1,
142
+ "problem_type": null,
143
+ "pruned_heads": {},
144
+ "qk_layer_norms": false,
145
+ "remove_invalid_values": false,
146
+ "repetition_penalty": 1.0,
147
+ "return_dict": true,
148
+ "return_dict_in_generate": false,
149
+ "rms_norm_eps": 1e-05,
150
+ "rope_scaling": null,
151
+ "rope_theta": 273768.0,
152
+ "sep_token_id": null,
153
+ "suppress_tokens": null,
154
+ "task_specific_params": null,
155
+ "temperature": 1.0,
156
+ "tf_legacy_loss": false,
157
+ "tie_encoder_decoder": false,
158
+ "tie_word_embeddings": false,
159
+ "tokenizer_class": null,
160
+ "top_k": 50,
161
+ "top_p": 1.0,
162
+ "torch_dtype": "bfloat16",
163
+ "torchscript": false,
164
+ "typical_p": 1.0,
165
+ "use_bfloat16": false,
166
+ "use_cache": true,
167
+ "use_resampler": false,
168
+ "vocab_size": 49155
169
+ },
170
+ "tie_word_embeddings": false,
171
+ "torch_dtype": "bfloat16",
172
+ "transformers_version": "4.46.0",
173
+ "transformers.js_config": {
174
+ "kv_cache_dtype": {
175
+ "q4f16": "float16",
176
+ "fp16": "float16"
177
+ },
178
+ "dtype": {
179
+ "embed_tokens": "auto",
180
+ "vision_encoder": "auto",
181
+ "decoder_model_merged": "q4"
182
+ },
183
+ "use_external_data_format": {
184
+ "decoder_model_merged.onnx": true,
185
+ "decoder_model_merged_fp16.onnx": true
186
+ }
187
+ },
188
+ "use_cache": true,
189
+ "vision_config": {
190
+ "size": {"longest_edge": 1920},
191
+ "max_image_size": {"longest_edge": 384},
192
+ "_attn_implementation_autoset": false,
193
+ "_name_or_path": "",
194
+ "add_cross_attention": false,
195
+ "architectures": null,
196
+ "attention_dropout": 0.0,
197
+ "bad_words_ids": null,
198
+ "begin_suppress_tokens": null,
199
+ "bos_token_id": null,
200
+ "chunk_size_feed_forward": 0,
201
+ "cross_attention_hidden_size": null,
202
+ "decoder_start_token_id": null,
203
+ "diversity_penalty": 0.0,
204
+ "do_sample": false,
205
+ "early_stopping": false,
206
+ "encoder_no_repeat_ngram_size": 0,
207
+ "eos_token_id": null,
208
+ "exponential_decay_length_penalty": null,
209
+ "finetuning_task": null,
210
+ "forced_bos_token_id": null,
211
+ "forced_eos_token_id": null,
212
+ "hidden_act": "gelu_pytorch_tanh",
213
+ "hidden_size": 1152,
214
+ "id2label": {
215
+ "0": "LABEL_0",
216
+ "1": "LABEL_1"
217
+ },
218
+ "image_size": 384,
219
+ "initializer_range": 0.02,
220
+ "intermediate_size": 4304,
221
+ "is_decoder": false,
222
+ "is_encoder_decoder": false,
223
+ "label2id": {
224
+ "LABEL_0": 0,
225
+ "LABEL_1": 1
226
+ },
227
+ "layer_norm_eps": 1e-06,
228
+ "length_penalty": 1.0,
229
+ "max_length": 20,
230
+ "min_length": 0,
231
+ "model_type": "idefics3",
232
+ "no_repeat_ngram_size": 0,
233
+ "num_attention_heads": 16,
234
+ "num_beam_groups": 1,
235
+ "num_beams": 1,
236
+ "num_channels": 3,
237
+ "num_hidden_layers": 27,
238
+ "num_return_sequences": 1,
239
+ "output_attentions": false,
240
+ "output_hidden_states": false,
241
+ "output_scores": false,
242
+ "pad_token_id": null,
243
+ "patch_size": 14,
244
+ "prefix": null,
245
+ "problem_type": null,
246
+ "pruned_heads": {},
247
+ "remove_invalid_values": false,
248
+ "repetition_penalty": 1.0,
249
+ "return_dict": true,
250
+ "return_dict_in_generate": false,
251
+ "sep_token_id": null,
252
+ "suppress_tokens": null,
253
+ "task_specific_params": null,
254
+ "temperature": 1.0,
255
+ "tf_legacy_loss": false,
256
+ "tie_encoder_decoder": false,
257
+ "tie_word_embeddings": false,
258
+ "tokenizer_class": null,
259
+ "top_k": 50,
260
+ "top_p": 1.0,
261
+ "torch_dtype": null,
262
+ "torchscript": false,
263
+ "typical_p": 1.0,
264
+ "use_bfloat16": false
265
+ },
266
+ "vocab_size": 49155
267
+ }
models/SmolVLM-Instruct/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 49154,
5
+ "pad_token_id": 2,
6
+ "transformers_version": "4.46.0"
7
+ }
models/SmolVLM-Instruct/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/SmolVLM-Instruct/preprocessor_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": true,
3
+ "do_image_splitting": true,
4
+ "do_normalize": true,
5
+ "do_pad": true,
6
+ "do_rescale": true,
7
+ "do_resize": true,
8
+ "image_mean": [
9
+ 0.5,
10
+ 0.5,
11
+ 0.5
12
+ ],
13
+ "image_processor_type": "Idefics3ImageProcessor",
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "max_image_size": {
20
+ "longest_edge": 384
21
+ },
22
+ "processor_class": "Idefics3Processor",
23
+ "resample": 1,
24
+ "rescale_factor": 0.00392156862745098,
25
+ "size": {
26
+ "longest_edge": 1536
27
+ }
28
+ }
models/SmolVLM-Instruct/processor_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "processor_class": "Idefics3Processor",
3
+ "image_seq_len": 81
4
+ }
models/SmolVLM-Instruct/smolvlm-data.pdf ADDED
Binary file (55.4 kB). View file
 
models/SmolVLM-Instruct/special_tokens_map.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "content": "<end_of_utterance>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ ],
25
+ "bos_token": {
26
+ "content": "<|im_start|>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ "eos_token": {
33
+ "content": "<|im_end|>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ },
39
+ "pad_token": {
40
+ "content": "<|im_end|>",
41
+ "lstrip": false,
42
+ "normalized": false,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ "unk_token": {
47
+ "content": "<|endoftext|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false
52
+ }
53
+ }
models/SmolVLM-Instruct/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff