Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- models/Phi-4-multimodal-instruct/model.safetensors.index.jsonAdded
- models/Phi-4-multimodal-instruct/modeling_phi4mm.pyAdded
- models/Phi-4-multimodal-instruct/preprocessor_config.jsonAdded+14
- models/Phi-4-multimodal-instruct/processing_phi4mm.pyAdded+733
- models/Phi-4-multimodal-instruct/processor_config.jsonAdded+6
- models/Phi-4-multimodal-instruct/sample_finetune_speech.pyAdded+478
- models/Phi-4-multimodal-instruct/sample_finetune_vision.pyAdded+556
- models/Phi-4-multimodal-instruct/sample_inference_phi4mm.pyAdded+243
- models/Phi-4-multimodal-instruct/special_tokens_map.jsonAdded+24
- models/Phi-4-multimodal-instruct/speech-lora/adapter_config.jsonAdded+23
- models/Phi-4-multimodal-instruct/speech-lora/added_tokens.jsonAdded+12
- models/Phi-4-multimodal-instruct/speech-lora/special_tokens_map.jsonAdded+24
- models/Phi-4-multimodal-instruct/speech-lora/tokenizer_config.jsonAdded+125
- models/Phi-4-multimodal-instruct/speech-lora/vocab.jsonAdded
- models/Phi-4-multimodal-instruct/speech_conformer_encoder.pyAdded
- models/Phi-4-multimodal-instruct/tokenizer_config.jsonAdded+125
- models/Phi-4-multimodal-instruct/vision-lora/adapter_config.jsonAdded+23
- models/Phi-4-multimodal-instruct/vision-lora/added_tokens.jsonAdded+12
- models/Phi-4-multimodal-instruct/vision-lora/special_tokens_map.jsonAdded+24
- models/Phi-4-multimodal-instruct/vision-lora/tokenizer_config.jsonAdded+125
- models/Phi-4-multimodal-instruct/vision-lora/vocab.jsonAdded
- models/Phi-4-multimodal-instruct/vision_siglip_navit.pyAdded+1717
- models/Phi-4-multimodal-instruct/vocab.jsonAdded
- models/Pixtral-12B-2409/.gitattributesAdded+36
- models/Pixtral-12B-2409/README.mdAdded+294
- models/Pixtral-12B-2409/params.jsonAdded+25
- models/Qwen2-VL-7B-Instruct/.gitattributesAdded+35
- models/Qwen2-VL-7B-Instruct/LICENSEAdded+202
- models/Qwen2-VL-7B-Instruct/README.mdAdded+502
- models/Qwen2-VL-7B-Instruct/chat_template.jsonAdded+3
- models/Qwen2-VL-7B-Instruct/config.jsonAdded+52
- models/Qwen2-VL-7B-Instruct/generation_config.jsonAdded+14
- models/Qwen2-VL-7B-Instruct/merges.txtAdded
- models/Qwen2-VL-7B-Instruct/model.safetensors.index.jsonAdded+737
- models/Qwen2-VL-7B-Instruct/preprocessor_config.jsonAdded+19
- models/Qwen2-VL-7B-Instruct/tokenizer.jsonAdded
- models/Qwen2-VL-7B-Instruct/tokenizer_config.jsonAdded+129
- models/Qwen2-VL-7B-Instruct/vocab.jsonAdded
- models/SmolVLM-Instruct/.gitattributesAdded+37
- models/SmolVLM-Instruct/README.mdAdded+191
- models/SmolVLM-Instruct/added_tokens.jsonAdded+5
- models/SmolVLM-Instruct/chat_template.jsonAdded+3
- models/SmolVLM-Instruct/config.jsonAdded+267
- models/SmolVLM-Instruct/generation_config.jsonAdded+7
- models/SmolVLM-Instruct/merges.txtAdded
- models/SmolVLM-Instruct/preprocessor_config.jsonAdded+28
- models/SmolVLM-Instruct/processor_config.jsonAdded+4
- models/SmolVLM-Instruct/smolvlm-data.pdfAdded
- models/SmolVLM-Instruct/special_tokens_map.jsonAdded+53
- models/SmolVLM-Instruct/tokenizer.jsonAdded
1234567891011121314{ "auto_map": { "AutoProcessor": "processing_phi4mm.Phi4MMProcessor", "AutoImageProcessor": "processing_phi4mm.Phi4MMImageProcessor", "AutoFeatureExtractor": "processing_phi4mm.Phi4MMAudioFeatureExtractor" }, "image_processor_type": "Phi4MMImageProcessor", "processor_class": "Phi4MMProcessor", "feature_extractor_type": "Phi4MMAudioFeatureExtractor", "audio_compression_rate": 8, "audio_downsample_rate": 1, "audio_feat_stride": 1, "dynamic_hd": 36}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Processor class for Phi4MM"""import refrom typing import List, Optional, Tuple, Unionimport mathfrom enum import Enum
import numpy as npimport scipyimport torchimport torchvision
from transformers import AutoFeatureExtractor, AutoImageProcessorfrom transformers.feature_extraction_sequence_utils import SequenceFeatureExtractorfrom transformers.image_processing_utils import BaseImageProcessor, BatchFeaturefrom transformers.image_utils import ( ImageInput, make_list_of_images, valid_images,)from transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategyfrom transformers.utils import TensorType, loggingfrom torch.nn.utils.rnn import pad_sequence
logger = logging.get_logger(__name__)
# Special tokens_COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN = r'<\|image_\d+\|>' # For backward compatibility_COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN = r'<\|audio_\d+\|>' # For backward compatibility_IMAGE_SPECIAL_TOKEN = '<|endoftext10|>'_AUDIO_SPECIAL_TOKEN = '<|endoftext11|>'_IMAGE_SPECIAL_TOKEN_ID = 200010 # '<|endoftext10|>', or we can better name it (in `tokenizer_config.json`)_AUDIO_SPECIAL_TOKEN_ID = 200011 # '<|endoftext11|>'
class InputMode(Enum): LANGUAGE = 0 VISION = 1 SPEECH = 2 VISION_SPEECH = 3
class Phi4MMImageProcessor(BaseImageProcessor): r""" Constructs a Phi4MM image processor. """ model_input_names = ["input_image_embeds", "image_sizes", "image_attention_mask"]
def __init__( self, dynamic_hd, **kwargs, ) -> None: super().__init__(**kwargs) self.dynamic_hd = dynamic_hd
def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float('inf') best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio
def dynamic_preprocess(self, image, min_num=1, max_num=12, image_size=384, mask_size=27, use_thumbnail=True): orig_width, orig_height = image.size
w_crop_num = math.ceil(orig_width/float(image_size)) h_crop_num = math.ceil(orig_height/float(image_size)) if w_crop_num * h_crop_num > max_num:
aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio target_ratios = set( (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 i * j <= max_num and i * j >= min_num) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target target_aspect_ratio = self.find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] else: target_width = image_size * w_crop_num target_height = image_size * h_crop_num target_aspect_ratio = (w_crop_num, h_crop_num)
# Calculate the ratio ratio_width = target_width / orig_width ratio_height = target_height / orig_height if ratio_width < ratio_height: new_size = (target_width, int(orig_height * ratio_width)) padding_width = 0 padding_height = target_height - int(orig_height * ratio_width) else: new_size = (int(orig_width * ratio_height), target_height) padding_width = target_width - int(orig_width * ratio_height) padding_height = 0
attention_mask = torch.ones((int(mask_size*target_aspect_ratio[1]), int(mask_size*target_aspect_ratio[0]))) if padding_width >= 14: attention_mask[:, -math.floor(padding_width/14):] = 0 if padding_height >= 14: attention_mask[-math.floor(padding_height/14):,:] = 0 assert attention_mask.sum() > 0
if min(new_size[1], target_height) < 10 or min(new_size[0], target_width) < 10: raise ValueError(f'the aspect ratio is very extreme {new_size}')
image = torchvision.transforms.functional.resize(image, [new_size[1], new_size[0]],)
resized_img = torchvision.transforms.functional.pad(image, [0, 0, padding_width, padding_height], fill=[255,255,255])
return resized_img, attention_mask
def pad_to_max_num_crops(self, images, max_crops=5): """ images: B x 3 x H x W, B<=max_crops """ B, _, H, W = images.shape if B < max_crops: pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device) images = torch.cat([images, pad], dim=0) return images
def pad_mask_to_max_num_crops(self, masks, max_crops=5): B, H, W = masks.shape if B < max_crops: pad = torch.ones(max_crops - B, H, W, dtype=masks.dtype, device=masks.device) masks = torch.cat([masks, pad], dim=0) return masks
def preprocess( self, images: ImageInput, return_tensors: Optional[Union[str, TensorType]] = None, ): """ Args: images (`ImageInput`): Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`. """ images = make_list_of_images(images)
if not valid_images(images): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." )
# Basic settings. img_processor = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.5, 0.5, 0.5), (0.5, 0.5, 0.5) ), ]) dyhd_base_resolution = 448
# Dynamic HD base_resolution = dyhd_base_resolution images = [image.convert('RGB') for image in images] # cover 384 and 448 resolution mask_resolution = base_resolution // 14 elems, image_attention_masks = [], [] for im in images: elem, attention_mask = self.dynamic_preprocess(im, max_num=self.dynamic_hd, image_size=base_resolution, mask_size=mask_resolution) elems.append(elem) image_attention_masks.append(attention_mask) hd_images = [img_processor(im) for im in elems] 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] shapes = [[im.size(1), im.size(2)] for im in hd_images] mask_shapes = [[mask.size(0), mask.size(1)] for mask in image_attention_masks] global_attention_mask = [torch.ones((1, mask_resolution, mask_resolution)) for _ in hd_images] hd_images_reshape = [im.reshape(1, 3, h//base_resolution, base_resolution, w//base_resolution, base_resolution ).permute(0,2,4,1,3,5).reshape(-1, 3, base_resolution, base_resolution).contiguous() for im, (h, w) in zip(hd_images, shapes)] attention_masks_reshape = [mask.reshape(1, h//mask_resolution, mask_resolution, w//mask_resolution, mask_resolution ).permute(0,1,3,2,4).reshape(-1, mask_resolution, mask_resolution).contiguous() for mask, (h, w) in zip(image_attention_masks, mask_shapes)] downsample_attention_masks = [mask[:,0::2,0::2].reshape(1, h//mask_resolution, w//mask_resolution, mask_resolution//2+mask_resolution%2, mask_resolution//2+mask_resolution%2 ).permute(0,1,3,2,4) for mask, (h,w) in zip(attention_masks_reshape, mask_shapes)] downsample_attention_masks = [mask.reshape(mask.size(1)*mask.size(2), mask.size(3)*mask.size(4))for mask in downsample_attention_masks] num_img_tokens = [256 + 1 + int(mask.sum().item()) + int(mask[:,0].sum().item()) + 16 for mask in downsample_attention_masks]
hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)] hd_masks_reshape = [torch.cat([_global_mask] + [_mask], dim=0) for _global_mask, _mask in zip(global_attention_mask, attention_masks_reshape)] max_crops = max([img.size(0) for img in hd_images_reshape]) image_transformed = [self.pad_to_max_num_crops(im, max_crops) for im in hd_images_reshape] image_transformed = torch.stack(image_transformed, dim=0) mask_transformed = [self.pad_mask_to_max_num_crops(mask, max_crops) for mask in hd_masks_reshape] mask_transformed = torch.stack(mask_transformed, dim=0)
returned_input_image_embeds = image_transformed returned_image_sizes = torch.tensor(shapes, dtype=torch.long) returned_image_attention_mask = mask_transformed returned_num_img_tokens = num_img_tokens
data = { "input_image_embeds": returned_input_image_embeds, "image_sizes": returned_image_sizes, "image_attention_mask": returned_image_attention_mask, "num_img_tokens": returned_num_img_tokens, }
return BatchFeature(data=data, tensor_type=return_tensors)
AudioInput = Tuple[Union[np.ndarray, torch.Tensor], int]AudioInputs = List[AudioInput]
def speechlib_mel(sample_rate, n_fft, n_mels, fmin=None, fmax=None): """Create a Mel filter-bank the same as SpeechLib FbankFC.
Args: sample_rate (int): Sample rate in Hz. number > 0 [scalar] n_fft (int): FFT size. int > 0 [scalar] n_mel (int): Mel filter size. int > 0 [scalar] fmin (float): lowest frequency (in Hz). If None use 0.0. float >= 0 [scalar] fmax: highest frequency (in Hz). If None use sample_rate / 2. float >= 0 [scalar]
Returns out (numpy.ndarray): Mel transform matrix [shape=(n_mels, 1 + n_fft/2)] """
bank_width = int(n_fft // 2 + 1) if fmax is None: fmax = sample_rate / 2 if fmin is None: fmin = 0 assert fmin >= 0, "fmin cannot be negtive" assert fmin < fmax <= sample_rate / 2, "fmax must be between (fmin, samplerate / 2]"
def mel(f): return 1127.0 * np.log(1.0 + f / 700.0)
def bin2mel(fft_bin): return 1127.0 * np.log(1.0 + fft_bin * sample_rate / (n_fft * 700.0))
def f2bin(f): return int((f * n_fft / sample_rate) + 0.5)
# Spec 1: FFT bin range [f2bin(fmin) + 1, f2bin(fmax) - 1] klo = f2bin(fmin) + 1 khi = f2bin(fmax)
khi = max(khi, klo)
# Spec 2: SpeechLib uses trianges in Mel space mlo = mel(fmin) mhi = mel(fmax) m_centers = np.linspace(mlo, mhi, n_mels + 2) ms = (mhi - mlo) / (n_mels + 1)
matrix = np.zeros((n_mels, bank_width), dtype=np.float32) for m in range(0, n_mels): left = m_centers[m] center = m_centers[m + 1] right = m_centers[m + 2] for fft_bin in range(klo, khi): mbin = bin2mel(fft_bin) if left < mbin < right: matrix[m, fft_bin] = 1.0 - abs(center - mbin) / ms
return matrix
class Phi4MMAudioFeatureExtractor(SequenceFeatureExtractor): model_input_names = ["input_audio_embeds", "audio_embed_sizes", "audio_attention_mask"]
def __init__(self, audio_compression_rate, audio_downsample_rate, audio_feat_stride, **kwargs): feature_size = 80 sampling_rate = 16000 padding_value = 0.0 super().__init__(feature_size, sampling_rate, padding_value, **kwargs)
self.compression_rate = audio_compression_rate self.qformer_compression_rate = audio_downsample_rate self.feat_stride = audio_feat_stride
self._eightk_method = "fillzero" self._mel = speechlib_mel(16000, 512, 80, fmin=None, fmax=7690).T
self._hamming400 = np.hamming(400) # for 16k audio self._hamming200 = np.hamming(200) # for 8k audio
def duration_to_frames(self, duration): """duration in s, estimated frames""" frame_rate = 10
num_frames = duration * 1000 // frame_rate return num_frames
def __call__( self, audios: List[AudioInput], return_tensors: Optional[Union[str, TensorType]] = None, ): # Ref: https://github.com/huggingface/transformers/blob/v4.47.0/src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py#L161 returned_input_audio_embeds = [] returned_audio_embed_sizes = [] audio_frames_list = []
for audio_data, sample_rate in audios: audio_embeds = self._extract_features(audio_data, sample_rate) audio_frames = len(audio_embeds) * self.feat_stride audio_embed_size = self._compute_audio_embed_size(audio_frames)
returned_input_audio_embeds.append(torch.tensor(audio_embeds)) returned_audio_embed_sizes.append(torch.tensor(audio_embed_size).long()) audio_frames_list.append(audio_frames)
returned_input_audio_embeds = pad_sequence( returned_input_audio_embeds, batch_first=True ) returned_audio_embed_sizes = torch.stack(returned_audio_embed_sizes, dim=0) audio_frames = torch.tensor(audio_frames_list) returned_audio_attention_mask = torch.arange(0, audio_frames.max()).unsqueeze(0) < audio_frames.unsqueeze(1) if len(audios) > 1 else None
data = { "input_audio_embeds": returned_input_audio_embeds, "audio_embed_sizes": returned_audio_embed_sizes, } if returned_audio_attention_mask is not None: data["audio_attention_mask"] = returned_audio_attention_mask
return BatchFeature(data=data, tensor_type=return_tensors)
def _extract_spectrogram(self, wav, fs): """Extract spectrogram features from waveform. Args: wav (1D array): waveform of the input fs (int): sampling rate of the waveform, 16000 or 8000. If fs=8000, the waveform will be resampled to 16000Hz. Output: log_fbank (2D array): a TxD matrix of log Mel filterbank features. D=80, and T is the number of frames. """ if wav.ndim > 1: wav = np.squeeze(wav)
# by default, we extract the mean if stereo if len(wav.shape) == 2: wav = wav.mean(1)
# Resample to 16000 or 8000 if needed if fs > 16000: wav = scipy.signal.resample_poly(wav, 1, fs // 16000) fs = 16000 elif 8000 < fs < 16000: wav = scipy.signal.resample_poly(wav, 1, fs // 8000) fs = 8000 elif fs < 8000: raise RuntimeError(f"Unsupported sample rate {fs}")
if fs == 8000: if self._eightk_method == "resample": # Input audio is 8 kHz. Convert to 16 kHz before feature # extraction wav = scipy.signal.resample_poly(wav, 2, 1) fs = 16000 # Do nothing here for fillzero method elif fs != 16000: # Input audio is not a supported sample rate. raise RuntimeError(f"Input data using an unsupported sample rate: {fs}")
preemphasis = 0.97
if fs == 8000: n_fft = 256 win_length = 200 hop_length = 80 fft_window = self._hamming200 elif fs == 16000: n_fft = 512 win_length = 400 hop_length = 160 fft_window = self._hamming400
# Spec 1: SpeechLib cut remaining sample insufficient for a hop n_batch = (wav.shape[0] - win_length) // hop_length + 1 # Here we don't use stride_tricks since the input array may not satisfy # memory layout requirement and we need writeable output # Here we only use list of views before copy to desination # so it is more efficient than broadcasting y_frames = np.array( [wav[_stride : _stride + win_length] for _stride in range(0, hop_length * n_batch, hop_length)], dtype=np.float32, )
# Spec 2: SpeechLib applies preemphasis within each batch y_frames_prev = np.roll(y_frames, 1, axis=1) y_frames_prev[:, 0] = y_frames_prev[:, 1] y_frames = (y_frames - preemphasis * y_frames_prev) * 32768
S = np.fft.rfft(fft_window * y_frames, n=n_fft, axis=1).astype(np.complex64)
if fs == 8000: # Need to pad the output to look like 16 kHz data but with zeros in # the 4 to 8 kHz bins. frames, bins = S.shape padarray = np.zeros((frames, bins)) S = np.concatenate((S[:, 0:-1], padarray), axis=1) # Nyquist bin gets set to zero
spec = np.abs(S).astype(np.float32) return spec
def _extract_features(self, wav, fs): """Extract log filterbank features from waveform. Args: wav (1D array): waveform of the input fs (int): sampling rate of the waveform, 16000 or 8000. If fs=8000, the waveform will be resampled to 16000Hz. Output: log_fbank (2D array): a TxD matrix of log Mel filterbank features. D=80, and T is the number of frames. """ spec = self._extract_spectrogram(wav, fs) spec_power = spec**2
fbank_power = np.clip(spec_power.dot(self._mel), 1.0, None) log_fbank = np.log(fbank_power).astype(np.float32)
return log_fbank
def _compute_audio_embed_size(self, audio_frames): integer = audio_frames // self.compression_rate remainder = audio_frames % self.compression_rate
result = integer if remainder == 0 else integer + 1
integer = result // self.qformer_compression_rate remainder = result % self.qformer_compression_rate result = integer if remainder == 0 else integer + 1 # qformer compression
return result
class Phi4MMProcessor(ProcessorMixin): r""" Constructs a Phi4MM processor which raps an image processor, a audio processor, and a GPT tokenizer into a single processor.
[`Phi4MMProcessor`] offers all the functionalities of [`Phi4MMImageProcessor`] and [`GPT2Tokenizer`]. See the [`~Phi4MMProcessor.__call__`] and [`~Phi4MMProcessor.decode`] for more information.
Args: image_processor ([`Phi4MMImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`GPT2Tokenizer`], *optional*): The tokenizer is a required input. """
attributes = ["image_processor", "audio_processor", "tokenizer"] tokenizer_class = "GPT2TokenizerFast" image_processor_class = "AutoImageProcessor" # Phi4MMImageProcessor will be registered later audio_processor_class = "AutoFeatureExtractor" # Phi4MMAudioFeatureExtractor will be registered later
def __init__(self, image_processor, audio_processor, tokenizer): self.image_processor = image_processor self.audio_processor = audio_processor self.tokenizer = tokenizer
def __call__( self, text: Union[TextInput, List[TextInput]], images: Optional[ImageInput] = None, audios: Optional[AudioInputs] = None, padding: Union[bool, str, PaddingStrategy] = False, truncation: Optional[Union[bool, str, TruncationStrategy]] = None, max_length=None, return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH, ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forards the `text` and `kwargs` arguments to GPT2Tokenizer's [`~GPT2Tokenizer.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to Phi4MMImageProcessor's [`~Phi4MMImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring of the above two methods for more information.
Args: text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than `max_length` to `max_length`. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are:
- `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects.
Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. - **input_image_embeds** -- Pixel values to be fed to a model. - **image_sizes** -- List of tuples specifying the size of each image in `input_image_embeds`. - **image_attention_mask** -- List of attention masks for each image in `input_image_embeds`. - **input_audio_embeds** -- Audio embeddings to be fed to a model. - **audio_embed_sizes** -- List of integers specifying the size of each audio in `input_audio_embeds`. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model. """ image_inputs = self.image_processor(images, return_tensors=return_tensors) if images is not None else {} audio_inputs = self.audio_processor(audios, return_tensors=return_tensors) if audios is not None else {} inputs = self._convert_images_audios_text_to_inputs( image_inputs, audio_inputs, text, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors, )
# idenfity the input mode if len(image_inputs) > 0 and len(audio_inputs) > 0: input_mode = InputMode.VISION_SPEECH elif len(image_inputs) > 0: input_mode = InputMode.VISION elif len(audio_inputs) > 0: input_mode = InputMode.SPEECH else: input_mode = InputMode.LANGUAGE inputs["input_mode"] = torch.tensor([input_mode.value], dtype=torch.long)
return inputs
@property def special_image_token_id(self): return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
def get_special_image_token_id(self): return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
@property def chat_template(self): return self.tokenizer.chat_template
def _convert_images_audios_text_to_inputs( self, images, audios, text, padding=False, truncation=None, max_length=None, return_tensors=None ): # prepare image id to image input ids if len(images) > 0: input_image_embeds = images["input_image_embeds"] image_sizes = images["image_sizes"] image_attention_mask = images["image_attention_mask"] num_img_tokens = images['num_img_tokens'] else: input_image_embeds = torch.tensor([]) image_sizes = torch.tensor([]) image_attention_mask = torch.tensor([]) num_img_tokens = []
# prepare audio id to audio input ids if len(audios) > 0: input_audio_embeds = audios["input_audio_embeds"] audio_embed_sizes = audios["audio_embed_sizes"] audio_attention_mask = audios.get("audio_attention_mask", None) else: input_audio_embeds = torch.tensor([]) audio_embed_sizes = torch.tensor([]) audio_attention_mask = None
# Replace certain special tokens for compatibility # Ref: https://stackoverflow.com/questions/11475885/python-replace-regex if isinstance(text, str): text = [text] assert isinstance(text, list) processed_text = [re.sub(_COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN, _IMAGE_SPECIAL_TOKEN, t) for t in text] processed_text = [re.sub(_COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN, _AUDIO_SPECIAL_TOKEN, t) for t in processed_text]
input_ids_list = [self.tokenizer(t).input_ids for t in processed_text]
img_cnt, audio_cnt = 0, 0 # only needed for later assertion image_token_count_iter = iter(num_img_tokens) audio_embed_size_iter = iter(audio_embed_sizes.tolist()) new_input_ids_list = [] for input_ids in input_ids_list: i = 0 while i < len(input_ids): token_id = input_ids[i] if token_id == _AUDIO_SPECIAL_TOKEN_ID: token_count = next(audio_embed_size_iter) audio_cnt += 1 elif token_id == _IMAGE_SPECIAL_TOKEN_ID: token_count = next(image_token_count_iter) img_cnt += 1 else: i += 1 continue tokens = [token_id] * token_count input_ids = input_ids[:i] + tokens + input_ids[i + 1:] i += token_count input_ids = torch.tensor(input_ids, dtype=torch.long) new_input_ids_list.append(input_ids) lengths = torch.tensor([len(input_ids) for input_ids in new_input_ids_list]) max_len = lengths.max() input_ids = input_ids.new_full((len(new_input_ids_list), max_len), self.tokenizer.pad_token_id) # batched inference requires left padding for i in range(len(new_input_ids_list)): input_ids[i, max_len - len(new_input_ids_list[i]):] = new_input_ids_list[i]
# If the below assertion fails, it might be that input pure-text # messages contain image/audio special tokens literally # (<|endoftext10|>, <|endoftext11|>). assert ( img_cnt == len(num_img_tokens) ), ( f"Number of image tokens in prompt_token_ids ({img_cnt}) " f"does not match number of images ({len(num_img_tokens)})" ) assert ( audio_cnt == len(audio_embed_sizes) ), ( f"Number of audio tokens in prompt_token_ids ({audio_cnt}) " f"does not match number of audios ({len(audio_embed_sizes)})" )
# prepare attention mask seq_range = torch.arange(max_len - 1, -1, -1) attention_mask = seq_range.unsqueeze(0) < lengths.unsqueeze(1)
# prepare batch feature data = { "input_ids": input_ids, "input_image_embeds": input_image_embeds, "image_sizes": image_sizes, "image_attention_mask": image_attention_mask, "input_audio_embeds": input_audio_embeds, "audio_embed_sizes": audio_embed_sizes, "audio_attention_mask": audio_attention_mask, "attention_mask": attention_mask, }
return BatchFeature( data=data )
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama def decode(self, *args, **kwargs): """ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)
@property # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names audio_processor_input_names = self.audio_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names + audio_processor_input_names))
AutoImageProcessor.register("Phi4MMImageProcessor", Phi4MMImageProcessor)AutoFeatureExtractor.register("Phi4MMAudioFeatureExtractor", Phi4MMAudioFeatureExtractor)123456{ "auto_map": { "AutoProcessor": "processing_phi4mm.Phi4MMProcessor" }, "processor_class": "Phi4MMProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478"""finetune Phi-4-multimodal-instruct on an speech task
scipy==1.15.1peft==0.13.2backoff==2.2.1transformers==4.46.1accelerate==1.3.0"""
import argparseimport jsonimport osfrom pathlib import Path
import torchimport sacrebleufrom accelerate import Acceleratorfrom accelerate.utils import gather_objectfrom datasets import load_datasetfrom torch.utils.data import Datasetfrom tqdm import tqdmfrom transformers import ( AutoModelForCausalLM, AutoProcessor, BatchFeature, Trainer, TrainingArguments, StoppingCriteria, StoppingCriteriaList,)
INSTSRUCTION = { "en_zh-CN": "Translate the audio to Mandarin.", "en_id": "Translate the audio to Indonesian.", "en_sl": "Translate the audio to Slovenian.",}TOKENIZER = { "en_zh-CN": "zh", "en_ja": "ja-mecab",}ANSWER_SUFFIX = "<|end|><|endoftext|>"_IGNORE_INDEX = -100_TRAIN_SIZE = 50000_EVAL_SIZE = 200
class MultipleTokenBatchStoppingCriteria(StoppingCriteria): """Stopping criteria capable of receiving multiple stop-tokens and handling batched inputs."""
def __init__(self, stop_tokens: torch.LongTensor, batch_size: int = 1) -> None: """Initialize the multiple token batch stopping criteria.
Args: stop_tokens: Stop-tokens. batch_size: Batch size.
"""
self.stop_tokens = stop_tokens self.max_stop_tokens = stop_tokens.shape[-1] self.stop_tokens_idx = torch.zeros(batch_size, dtype=torch.long, device=stop_tokens.device)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: # Only gather the maximum number of inputs compatible with stop tokens # and checks whether generated inputs are equal to `stop_tokens` generated_inputs = torch.eq(input_ids[:, -self.max_stop_tokens :].unsqueeze(1), self.stop_tokens) equal_generated_inputs = torch.all(generated_inputs, dim=2)
# Mark the position where a stop token has been produced for each input in the batch, # but only if the corresponding entry is not already set sequence_idx = torch.any(equal_generated_inputs, dim=1) sequence_set_mask = self.stop_tokens_idx == 0 self.stop_tokens_idx[sequence_idx & sequence_set_mask] = input_ids.shape[-1]
return torch.all(self.stop_tokens_idx)
class CoVoSTDataset(Dataset): def __init__(self, processor, data_dir, split, lang="en_zh-CN", rank=0, world_size=1):
self.data = load_dataset("facebook/covost2", lang, data_dir=data_dir, split=split, trust_remote_code=True ) self.training = "train" in split self.processor = processor self.instruction = INSTSRUCTION[lang] if world_size > 1: self.data = self.data.shard(world_size, rank)
def __len__(self): return len(self.data)
def __getitem__(self, idx): """ {'client_id': '0013037a1d45cc33460806cc3f8ecee9d536c45639ba4cbbf1564f1c051f53ff3c9f89ef2f1bf04badf55b3a2e7654c086f903681a7b6299616cff6f67598eff', 'file': '{data_dir}/clips/common_voice_en_699711.mp3', 'audio': {'path': '{data_dir}/clips/common_voice_en_699711.mp3', 'array': array([-1.28056854e-09, -1.74622983e-09, -1.16415322e-10, ..., 3.92560651e-10, 6.62794264e-10, -3.89536581e-09]), 'sampling_rate': 16000}, 'sentence': '"She\'ll be all right."', 'translation': '她会没事的。', 'id': 'common_voice_en_699711'} """ data = self.data[idx] user_message = { 'role': 'user', 'content': '<|audio_1|>\n' + self.instruction, } prompt = self.processor.tokenizer.apply_chat_template( [user_message], tokenize=False, add_generation_prompt=True ) inputs = self.processor(text=prompt, audios=[(data["audio"]["array"], data["audio"]["sampling_rate"])], return_tensors='pt') answer = f"{data['translation']}{ANSWER_SUFFIX}" answer_ids = self.processor.tokenizer(answer, return_tensors='pt').input_ids if self.training: input_ids = torch.cat([inputs.input_ids, answer_ids], dim=1) labels = torch.full_like(input_ids, _IGNORE_INDEX) labels[:, -answer_ids.shape[1] :] = answer_ids else: input_ids = inputs.input_ids labels = answer_ids
return { 'input_ids': input_ids, 'labels': labels, 'input_audio_embeds': inputs.input_audio_embeds, 'audio_embed_sizes': inputs.audio_embed_sizes, }
def pad_sequence(sequences, padding_side='right', padding_value=0): """ Pad a list of sequences to the same length. sequences: list of tensors in [seq_len, *] shape """ assert padding_side in ['right', 'left'] max_size = sequences[0].size() trailing_dims = max_size[1:] max_len = max(len(seq) for seq in sequences) batch_size = len(sequences) output = sequences[0].new_full((batch_size, max_len) + trailing_dims, padding_value) for i, seq in enumerate(sequences): length = seq.size(0) if padding_side == 'right': output.data[i, :length] = seq else: output.data[i, -length:] = seq return output
def cat_with_pad(tensors, dim, padding_value=0): """ cat along dim, while pad to max for all other dims """ ndim = tensors[0].dim() assert all( t.dim() == ndim for t in tensors[1:] ), 'All tensors must have the same number of dimensions'
out_size = [max(t.shape[i] for t in tensors) for i in range(ndim)] out_size[dim] = sum(t.shape[dim] for t in tensors) output = tensors[0].new_full(out_size, padding_value)
index = 0 for t in tensors: # Create a slice list where every dimension except dim is full slice slices = [slice(0, t.shape[d]) for d in range(ndim)] # Update only the concat dimension slice slices[dim] = slice(index, index + t.shape[dim])
output[slices] = t index += t.shape[dim]
return output
def covost_collate_fn(batch): input_ids_list = [] labels_list = [] input_audio_embeds_list = [] audio_embed_sizes_list = [] audio_attention_mask_list = [] for inputs in batch: input_ids_list.append(inputs['input_ids'][0]) labels_list.append(inputs['labels'][0]) input_audio_embeds_list.append(inputs['input_audio_embeds']) audio_embed_sizes_list.append(inputs['audio_embed_sizes']) audio_attention_mask_list.append( inputs['input_audio_embeds'].new_full((inputs['input_audio_embeds'].size(1),), True, dtype=torch.bool) )
try: input_ids = pad_sequence(input_ids_list, padding_side='left', padding_value=0) labels = pad_sequence(labels_list, padding_side='left', padding_value=0) audio_attention_mask = ( pad_sequence(audio_attention_mask_list, padding_side='right', padding_value=False) if len(audio_attention_mask_list) > 1 else None ) except Exception as e: print(e) print(input_ids_list) print(labels_list) raise attention_mask = (input_ids != 0).long() input_audio_embeds = cat_with_pad(input_audio_embeds_list, dim=0) audio_embed_sizes = torch.cat(audio_embed_sizes_list)
return BatchFeature( { 'input_ids': input_ids, 'labels': labels, 'attention_mask': attention_mask, 'input_audio_embeds': input_audio_embeds, 'audio_embed_sizes': audio_embed_sizes, 'audio_attention_mask': audio_attention_mask, 'input_mode': 2, # speech mode } )
def create_model(model_name_or_path, use_flash_attention=False): model = AutoModelForCausalLM.from_pretrained( model_name_or_path, torch_dtype=torch.bfloat16 if use_flash_attention else torch.float32, _attn_implementation='flash_attention_2' if use_flash_attention else 'sdpa', trust_remote_code=True, ).to('cuda')
return model
@torch.no_grad()def evaluate( model, processor, eval_dataset, save_path=None, disable_tqdm=False, eval_batch_size=1): rank = int(os.environ.get('RANK', 0)) local_rank = int(os.environ.get('LOCAL_RANK', 0))
model.eval() all_generated_texts = [] all_labels = []
eval_dataloader = torch.utils.data.DataLoader( eval_dataset, batch_size=eval_batch_size, collate_fn=covost_collate_fn, shuffle=False, drop_last=False, num_workers=8, prefetch_factor=2, pin_memory=True, ) stop_tokens = ["<|end|>", processor.tokenizer.eos_token] stop_tokens_ids = processor.tokenizer(stop_tokens, add_special_tokens=False, padding="longest", return_tensors="pt")["input_ids"] stop_tokens_ids = stop_tokens_ids.to(f'cuda:{local_rank}')
for inputs in tqdm( eval_dataloader, disable=(rank != 0) or disable_tqdm, desc='running eval' ): stopping_criteria=StoppingCriteriaList([MultipleTokenBatchStoppingCriteria(stop_tokens_ids, batch_size=inputs.input_ids.size(0))]) inputs = inputs.to(f'cuda:{local_rank}') generated_ids = model.generate( **inputs, eos_token_id=processor.tokenizer.eos_token_id, max_new_tokens=64, stopping_criteria=stopping_criteria, )
stop_tokens_idx = stopping_criteria[0].stop_tokens_idx.reshape(inputs.input_ids.size(0), -1)[:, 0]
stop_tokens_idx = torch.where( stop_tokens_idx > 0, stop_tokens_idx - stop_tokens_ids.shape[-1], generated_ids.shape[-1], ) generated_text = [ processor.decode(_pred_ids[inputs["input_ids"].shape[1] : _stop_tokens_idx], skip_special_tokens=True, clean_up_tokenization_spaces=False) for _pred_ids, _stop_tokens_idx in zip(generated_ids, stop_tokens_idx) ] all_generated_texts.extend(generated_text) labels = [processor.decode(_label_ids[_label_ids != 0]).removesuffix(ANSWER_SUFFIX) for _label_ids in inputs["labels"]] all_labels.extend(labels)
all_generated_texts = gather_object(all_generated_texts) all_labels = gather_object(all_labels) if rank == 0: assert len(all_generated_texts) == len(all_labels) bleu = sacrebleu.corpus_bleu(all_generated_texts, [all_labels]) print(bleu) if save_path: with open(save_path, 'w') as f: save_dict = { 'all_generated_texts': all_generated_texts, 'all_labels': all_labels, 'score': bleu.score, } json.dump(save_dict, f)
return bleu.score return None
def main(): parser = argparse.ArgumentParser() parser.add_argument( '--model_name_or_path', type=str, default='microsoft/Phi-4-multimodal-instruct', help='Model name or path to load from', ) parser.add_argument( "--common_voice_dir", type=str, default="CommonVoice/EN", help="Unzipped Common Voice Audio dataset directory, refer to https://commonvoice.mozilla.org/en/datasets, version 4.0", ) parser.add_argument( "--lang", type=str, default="en_sl", help="Language pair for translation.", ) parser.add_argument('--use_flash_attention', action='store_true', help='Use Flash Attention') parser.add_argument('--output_dir', type=str, default='./output/', help='Output directory') parser.add_argument('--batch_size', type=int, default=128, help='Batch size') parser.add_argument( '--batch_size_per_gpu', type=int, default=32, help='Batch size per GPU (adjust this to fit in GPU memory)', ) parser.add_argument( '--num_train_epochs', type=int, default=1, help='Number of training epochs' ) parser.add_argument('--learning_rate', type=float, default=4.0e-5, help='Learning rate') parser.add_argument('--wd', type=float, default=0.01, help='Weight decay') parser.add_argument('--no-tqdm', dest='tqdm', action='store_false', help='Disable tqdm') args = parser.parse_args()
accelerator = Accelerator()
with accelerator.local_main_process_first(): processor = AutoProcessor.from_pretrained( args.model_name_or_path, trust_remote_code=True, ) model = create_model( args.model_name_or_path, use_flash_attention=args.use_flash_attention, )
model.set_lora_adapter('speech')
rank = int(os.environ.get('RANK', 0)) world_size = int(os.environ.get('WORLD_SIZE', 1))
eval_dataset = CoVoSTDataset(processor, data_dir=args.common_voice_dir, split=f'test[:{_EVAL_SIZE}]', lang=args.lang, rank=rank, world_size=world_size) train_dataset = CoVoSTDataset(processor, data_dir=args.common_voice_dir, split=f'train[:{_TRAIN_SIZE}]', lang=args.lang)
num_gpus = accelerator.num_processes print(f'training on {num_gpus} GPUs') assert ( args.batch_size % (num_gpus * args.batch_size_per_gpu) == 0 ), 'Batch size must be divisible by the number of GPUs' gradient_accumulation_steps = args.batch_size // (num_gpus * args.batch_size_per_gpu)
if args.use_flash_attention: fp16 = False bf16 = True else: fp16 = True bf16 = False
# hard coded training args training_args = TrainingArguments( num_train_epochs=args.num_train_epochs, per_device_train_batch_size=args.batch_size_per_gpu, gradient_checkpointing=True, gradient_checkpointing_kwargs={'use_reentrant': False}, gradient_accumulation_steps=gradient_accumulation_steps, optim='adamw_torch', adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-7, learning_rate=args.learning_rate, weight_decay=args.wd, max_grad_norm=1.0, lr_scheduler_type='linear', warmup_steps=50, logging_steps=10, output_dir=args.output_dir, save_strategy='no', save_total_limit=10, save_only_model=True, bf16=bf16, fp16=fp16, remove_unused_columns=False, report_to='none', deepspeed=None, disable_tqdm=not args.tqdm, dataloader_num_workers=4, ddp_find_unused_parameters=True, # for unused SigLIP layers )
# eval before fine-tuning out_path = Path(training_args.output_dir) out_path.mkdir(parents=True, exist_ok=True)
score = evaluate( model, processor, eval_dataset, save_path=out_path / 'eval_before.json', disable_tqdm=not args.tqdm, eval_batch_size=args.batch_size_per_gpu, ) if accelerator.is_main_process: print(f'BLEU Score before finetuning: {score}')
trainer = Trainer( model=model, args=training_args, data_collator=covost_collate_fn, train_dataset=train_dataset, )
trainer.train() trainer.save_model() if accelerator.is_main_process: processor.save_pretrained(training_args.output_dir) accelerator.wait_for_everyone()
# eval after fine-tuning (load saved checkpoint) # first try to clear GPU memory del model del trainer __import__('gc').collect() torch.cuda.empty_cache()
# reload the model for inference model = AutoModelForCausalLM.from_pretrained( training_args.output_dir, torch_dtype=torch.bfloat16 if args.use_flash_attention else torch.float32, trust_remote_code=True, _attn_implementation='flash_attention_2' if args.use_flash_attention else 'sdpa', ).to('cuda')
score = evaluate( model, processor, eval_dataset, save_path=out_path / 'eval_after.json', disable_tqdm=not args.tqdm, eval_batch_size=args.batch_size_per_gpu, ) if accelerator.is_main_process: print(f'BLEU Score after finetuning: {score}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556"""finetune Phi-4-multimodal-instruct on an image task
scipy==1.15.1peft==0.13.2backoff==2.2.1transformers==4.47.0accelerate==1.3.0"""
import argparseimport jsonimport osimport tempfileimport zipfilefrom pathlib import Path
import torchfrom accelerate import Acceleratorfrom accelerate.utils import gather_objectfrom datasets import load_datasetfrom huggingface_hub import hf_hub_downloadfrom PIL import Imagefrom torch.utils.data import Datasetfrom tqdm import tqdmfrom transformers import ( AutoModelForCausalLM, AutoProcessor, BatchFeature, Trainer, TrainingArguments,)
DEFAULT_INSTSRUCTION = "Answer with the option's letter from the given choices directly."_IGNORE_INDEX = -100_TRAIN_SIZE = 8000_EVAL_SIZE = 500_MAX_TRAINING_LENGTH = 8192
class PmcVqaTrainDataset(Dataset): def __init__(self, processor, data_size, instruction=DEFAULT_INSTSRUCTION): # Download the file file_path = hf_hub_download( repo_id='xmcmic/PMC-VQA', # repository name filename='images_2.zip', # file to download repo_type='dataset', # specify it's a dataset repo )
# file_path will be the local path where the file was downloaded print(f'File downloaded to: {file_path}')
# unzip to temp folder self.image_folder = Path(tempfile.mkdtemp()) with zipfile.ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(self.image_folder)
data_files = { 'train': 'https://huggingface.co/datasets/xmcmic/PMC-VQA/resolve/main/train_2.csv', } split = 'train' if data_size is None else f'train[:{data_size}]' self.annotations = load_dataset('xmcmic/PMC-VQA', data_files=data_files, split=split) self.processor = processor self.instruction = instruction
def __len__(self): return len(self.annotations)
def __getitem__(self, idx): """ {'index': 35, 'Figure_path': 'PMC8253797_Fig4_11.jpg', '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).', 'Question': ' What color is used to label the Golgi complexes in the image?', 'Choice A': ' A: Green ', 'Choice B': ' B: Red ', 'Choice C': ' C: Light blue ', 'Choice D': ' D: Yellow', 'Answer': 'B', 'split': 'train'} """ annotation = self.annotations[idx] image = Image.open(self.image_folder / 'figures' / annotation['Figure_path']) question = annotation['Question'] choices = [annotation[f'Choice {chr(ord("A") + i)}'] for i in range(4)] user_message = { 'role': 'user', 'content': '<|image_1|>' + '\n'.join([question] + choices + [self.instruction]), } prompt = self.processor.tokenizer.apply_chat_template( [user_message], tokenize=False, add_generation_prompt=True ) answer = f'{annotation["Answer"]}<|end|><|endoftext|>' inputs = self.processor(prompt, images=[image], return_tensors='pt')
answer_ids = self.processor.tokenizer(answer, return_tensors='pt').input_ids
input_ids = torch.cat([inputs.input_ids, answer_ids], dim=1) labels = torch.full_like(input_ids, _IGNORE_INDEX) labels[:, -answer_ids.shape[1] :] = answer_ids
if input_ids.size(1) > _MAX_TRAINING_LENGTH: input_ids = input_ids[:, :_MAX_TRAINING_LENGTH] labels = labels[:, :_MAX_TRAINING_LENGTH] if torch.all(labels == _IGNORE_INDEX).item(): # workaround to make sure loss compute won't fail labels[:, -1] = self.processor.tokenizer.eos_token_id
return { 'input_ids': input_ids, 'labels': labels, 'input_image_embeds': inputs.input_image_embeds, 'image_attention_mask': inputs.image_attention_mask, 'image_sizes': inputs.image_sizes, }
def __del__(self): __import__('shutil').rmtree(self.image_folder)
class PmcVqaEvalDataset(Dataset): def __init__( self, processor, data_size, instruction=DEFAULT_INSTSRUCTION, rank=0, world_size=1 ): # Download the file file_path = hf_hub_download( repo_id='xmcmic/PMC-VQA', # repository name filename='images_2.zip', # file to download repo_type='dataset', # specify it's a dataset repo )
# file_path will be the local path where the file was downloaded print(f'File downloaded to: {file_path}')
# unzip to temp folder self.image_folder = Path(tempfile.mkdtemp()) with zipfile.ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(self.image_folder)
data_files = { 'test': 'https://huggingface.co/datasets/xmcmic/PMC-VQA/resolve/main/test_2.csv', } split = 'test' if data_size is None else f'test[:{data_size}]' self.annotations = load_dataset( 'xmcmic/PMC-VQA', data_files=data_files, split=split ).shard(num_shards=world_size, index=rank) self.processor = processor self.instruction = instruction
def __len__(self): return len(self.annotations)
def __getitem__(self, idx): """ {'index': 62, 'Figure_path': 'PMC8253867_Fig2_41.jpg', 'Caption': 'CT pulmonary angiogram reveals encasement and displacement of the left anterior descending coronary artery ( blue arrows ).', 'Question': ' What is the name of the artery encased and displaced in the image? ', 'Choice A': ' A: Right Coronary Artery ', 'Choice B': ' B: Left Anterior Descending Coronary Artery ', 'Choice C': ' C: Circumflex Coronary Artery ', 'Choice D': ' D: Superior Mesenteric Artery ', 'Answer': 'B', 'split': 'test'} """ annotation = self.annotations[idx] image = Image.open(self.image_folder / 'figures' / annotation['Figure_path']) question = annotation['Question'] choices = [annotation[f'Choice {chr(ord("A") + i)}'] for i in range(4)] user_message = { 'role': 'user', 'content': '<|image_1|>' + '\n'.join([question] + choices + [self.instruction]), } prompt = self.processor.tokenizer.apply_chat_template( [user_message], tokenize=False, add_generation_prompt=True ) answer = annotation['Answer'] inputs = self.processor(prompt, images=[image], return_tensors='pt')
unique_id = f'{annotation["index"]:010d}' return { 'id': unique_id, 'input_ids': inputs.input_ids, 'input_image_embeds': inputs.input_image_embeds, 'image_attention_mask': inputs.image_attention_mask, 'image_sizes': inputs.image_sizes, 'answer': answer, }
def __del__(self): __import__('shutil').rmtree(self.image_folder)
def pad_sequence(sequences, padding_side='right', padding_value=0): """ Pad a list of sequences to the same length. sequences: list of tensors in [seq_len, *] shape """ assert padding_side in ['right', 'left'] max_size = sequences[0].size() trailing_dims = max_size[1:] max_len = max(len(seq) for seq in sequences) batch_size = len(sequences) output = sequences[0].new_full((batch_size, max_len) + trailing_dims, padding_value) for i, seq in enumerate(sequences): length = seq.size(0) if padding_side == 'right': output.data[i, :length] = seq else: output.data[i, -length:] = seq return output
def cat_with_pad(tensors, dim, padding_value=0): """ cat along dim, while pad to max for all other dims """ ndim = tensors[0].dim() assert all( t.dim() == ndim for t in tensors[1:] ), 'All tensors must have the same number of dimensions'
out_size = [max(t.shape[i] for t in tensors) for i in range(ndim)] out_size[dim] = sum(t.shape[dim] for t in tensors) output = tensors[0].new_full(out_size, padding_value)
index = 0 for t in tensors: # Create a slice list where every dimension except dim is full slice slices = [slice(0, t.shape[d]) for d in range(ndim)] # Update only the concat dimension slice slices[dim] = slice(index, index + t.shape[dim])
output[slices] = t index += t.shape[dim]
return output
def pmc_vqa_collate_fn(batch): input_ids_list = [] labels_list = [] input_image_embeds_list = [] image_attention_mask_list = [] image_sizes_list = [] for inputs in batch: input_ids_list.append(inputs['input_ids'][0]) labels_list.append(inputs['labels'][0]) input_image_embeds_list.append(inputs['input_image_embeds']) image_attention_mask_list.append(inputs['image_attention_mask']) image_sizes_list.append(inputs['image_sizes'])
input_ids = pad_sequence(input_ids_list, padding_side='right', padding_value=0) labels = pad_sequence(labels_list, padding_side='right', padding_value=0) attention_mask = (input_ids != 0).long() input_image_embeds = cat_with_pad(input_image_embeds_list, dim=0) image_attention_mask = cat_with_pad(image_attention_mask_list, dim=0) image_sizes = torch.cat(image_sizes_list)
return BatchFeature( { 'input_ids': input_ids, 'labels': labels, 'attention_mask': attention_mask, 'input_image_embeds': input_image_embeds, 'image_attention_mask': image_attention_mask, 'image_sizes': image_sizes, 'input_mode': 1, # vision mode } )
def pmc_vqa_eval_collate_fn(batch): input_ids_list = [] input_image_embeds_list = [] image_attention_mask_list = [] image_sizes_list = [] all_unique_ids = [] all_answers = [] for inputs in batch: input_ids_list.append(inputs['input_ids'][0]) input_image_embeds_list.append(inputs['input_image_embeds']) image_attention_mask_list.append(inputs['image_attention_mask']) image_sizes_list.append(inputs['image_sizes']) all_unique_ids.append(inputs['id']) all_answers.append(inputs['answer'])
input_ids = pad_sequence(input_ids_list, padding_side='left', padding_value=0) attention_mask = (input_ids != 0).long() input_image_embeds = cat_with_pad(input_image_embeds_list, dim=0) image_attention_mask = cat_with_pad(image_attention_mask_list, dim=0) image_sizes = torch.cat(image_sizes_list)
return ( all_unique_ids, all_answers, BatchFeature( { 'input_ids': input_ids, 'attention_mask': attention_mask, 'input_image_embeds': input_image_embeds, 'image_attention_mask': image_attention_mask, 'image_sizes': image_sizes, 'input_mode': 1, # vision mode } ), )
def create_model(model_name_or_path, use_flash_attention=False): model = AutoModelForCausalLM.from_pretrained( model_name_or_path, torch_dtype=torch.bfloat16 if use_flash_attention else torch.float32, _attn_implementation='flash_attention_2' if use_flash_attention else 'sdpa', trust_remote_code=True, ).to('cuda') # remove parameters irrelevant to vision tasks del model.model.embed_tokens_extend.audio_embed # remove audio encoder for layer in model.model.layers: # remove audio lora del layer.mlp.down_proj.lora_A.speech del layer.mlp.down_proj.lora_B.speech del layer.mlp.gate_up_proj.lora_A.speech del layer.mlp.gate_up_proj.lora_B.speech del layer.self_attn.o_proj.lora_A.speech del layer.self_attn.o_proj.lora_B.speech del layer.self_attn.qkv_proj.lora_A.speech del layer.self_attn.qkv_proj.lora_B.speech
# TODO remove unused vision layers?
return model
@torch.no_grad()def evaluate( model, processor, eval_dataset, save_path=None, disable_tqdm=False, eval_batch_size=1): rank = int(os.environ.get('RANK', 0)) local_rank = int(os.environ.get('LOCAL_RANK', 0))
model.eval() all_answers = [] all_generated_texts = []
eval_dataloader = torch.utils.data.DataLoader( eval_dataset, batch_size=eval_batch_size, collate_fn=pmc_vqa_eval_collate_fn, shuffle=False, drop_last=False, num_workers=4, prefetch_factor=2, pin_memory=True, ) for ids, answers, inputs in tqdm( eval_dataloader, disable=(rank != 0) or disable_tqdm, desc='running eval' ): all_answers.extend({'id': i, 'answer': a.strip().lower()} for i, a in zip(ids, answers))
inputs = inputs.to(f'cuda:{local_rank}') generated_ids = model.generate( **inputs, eos_token_id=processor.tokenizer.eos_token_id, max_new_tokens=64 )
input_len = inputs.input_ids.size(1) generated_texts = processor.batch_decode( generated_ids[:, input_len:], skip_special_tokens=True, clean_up_tokenization_spaces=False, ) all_generated_texts.extend( {'id': i, 'generated_text': g.strip().lower()} for i, g in zip(ids, generated_texts) )
# gather outputs from all ranks all_answers = gather_object(all_answers) all_generated_texts = gather_object(all_generated_texts)
if rank == 0: assert len(all_answers) == len(all_generated_texts) acc = sum( a['answer'] == g['generated_text'] for a, g in zip(all_answers, all_generated_texts) ) / len(all_answers) if save_path: with open(save_path, 'w') as f: save_dict = { 'answers_unique': all_answers, 'generated_texts_unique': all_generated_texts, 'accuracy': acc, } json.dump(save_dict, f)
return acc return None
def main(): parser = argparse.ArgumentParser() parser.add_argument( '--model_name_or_path', type=str, default='microsoft/Phi-4-multimodal-instruct', help='Model name or path to load from', ) parser.add_argument('--use_flash_attention', action='store_true', help='Use Flash Attention') parser.add_argument('--output_dir', type=str, default='./output/', help='Output directory') parser.add_argument('--batch_size', type=int, default=16, help='Batch size') parser.add_argument( '--batch_size_per_gpu', type=int, default=1, help='Batch size per GPU (adjust this to fit in GPU memory)', ) parser.add_argument( '--dynamic_hd', type=int, default=36, help='Number of maximum image crops', ) parser.add_argument( '--num_train_epochs', type=int, default=1, help='Number of training epochs' ) parser.add_argument('--learning_rate', type=float, default=4.0e-5, help='Learning rate') parser.add_argument('--wd', type=float, default=0.01, help='Weight decay') parser.add_argument('--no_tqdm', dest='tqdm', action='store_false', help='Disable tqdm') parser.add_argument('--full_run', action='store_true', help='Run the full training and eval') args = parser.parse_args()
accelerator = Accelerator()
with accelerator.local_main_process_first(): processor = AutoProcessor.from_pretrained( args.model_name_or_path, trust_remote_code=True, dynamic_hd=args.dynamic_hd, ) model = create_model( args.model_name_or_path, use_flash_attention=args.use_flash_attention, ) # tune vision encoder and lora model.set_lora_adapter('vision') for param in model.model.embed_tokens_extend.image_embed.parameters(): param.requires_grad = True
rank = int(os.environ.get('RANK', 0)) world_size = int(os.environ.get('WORLD_SIZE', 1))
train_dataset = PmcVqaTrainDataset(processor, data_size=None if args.full_run else _TRAIN_SIZE) eval_dataset = PmcVqaEvalDataset( processor, data_size=None if args.full_run else _EVAL_SIZE, rank=rank, world_size=world_size, )
num_gpus = accelerator.num_processes print(f'training on {num_gpus} GPUs') assert ( args.batch_size % (num_gpus * args.batch_size_per_gpu) == 0 ), 'Batch size must be divisible by the number of GPUs' gradient_accumulation_steps = args.batch_size // (num_gpus * args.batch_size_per_gpu)
if args.use_flash_attention: fp16 = False bf16 = True else: fp16 = True bf16 = False
# hard coded training args training_args = TrainingArguments( num_train_epochs=args.num_train_epochs, per_device_train_batch_size=args.batch_size_per_gpu, gradient_checkpointing=True, gradient_checkpointing_kwargs={'use_reentrant': False}, gradient_accumulation_steps=gradient_accumulation_steps, optim='adamw_torch', adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-7, learning_rate=args.learning_rate, weight_decay=args.wd, max_grad_norm=1.0, lr_scheduler_type='linear', warmup_steps=50, logging_steps=10, output_dir=args.output_dir, save_strategy='no', save_total_limit=10, save_only_model=True, bf16=bf16, fp16=fp16, remove_unused_columns=False, report_to='none', deepspeed=None, disable_tqdm=not args.tqdm, dataloader_num_workers=4, ddp_find_unused_parameters=True, # for unused SigLIP layers )
# eval before fine-tuning out_path = Path(training_args.output_dir) out_path.mkdir(parents=True, exist_ok=True)
acc = evaluate( model, processor, eval_dataset, save_path=out_path / 'eval_before.json', disable_tqdm=not args.tqdm, eval_batch_size=args.batch_size_per_gpu, ) if accelerator.is_main_process: print(f'Accuracy before finetuning: {acc}')
trainer = Trainer( model=model, args=training_args, data_collator=pmc_vqa_collate_fn, train_dataset=train_dataset, ) trainer.train() trainer.save_model() accelerator.wait_for_everyone()
# eval after fine-tuning (load saved checkpoint) # first try to clear GPU memory del model del trainer __import__('gc').collect() torch.cuda.empty_cache()
# reload the model for inference model = AutoModelForCausalLM.from_pretrained( training_args.output_dir, torch_dtype=torch.bfloat16 if args.use_flash_attention else torch.float32, trust_remote_code=True, _attn_implementation='flash_attention_2' if args.use_flash_attention else 'sdpa', ).to('cuda')
acc = evaluate( model, processor, eval_dataset, save_path=out_path / 'eval_after.json', disable_tqdm=not args.tqdm, eval_batch_size=args.batch_size_per_gpu, ) if accelerator.is_main_process: print(f'Accuracy after finetuning: {acc}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243import osimport requestsimport torchfrom PIL import Imageimport soundfilefrom transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
model_path = './'
kwargs = {}kwargs['torch_dtype'] = torch.bfloat16
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)print(processor.tokenizer)
model = AutoModelForCausalLM.from_pretrained( model_path, trust_remote_code=True, torch_dtype='auto', _attn_implementation='flash_attention_2',).cuda()print("model.config._attn_implementation:", model.config._attn_implementation)
generation_config = GenerationConfig.from_pretrained(model_path, 'generation_config.json')
user_prompt = '<|user|>'assistant_prompt = '<|assistant|>'prompt_suffix = '<|end|>' #################################################### text-only ####################################################prompt = f'{user_prompt}what is the answer for 1+1? Explain it.{prompt_suffix}{assistant_prompt}'print(f'>>> Prompt\n{prompt}')inputs = processor(prompt, images=None, return_tensors='pt').to('cuda:0')
generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(f'>>> Response\n{response}')
#################################################### vision (single-turn) ##################################################### single-image promptprompt = f'{user_prompt}<|image_1|>What is shown in this image?{prompt_suffix}{assistant_prompt}'url = 'https://www.ilankelman.org/stopsigns/australia.jpg'print(f'>>> Prompt\n{prompt}')image = Image.open(requests.get(url, stream=True).raw)inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')
#################################################### vision (multi-turn) ##################################################### chat templatechat = [ {'role': 'user', 'content': f'<|image_1|>What is shown in this image?'}, { 'role': 'assistant', '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.", }, {'role': 'user', 'content': 'What is so special about this image'},]url = 'https://www.ilankelman.org/stopsigns/australia.jpg'image = Image.open(requests.get(url, stream=True).raw)prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)# 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.if prompt.endswith('<|endoftext|>'): prompt = prompt.rstrip('<|endoftext|>')
print(f'>>> Prompt\n{prompt}')
inputs = processor(prompt, [image], return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')
########################### vision (multi-frame) ################################images = []placeholder = ''for i in range(1, 5): url = f'https://image.slidesharecdn.com/azureintroduction-191206101932/75/Introduction-to-Microsoft-Azure-Cloud-{i}-2048.jpg' images.append(Image.open(requests.get(url, stream=True).raw)) placeholder += f'<|image_{i}|>'
messages = [ {'role': 'user', 'content': placeholder + 'Summarize the deck of slides.'},]
prompt = processor.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True)
print(f'>>> Prompt\n{prompt}')
inputs = processor(prompt, images, return_tensors='pt').to('cuda:0')
generation_args = { 'max_new_tokens': 1000, 'temperature': 0.0, 'do_sample': False,}
generate_ids = model.generate( **inputs, **generation_args, generation_config=generation_config,)
# remove input tokensgenerate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(response)
# NOTE: Please prepare the audio file 'examples/what_is_the_traffic_sign_in_the_image.wav'# and audio file 'examples/what_is_shown_in_this_image.wav' before running the following code# 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".# 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".
AUDIO_FILE_1 = 'examples/what_is_the_traffic_sign_in_the_image.wav'AUDIO_FILE_2 = 'examples/what_is_shown_in_this_image.wav'
if not os.path.exists(AUDIO_FILE_1): raise FileNotFoundError(f'Please prepare the audio file {AUDIO_FILE_1} before running the following code.')########################## vision-speech ################################prompt = f'{user_prompt}<|image_1|><|audio_1|>{prompt_suffix}{assistant_prompt}'url = 'https://www.ilankelman.org/stopsigns/australia.jpg'print(f'>>> Prompt\n{prompt}')image = Image.open(requests.get(url, stream=True).raw)audio = soundfile.read(AUDIO_FILE_1)inputs = processor(text=prompt, images=[image], audios=[audio], return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')
########################## speech only ################################speech_prompt = "Based on the attached audio, generate a comprehensive text transcription of the spoken content."prompt = f'{user_prompt}<|audio_1|>{speech_prompt}{prompt_suffix}{assistant_prompt}'
print(f'>>> Prompt\n{prompt}')audio = soundfile.read(AUDIO_FILE_1)inputs = processor(text=prompt, audios=[audio], return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')
if not os.path.exists(AUDIO_FILE_2): raise FileNotFoundError(f'Please prepare the audio file {AUDIO_FILE_2} before running the following code.')########################### speech only (multi-turn) ################################audio_1 = soundfile.read(AUDIO_FILE_2)audio_2 = soundfile.read(AUDIO_FILE_1)chat = [ {'role': 'user', 'content': f'<|audio_1|>Based on the attached audio, generate a comprehensive text transcription of the spoken content.'}, { 'role': 'assistant', 'content': "What is shown in this image.", }, {'role': 'user', 'content': f'<|audio_2|>Based on the attached audio, generate a comprehensive text transcription of the spoken content.'},]prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)# 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.if prompt.endswith('<|endoftext|>'): prompt = prompt.rstrip('<|endoftext|>')
print(f'>>> Prompt\n{prompt}')
inputs = processor(text=prompt, audios=[audio_1, audio_2], return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')
#################################################### vision-speech (multi-turn) ##################################################### chat templateaudio_1 = soundfile.read(AUDIO_FILE_2)audio_2 = soundfile.read(AUDIO_FILE_1)chat = [ {'role': 'user', 'content': f'<|image_1|><|audio_1|>'}, { 'role': 'assistant', '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.", }, {'role': 'user', 'content': f'<|audio_2|>'},]url = 'https://www.ilankelman.org/stopsigns/australia.jpg'image = Image.open(requests.get(url, stream=True).raw)prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)# 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.if prompt.endswith('<|endoftext|>'): prompt = prompt.rstrip('<|endoftext|>')
print(f'>>> Prompt\n{prompt}')
inputs = processor(text=prompt, images=[image], audios=[audio_1, audio_2], return_tensors='pt').to('cuda:0')generate_ids = model.generate( **inputs, max_new_tokens=1000, generation_config=generation_config,)generate_ids = generate_ids[:, inputs['input_ids'].shape[1] :]response = processor.batch_decode( generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]print(f'>>> Response\n{response}')123456789101112131415161718192021222324{ "bos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": "<|endoftext|>", "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}1234567891011121314151617181920212223{ "auto_mapping": null, "base_model_name_or_path": "TBA", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "lora_alpha": 640, "lora_dropout": 0.01, "modules_to_save": [], "peft_type": "LORA", "r": 320, "revision": null, "target_modules": [ "qkv_proj", "o_proj", "gate_up_proj", "down_proj" ], "task_type": "CAUSAL_LM"}123456789101112{ "<|/tool_call|>": 200026, "<|/tool|>": 200024, "<|assistant|>": 200019, "<|end|>": 200020, "<|system|>": 200022, "<|tag|>": 200028, "<|tool_call|>": 200025, "<|tool_response|>": 200027, "<|tool|>": 200023, "<|user|>": 200021}123456789101112131415161718192021222324{ "bos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": "<|endoftext|>", "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{ "add_prefix_space": false, "added_tokens_decoder": { "200010": { "content": "<|endoftext10|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200011": { "content": "<|endoftext11|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "199999": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200018": { "content": "<|endofprompt|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200019": { "content": "<|assistant|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200020": { "content": "<|end|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200021": { "content": "<|user|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200022": { "content": "<|system|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200023": { "content": "<|tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200024": { "content": "<|/tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200025": { "content": "<|tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200026": { "content": "<|/tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200027": { "content": "<|tool_response|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200028": { "content": "<|tag|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true } }, "bos_token": "<|endoftext|>", "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 %}", "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "model_max_length": 128000, "pad_token": "<|endoftext|>", "tokenizer_class": "GPT2TokenizerFast", "unk_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{ "add_prefix_space": false, "added_tokens_decoder": { "200010": { "content": "<|endoftext10|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200011": { "content": "<|endoftext11|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "199999": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200018": { "content": "<|endofprompt|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200019": { "content": "<|assistant|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200020": { "content": "<|end|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200021": { "content": "<|user|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200022": { "content": "<|system|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200023": { "content": "<|tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200024": { "content": "<|/tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200025": { "content": "<|tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200026": { "content": "<|/tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200027": { "content": "<|tool_response|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200028": { "content": "<|tag|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true } }, "bos_token": "<|endoftext|>", "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 %}", "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "model_max_length": 131072, "pad_token": "<|endoftext|>", "tokenizer_class": "GPT2TokenizerFast", "unk_token": "<|endoftext|>"}1234567891011121314151617181920212223{ "auto_mapping": null, "base_model_name_or_path": "TBA", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "lora_alpha": 512, "lora_dropout": 0.0, "modules_to_save": [], "peft_type": "LORA", "r": 256, "revision": null, "target_modules": [ "qkv_proj", "o_proj", "gate_up_proj", "down_proj" ], "task_type": "CAUSAL_LM"}123456789101112{ "<|/tool_call|>": 200026, "<|/tool|>": 200024, "<|assistant|>": 200019, "<|end|>": 200020, "<|system|>": 200022, "<|tag|>": 200028, "<|tool_call|>": 200025, "<|tool_response|>": 200027, "<|tool|>": 200023, "<|user|>": 200021}123456789101112131415161718192021222324{ "bos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": "<|endoftext|>", "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{ "add_prefix_space": false, "added_tokens_decoder": { "200010": { "content": "<|endoftext10|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200011": { "content": "<|endoftext11|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "199999": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200018": { "content": "<|endofprompt|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "200019": { "content": "<|assistant|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200020": { "content": "<|end|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200021": { "content": "<|user|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200022": { "content": "<|system|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "200023": { "content": "<|tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200024": { "content": "<|/tool|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200025": { "content": "<|tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200026": { "content": "<|/tool_call|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200027": { "content": "<|tool_response|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "200028": { "content": "<|tag|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true } }, "bos_token": "<|endoftext|>", "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 %}", "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "model_max_length": 128000, "pad_token": "<|endoftext|>", "tokenizer_class": "GPT2TokenizerFast", "unk_token": "<|endoftext|>"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717# coding=utf-8# Copyright 2024 The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Siglip model configuration"""
import osfrom typing import Union
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
SIGLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = { "google/siglip-base-patch16-224": "https://huggingface.co/google/siglip-base-patch16-224/resolve/main/config.json",}
class SiglipTextConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`SiglipTextModel`]. It is used to instantiate a Siglip text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the text encoder of the Siglip [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 32000): Vocabulary size of the Siglip text model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`SiglipModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. max_position_embeddings (`int`, *optional*, defaults to 64): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported. layer_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the layer normalization layers. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. pad_token_id (`int`, *optional*, defaults to 1): The id of the padding token in the vocabulary. bos_token_id (`int`, *optional*, defaults to 49406): The id of the beginning-of-sequence token in the vocabulary. eos_token_id (`int`, *optional*, defaults to 49407): The id of the end-of-sequence token in the vocabulary. Example: ```python >>> from transformers import SiglipTextConfig, SiglipTextModel >>> # Initializing a SiglipTextConfig with google/siglip-base-patch16-224 style configuration >>> configuration = SiglipTextConfig() >>> # Initializing a SiglipTextModel (with random weights) from the google/siglip-base-patch16-224 style configuration >>> model = SiglipTextModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "siglip_text_model"
def __init__( self, vocab_size=32000, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, max_position_embeddings=64, hidden_act="gelu_pytorch_tanh", layer_norm_eps=1e-6, attention_dropout=0.0, # This differs from `CLIPTokenizer`'s default and from openai/siglip # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538 pad_token_id=1, bos_token_id=49406, eos_token_id=49407, _flash_attn_2_enabled=True, **kwargs, ): super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.max_position_embeddings = max_position_embeddings self.layer_norm_eps = layer_norm_eps self.hidden_act = hidden_act self.attention_dropout = attention_dropout self._flash_attn_2_enabled = _flash_attn_2_enabled
@classmethod def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": cls._set_token_in_kwargs(kwargs)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
# get the text config dict if we are loading from SiglipConfig if config_dict.get("model_type") == "siglip": config_dict = config_dict["text_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." )
return cls.from_dict(config_dict, **kwargs)
class SiglipVisionConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. num_channels (`int`, *optional*, defaults to 3): Number of channels in the input images. image_size (`int`, *optional*, defaults to 224): The size (resolution) of each image. patch_size (`int`, *optional*, defaults to 16): The size (resolution) of each patch. hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported. layer_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the layer normalization layers. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. Example: ```python >>> from transformers import SiglipVisionConfig, SiglipVisionModel >>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration >>> configuration = SiglipVisionConfig() >>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration >>> model = SiglipVisionModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "siglip_vision_model"
def __init__( self, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, num_channels=3, image_size=224, patch_size=16, hidden_act="gelu_pytorch_tanh", layer_norm_eps=1e-6, attention_dropout=0.0, _flash_attn_2_enabled=True, **kwargs, ): super().__init__(**kwargs)
self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_channels = num_channels self.patch_size = patch_size self.image_size = image_size self.attention_dropout = attention_dropout self.layer_norm_eps = layer_norm_eps self.hidden_act = hidden_act self._flash_attn_2_enabled = _flash_attn_2_enabled
@classmethod def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": cls._set_token_in_kwargs(kwargs)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
# get the vision config dict if we are loading from SiglipConfig if config_dict.get("model_type") == "siglip": config_dict = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." )
return cls.from_dict(config_dict, **kwargs)
class SiglipConfig(PretrainedConfig): r""" [`SiglipConfig`] is the configuration class to store the configuration of a [`SiglipModel`]. It is used to instantiate a Siglip model according to the specified arguments, defining the text model and vision model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the Siglip [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: text_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`SiglipTextConfig`]. vision_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`SiglipVisionConfig`]. kwargs (*optional*): Dictionary of keyword arguments. Example: ```python >>> from transformers import SiglipConfig, SiglipModel >>> # Initializing a SiglipConfig with google/siglip-base-patch16-224 style configuration >>> configuration = SiglipConfig() >>> # Initializing a SiglipModel (with random weights) from the google/siglip-base-patch16-224 style configuration >>> model = SiglipModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config >>> # We can also initialize a SiglipConfig from a SiglipTextConfig and a SiglipVisionConfig >>> from transformers import SiglipTextConfig, SiglipVisionConfig >>> # Initializing a SiglipText and SiglipVision configuration >>> config_text = SiglipTextConfig() >>> config_vision = SiglipVisionConfig() >>> config = SiglipConfig.from_text_vision_configs(config_text, config_vision) ```"""
model_type = "siglip"
def __init__(self, text_config=None, vision_config=None, **kwargs): super().__init__(**kwargs)
if text_config is None: text_config = {} logger.info("`text_config` is `None`. Initializing the `SiglipTextConfig` with default values.")
if vision_config is None: vision_config = {} logger.info("`vision_config` is `None`. initializing the `SiglipVisionConfig` with default values.")
self.text_config = SiglipTextConfig(**text_config) self.vision_config = SiglipVisionConfig(**vision_config)
self.initializer_factor = 1.0
@classmethod def from_text_vision_configs(cls, text_config: SiglipTextConfig, vision_config: SiglipVisionConfig, **kwargs): r""" Instantiate a [`SiglipConfig`] (or a derived class) from siglip text model configuration and siglip vision model configuration. Returns: [`SiglipConfig`]: An instance of a configuration object """
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
# coding=utf-8# Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" PyTorch Siglip model."""
import mathimport warningsfrom dataclasses import dataclassfrom typing import Any, Optional, Tuple, Union
import numpy as npimport torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn.init import _calculate_fan_in_and_fan_out
from transformers.activations import ACT2FNfrom transformers.modeling_attn_mask_utils import _prepare_4d_attention_maskfrom transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPoolingfrom transformers.modeling_utils import PreTrainedModelfrom transformers.utils import ( ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, logging, replace_return_docstrings,)
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [ "google/siglip-base-patch16-224", # See all SigLIP models at https://huggingface.co/models?filter=siglip]
if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
# Copied from transformers.models.llama.modeling_llama._get_unpad_datadef _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, )
def _trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf def norm_cdf(x): # Computes standard normal cumulative distribution function return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
if (mean < a - 2 * std) or (mean > b + 2 * std): warnings.warn( "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.", stacklevel=2, )
# Values are generated by using a truncated uniform distribution and # then using the inverse CDF for the normal distribution. # Get upper and lower cdf values l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std)
# Uniformly fill tensor with values from [l, u], then translate to # [2l-1, 2u-1]. tensor.uniform_(2 * l - 1, 2 * u - 1)
# Use inverse cdf transform for normal distribution to get truncated # standard normal if tensor.dtype in [torch.float16, torch.bfloat16]: # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu og_dtype = tensor.dtype tensor = tensor.to(torch.float32) tensor.erfinv_() tensor = tensor.to(og_dtype) else: tensor.erfinv_()
# Transform to proper mean, std tensor.mul_(std * math.sqrt(2.0)) tensor.add_(mean)
# Clamp to ensure it's in the proper range if tensor.dtype == torch.float16: # The `clamp_` op is not (yet?) defined in float16+cpu tensor = tensor.to(torch.float32) tensor.clamp_(min=a, max=b) tensor = tensor.to(torch.float16) else: tensor.clamp_(min=a, max=b)
def trunc_normal_tf_( tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0) -> torch.Tensor: """Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values works best when :math:`a \\leq \text{mean} \\leq b`. NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0 and the result is subsquently scaled and shifted by the mean and std args. Args: tensor: an n-dimensional `torch.Tensor` mean: the mean of the normal distribution std: the standard deviation of the normal distribution a: the minimum cutoff value b: the maximum cutoff value """ with torch.no_grad(): _trunc_normal_(tensor, 0, 1.0, a, b) tensor.mul_(std).add_(mean)
def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"): fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) if mode == "fan_in": denom = fan_in elif mode == "fan_out": denom = fan_out elif mode == "fan_avg": denom = (fan_in + fan_out) / 2
variance = scale / denom
if distribution == "truncated_normal": # constant is stddev of standard normal truncated to (-2, 2) trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978) elif distribution == "normal": with torch.no_grad(): tensor.normal_(std=math.sqrt(variance)) elif distribution == "uniform": bound = math.sqrt(3 * variance) with torch.no_grad(): tensor.uniform_(-bound, bound) else: raise ValueError(f"invalid distribution {distribution}")
def lecun_normal_(tensor): variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
def default_flax_embed_init(tensor): variance_scaling_(tensor, mode="fan_in", distribution="normal")
@dataclass# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglipclass SiglipVisionModelOutput(ModelOutput): """ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states. Args: image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): The image embeddings obtained by applying the projection layer to the pooler_output. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """
image_embeds: Optional[torch.FloatTensor] = None last_hidden_state: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglipclass SiglipTextModelOutput(ModelOutput): """ Base class for text model's outputs that also contains a pooling of the last hidden states. Args: text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): The text embeddings obtained by applying the projection layer to the pooler_output. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """
text_embeds: Optional[torch.FloatTensor] = None last_hidden_state: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglipclass SiglipOutput(ModelOutput): """ Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): Contrastive loss for image-text similarity. logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`): The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text similarity scores. logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`): The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image similarity scores. text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`]. image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`]. text_model_output(`BaseModelOutputWithPooling`): The output of the [`SiglipTextModel`]. vision_model_output(`BaseModelOutputWithPooling`): The output of the [`SiglipVisionModel`]. """
loss: Optional[torch.FloatTensor] = None logits_per_image: torch.FloatTensor = None logits_per_text: torch.FloatTensor = None text_embeds: torch.FloatTensor = None image_embeds: torch.FloatTensor = None text_model_output: BaseModelOutputWithPooling = None vision_model_output: BaseModelOutputWithPooling = None
def to_tuple(self) -> Tuple[Any]: return tuple( self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple() for k in self.keys() )
class SiglipVisionEmbeddings(nn.Module): def __init__(self, config: SiglipVisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size
self.patch_embedding = nn.Conv2d( in_channels=config.num_channels, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size, padding="valid", )
self.num_patches_per_side = self.image_size // self.patch_size self.num_patches = self.num_patches_per_side**2 self.num_positions = self.num_patches self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor: batch_size = pixel_values.size(0)
patch_embeds = self.patch_embedding(pixel_values) embeddings = patch_embeds.flatten(2).transpose(1, 2)
max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3) max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side) position_ids = torch.full( size=( batch_size, max_nb_patches_h * max_nb_patches_w, ), fill_value=0, )
for batch_idx, p_attn_mask in enumerate(patch_attention_mask): nb_patches_h = p_attn_mask[:, 0].sum() nb_patches_w = p_attn_mask[0].sum()
fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h) fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True) bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten() position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
position_ids = position_ids.to(self.position_embedding.weight.device)
embeddings = embeddings + self.position_embedding(position_ids) return embeddings
# Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglipclass SiglipTextEmbeddings(nn.Module): def __init__(self, config: SiglipTextConfig): super().__init__() embed_dim = config.hidden_size
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim) self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer( "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False )
def forward( self, input_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, ) -> torch.Tensor: seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
if position_ids is None: position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None: inputs_embeds = self.token_embedding(input_ids)
position_embeddings = self.position_embedding(position_ids) embeddings = inputs_embeds + position_embeddings
return embeddings
class SiglipAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__ def __init__(self, config): super().__init__() self.config = config self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads if self.head_dim * self.num_heads != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads})." ) self.scale = self.head_dim**-0.5 self.dropout = config.attention_dropout
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim) self.v_proj = nn.Linear(self.embed_dim, self.embed_dim) self.q_proj = nn.Linear(self.embed_dim, self.embed_dim) self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel"""
batch_size, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
k_v_seq_len = key_states.shape[-2] attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len): raise ValueError( f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is" f" {attn_weights.size()}" )
if attention_mask is not None: if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len): raise ValueError( f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask
# upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) attn_output = torch.matmul(attn_weights, value_states)
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}" )
attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
class SiglipFlashAttention2(SiglipAttention): """ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_causal = False # Hack to make sure we don't use a causal mask
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: output_attentions = False
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
# Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
kv_seq_len = key_states.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
# if past_key_value is not None: # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
# 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 # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2)
dropout_rate = self.dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (LlamaRMSNorm handles it correctly)
input_dtype = query_states.dtype if input_dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype
logger.warning_once( "The input hidden states seems to be silently casted in float32, this might be related to the fact" " you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." )
query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype)
attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate )
attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous() attn_output = self.out_proj(attn_output)
if not output_attentions: attn_weights = None
return attn_output, attn_weights
def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`int`, *optional*): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """
# 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__. causal = self.is_causal and query_length != 1
# Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( query_states, key_states, value_states, attention_mask, query_length )
cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, )
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal )
return attn_output
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), )
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglipclass SiglipMLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.activation_fn = ACT2FN[config.hidden_act] self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) return hidden_states
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglipclass SiglipEncoderLayer(nn.Module): def __init__(self, config: SiglipConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = ( SiglipAttention(config) if not getattr(config, "_flash_attn_2_enabled", False) else SiglipFlashAttention2(config) ) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = SiglipMLP(config) self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> Tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(batch, seq_len, embed_dim)`. attention_mask (`torch.FloatTensor`): Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*, defaults to `False`): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states
hidden_states = self.layer_norm1(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, ) hidden_states = residual + hidden_states
residual = hidden_states hidden_states = self.layer_norm2(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions: outputs += (attn_weights,)
return outputs
class SiglipPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
config_class = SiglipConfig base_model_prefix = "siglip" supports_gradient_checkpointing = True
def _init_weights(self, module): """Initialize the weights"""
if isinstance(module, SiglipVisionEmbeddings): width = ( self.config.vision_config.hidden_size if isinstance(self.config, SiglipConfig) else self.config.hidden_size ) nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width)) elif isinstance(module, nn.Embedding): default_flax_embed_init(module.weight) elif isinstance(module, SiglipAttention): nn.init.normal_(module.q_proj.weight) nn.init.normal_(module.k_proj.weight) nn.init.normal_(module.v_proj.weight) nn.init.normal_(module.out_proj.weight) nn.init.zeros_(module.q_proj.bias) nn.init.zeros_(module.k_proj.bias) nn.init.zeros_(module.v_proj.bias) nn.init.zeros_(module.out_proj.bias) elif isinstance(module, SiglipMLP): nn.init.normal_(module.fc1.weight) nn.init.normal_(module.fc2.weight) nn.init.normal_(module.fc1.bias, std=1e-6) nn.init.normal_(module.fc2.bias, std=1e-6) elif isinstance(module, SiglipMultiheadAttentionPoolingHead): nn.init.normal_(module.probe.data) nn.init.normal_(module.attention.in_proj_weight.data) nn.init.zeros_(module.attention.in_proj_bias.data) elif isinstance(module, SiglipModel): logit_scale_init = torch.tensor(0.0) module.logit_scale.data.fill_(logit_scale_init) module.logit_bias.data.zero_() elif isinstance(module, (nn.Linear, nn.Conv2d)): lecun_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0)
SIGLIP_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`SiglipConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
SIGLIP_TEXT_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
SIGLIP_VISION_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
SIGLIP_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details. return_loss (`bool`, *optional*): Whether or not to return the contrastive loss. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglipclass SiglipEncoder(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`SiglipEncoderLayer`]. Args: config: SiglipConfig """
def __init__(self, config: SiglipConfig): super().__init__() self.config = config self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False
# Ignore copy def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: r""" Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
encoder_states = () if output_hidden_states else None all_attentions = () if output_attentions else None
hidden_states = inputs_embeds for encoder_layer in self.layers: if output_hidden_states: encoder_states = encoder_states + (hidden_states,) if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( encoder_layer.__call__, hidden_states, attention_mask, output_attentions, ) else: layer_outputs = encoder_layer( hidden_states, attention_mask, output_attentions=output_attentions, )
hidden_states = layer_outputs[0]
if output_attentions: all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states: encoder_states = encoder_states + (hidden_states,)
if not return_dict: return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions )
class SiglipTextTransformer(nn.Module): def __init__(self, config: SiglipTextConfig): super().__init__() self.config = config embed_dim = config.hidden_size self.embeddings = SiglipTextEmbeddings(config) self.encoder = SiglipEncoder(config) self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.head = nn.Linear(embed_dim, embed_dim)
@add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Returns: """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is None: raise ValueError("You have to specify input_ids")
input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1])
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
# note: SigLIP's text model does not use a causal mask, unlike the original CLIP model. # expand attention_mask if attention_mask is not None: # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len] attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
encoder_outputs = self.encoder( inputs_embeds=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
last_hidden_state = encoder_outputs[0] last_hidden_state = self.final_layer_norm(last_hidden_state)
# Assuming "sticky" EOS tokenization, last token is always EOS. pooled_output = last_hidden_state[:, -1, :] pooled_output = self.head(pooled_output)
if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling( last_hidden_state=last_hidden_state, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, )
@add_start_docstrings( """The text model from SigLIP without any head or projection on top.""", SIGLIP_START_DOCSTRING,)class SiglipTextModel(SiglipPreTrainedModel): config_class = SiglipTextConfig
_no_split_modules = ["SiglipTextEmbeddings", "SiglipEncoderLayer"]
def __init__(self, config: SiglipTextConfig): super().__init__(config) self.text_model = SiglipTextTransformer(config) # Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self) -> nn.Module: return self.text_model.embeddings.token_embedding
def set_input_embeddings(self, value): self.text_model.embeddings.token_embedding = value
@add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Returns: Examples: ```python >>> from transformers import AutoTokenizer, SiglipTextModel >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224") >>> # important: make sure to set padding="max_length" as that's how the model was trained >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_state = outputs.last_hidden_state >>> pooled_output = outputs.pooler_output # pooled (EOS token) states ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict
return self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
class SiglipVisionTransformer(nn.Module): def __init__(self, config: SiglipVisionConfig): super().__init__() self.config = config embed_dim = config.hidden_size
self.embeddings = SiglipVisionEmbeddings(config) self.encoder = SiglipEncoder(config) self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) self.head = SiglipMultiheadAttentionPoolingHead(config)
@add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig) def forward( self, pixel_values, patch_attention_mask: Optional[torch.BoolTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Returns: """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
batch_size = pixel_values.size(0) if patch_attention_mask is None: patch_attention_mask = torch.ones( size=( batch_size, pixel_values.size(2) // self.config.patch_size, pixel_values.size(3) // self.config.patch_size, ), dtype=torch.bool, device=pixel_values.device, )
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
patch_attention_mask = patch_attention_mask.view(batch_size, -1) # The call to `_upad_input` in `_flash_attention_forward` is expensive # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence), # avoiding passing the attention_mask, which is equivalent to attending to the full sequence if not torch.any(~patch_attention_mask): attention_mask=None else: attention_mask = ( _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype) if not self.config._flash_attn_2_enabled else patch_attention_mask )
encoder_outputs = self.encoder( inputs_embeds=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
last_hidden_state = encoder_outputs[0] last_hidden_state = self.post_layernorm(last_hidden_state)
pooled_output = self.head( hidden_state=last_hidden_state, attention_mask=patch_attention_mask, )
if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling( last_hidden_state=last_hidden_state, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, )
class SiglipMultiheadAttentionPoolingHead(nn.Module): """Multihead Attention Pooling."""
def __init__(self, config: SiglipVisionConfig): super().__init__()
self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True) self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.mlp = SiglipMLP(config)
def forward(self, hidden_state, attention_mask): batch_size = hidden_state.shape[0] probe = self.probe.repeat(batch_size, 1, 1)
hidden_state = self.attention( query=probe, key=hidden_state, value=hidden_state, key_padding_mask=~attention_mask )[0]
residual = hidden_state hidden_state = self.layernorm(hidden_state) hidden_state = residual + self.mlp(hidden_state)
return hidden_state[:, 0]
@add_start_docstrings( """The vision model from SigLIP without any head or projection on top.""", SIGLIP_START_DOCSTRING,)class SiglipVisionModel(SiglipPreTrainedModel): config_class = SiglipVisionConfig main_input_name = "pixel_values"
def __init__(self, config: SiglipVisionConfig): super().__init__(config)
self.vision_model = SiglipVisionTransformer(config)
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self) -> nn.Module: return self.vision_model.embeddings.patch_embedding
@add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig) def forward( self, pixel_values, patch_attention_mask: Optional[torch.BoolTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Returns: Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, SiglipVisionModel >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_state = outputs.last_hidden_state >>> pooled_output = outputs.pooler_output # pooled features ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict
return self.vision_model( pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
@add_start_docstrings(SIGLIP_START_DOCSTRING)class SiglipModel(SiglipPreTrainedModel): config_class = SiglipConfig
def __init__(self, config: SiglipConfig): super().__init__(config)
if not isinstance(config.text_config, SiglipTextConfig): raise ValueError( "config.text_config is expected to be of type SiglipTextConfig but is of type" f" {type(config.text_config)}." )
if not isinstance(config.vision_config, SiglipVisionConfig): raise ValueError( "config.vision_config is expected to be of type SiglipVisionConfig but is of type" f" {type(config.vision_config)}." )
text_config = config.text_config vision_config = config.vision_config
self.text_model = SiglipTextTransformer(text_config) self.vision_model = SiglipVisionTransformer(vision_config)
self.logit_scale = nn.Parameter(torch.randn(1)) self.logit_bias = nn.Parameter(torch.randn(1))
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING) def get_text_features( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> torch.FloatTensor: r""" Returns: text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`]. Examples: ```python >>> from transformers import AutoTokenizer, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224") >>> # important: make sure to set padding="max_length" as that's how the model was trained >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt") >>> with torch.no_grad(): ... text_features = model.get_text_features(**inputs) ```""" # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
text_outputs = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
pooled_output = text_outputs[1]
return pooled_output
@add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING) def get_image_features( self, pixel_values: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> torch.FloatTensor: r""" Returns: image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`]. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> with torch.no_grad(): ... image_features = model.get_image_features(**inputs) ```""" # Use SiglipModel's config for some fields (if specified) instead of those of vision & text components. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model( pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
pooled_output = vision_outputs[1]
return pooled_output
@add_start_docstrings_to_model_forward(SIGLIP_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=SiglipOutput, config_class=SiglipConfig) def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, return_loss: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SiglipOutput]: r""" Returns: Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"] >>> # important: we pass `padding=max_length` since the model was trained with this >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt") >>> with torch.no_grad(): ... outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'") 31.9% that image 0 is 'a photo of 2 cats' ```""" # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model( pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
text_outputs = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
image_embeds = vision_outputs[1] text_embeds = text_outputs[1]
# normalized features image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True) text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
# cosine similarity as logits logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * self.logit_scale.exp() + self.logit_bias logits_per_image = logits_per_text.t()
loss = None if return_loss: raise NotImplementedError("SigLIP loss to be implemented")
if not return_dict: output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs) return ((loss,) + output) if loss is not None else output
return SiglipOutput( loss=loss, logits_per_image=logits_per_image, logits_per_text=logits_per_text, text_embeds=text_embeds, image_embeds=image_embeds, text_model_output=text_outputs, vision_model_output=vision_outputs, )
def get_siglip_vision_model(_flash_attn_2_enabled=True, **kwargs): siglip_vision_config = { "hidden_size": 1152, "image_size": 448, "intermediate_size": 4304, "model_type": "siglip_vision_model", "num_attention_heads": 16, "num_hidden_layers": 27, "patch_size": 14, }
model_config = SiglipVisionConfig(**siglip_vision_config, _flash_attn_2_enabled=_flash_attn_2_enabled, **kwargs)
vision_model = SiglipVisionModel(model_config).vision_model
return vision_model123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttekken.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294---library_name: vllmlanguage:- en- fr- de- es- it- pt- ru- zh- jalicense: apache-2.0base_model:- mistralai/Pixtral-12B-Base-2409inference: falseextra_gated_description: >- If you want to learn more about how we process your personal data, please read our <a href="https://mistral.ai/terms/">Privacy Policy</a>.tags:- mistral-common---
# Model Card for Pixtral-12B-2409
The Pixtral-12B-2409 is a Multimodal Model of 12B parameters plus a 400M parameter vision encoder.
For more details about this model please refer to our release [blog post](https://mistral.ai/news/pixtral-12b/).
Feel free to try it [here](https://chat.mistral.ai/chat)
## Key features- Natively multimodal, trained with interleaved image and text data- 12B parameter Multimodal Decoder + 400M parameter Vision Encoder- Supports variable image sizes- Leading performance in its weight class on multimodal tasks- Maintains state-of-the-art performance on text-only benchmarks- Sequence length: 128k- License: Apache 2.0
## BenchmarksThe performance of Pixtral-12B-2409 compared to multimodal models. All models were re-evaluated and benchmarked through the same evaluation pipeline.
### Multimodal Benchmarks
| | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision ||:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|| **MMMU** *(CoT)* | <ins>**52.5**</ins> | 47.6 | 45.1 | 40.3 | 38.3 || **Mathvista** *(CoT)* | <ins>**58.0**</ins> | 54.4 | 36.1 | 36.4 | 39.3 || **ChartQA** *(CoT)* | <ins>**81.8**</ins> | 38.6 | 67.1 | 72.0 | 67.7 || **DocVQA** *(ANLS)* | 90.7 | <ins>**94.5**</ins> | 90.5 | 84.9 | 74.4 || **VQAv2** *(VQA Match)* | <ins>**78.6**</ins> | 75.9 | 78.3 | 42.4 | 56.1 |
### Instruction Following
| | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision ||:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|| **MM MT-Bench** | <ins>**6.05**</ins> | 5.43 | 4.12 | 3.70 |4.46 || **Text MT-Bench** | <ins>**7.68**</ins> | 6.41 | 6.94 | 6.27 |6.31 || **MM IF-Eval** | <ins>**52.7**</ins> | 38.9 | 42.5 | 41.2 |31.4 || **Text IF-Eval** | <ins>**61.3**</ins> | 50.1 | 51.4 | 50.9 |47.4 |
### Text Benchmarks
| | Pixtral 12B | Qwen2 7B VL | LLaVA-OV 7B | Phi-3 Vision | Phi-3.5 Vision ||:-------------------:|:-------------:|:----------:|:-------------:|:--------------:|:--------------:|| **MMLU** *(5-shot)* | <ins>**69.2**</ins> | 68.5 | 67.9 | 63.5 | 63.6 || **Math** *(Pass@1)* | <ins>**48.1**</ins> | 27.8 | 38.6 | 29.2 | 28.4 || **Human Eval** *(Pass@1)* | <ins>**72.0**</ins> | 64.6 | 65.9 | 48.8 | 49.4 |
### Comparison with Closed Source and Larger Models| | Pixtral 12B | Claude-3 Haiku | Gemini-1.5 Flash 8B *(0827)* | . |*LLaVA-OV 72B* | *GPT-4o* | *Claude-3.5 Sonnet* ||:-------------------:|:-------------:|:----------------:|:----------------------:|:--------:|:----:|:-------------------:|:-------------------:|| **MMMU** *(CoT)* | **52.5** | 50.4 | 50.7 | |*54.4* |<ins>*68.6*</ins> | *68.0* || **Mathvista** *(CoT)* | **58.0** | 44.8 | 56.9 | |*57.2* |<ins>*64.6*</ins> | *64.4* || **ChartQA** *(CoT)* | **81.8** | 69.6 | 78.0 | |*66.9* |*85.1* | <ins>*87.6*</ins> || **DocVQA** *(ANLS)* | **90.7**</ins> | 74.6 | 79.5 | |<ins>*91.6*</ins> |*88.9* | *90.3* || **VQAv2** *(VQA Match)* | **78.6** | 68.4 | 65.5 | |<ins>*83.8*</ins> |*77.8* | *70.7* |
## Usage Examples
### vLLM (recommended)
We recommend using Pixtral with the [vLLM library](https://github.com/vllm-project/vllm)to implement production-ready inference pipelines with Pixtral.
**_Installation_**
Make sure you install `vLLM >= v0.6.2`:
```pip install --upgrade vllm```
Also make sure you have `mistral_common >= 1.4.4` installed:
```pip install --upgrade mistral_common```
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).
**_Simple Example_**
```pyfrom vllm import LLMfrom vllm.sampling_params import SamplingParams
model_name = "mistralai/Pixtral-12B-2409"
sampling_params = SamplingParams(max_tokens=8192)
llm = LLM(model=model_name, tokenizer_mode="mistral")
prompt = "Describe this image in one sentence."image_url = "https://picsum.photos/id/237/200/300"
messages = [ { "role": "user", "content": [{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": image_url}}] },]
outputs = llm.chat(messages, sampling_params=sampling_params)
print(outputs[0].outputs[0].text)```
**_Advanced Example_**
You can also pass multiple images per message and/or pass multi-turn conversations
```pyfrom vllm import LLMfrom vllm.sampling_params import SamplingParams
model_name = "mistralai/Pixtral-12B-2409"max_img_per_msg = 5
sampling_params = SamplingParams(max_tokens=8192, temperature=0.7)
# Lower max_num_seqs or max_model_len on low-VRAM GPUs.llm = LLM(model=model_name, tokenizer_mode="mistral", limit_mm_per_prompt={"image": max_img_per_msg}, max_model_len=32768)
prompt = "Describe the following image."
url_1 = "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"url_2 = "https://picsum.photos/seed/picsum/200/300"url_3 = "https://picsum.photos/id/32/512/512"
messages = [ { "role": "user", "content": [{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": url_1}}, {"type": "image_url", "image_url": {"url": url_2}}], }, { "role": "assistant", "content": "The images shows nature.", }, { "role": "user", "content": "More details please and answer only in French!." }, { "role": "user", "content": [{"type": "image_url", "image_url": {"url": url_3}}], }]
outputs = llm.chat(messages=messages, sampling_params=sampling_params)print(outputs[0].outputs[0].text)```
You can find more examples and tests directly in vLLM.- [Examples](https://github.com/vllm-project/vllm/blob/main/examples/offline_inference_pixtral.py)- [Tests](https://github.com/vllm-project/vllm/blob/main/tests/models/test_pixtral.py)
**_Server_**
You can also use pixtral in a server/client setting.
1. Spin up a server:
```vllm serve mistralai/Pixtral-12B-2409 --tokenizer_mode mistral --limit_mm_per_prompt 'image=4'```
2. And ping the client:
```curl --location 'http://<your-node-url>:8000/v1/chat/completions' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer token' \--data '{ "model": "mistralai/Pixtral-12B-2409", "messages": [ { "role": "user", "content": [ {"type" : "text", "text": "Describe this image in detail please."}, {"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"}}, {"type" : "text", "text": "and this one as well. Answer in French."}, {"type": "image_url", "image_url": {"url": "https://www.wolframcloud.com/obj/resourcesystem/images/a0e/a0ee3983-46c6-4c92-b85d-059044639928/6af8cfb971db031b.png"}} ] } ] }'```
### Mistral-inference
We recommend using [mistral-inference](https://github.com/mistralai/mistral-inference) to quickly try out / "vibe-check" Pixtral.
**_Install_**
Make sure to have `mistral_inference >= 1.4.1` installed.
```pip install mistral_inference --upgrade```
**_Download_**
```pyfrom huggingface_hub import snapshot_downloadfrom pathlib import Path
mistral_models_path = Path.home().joinpath('mistral_models', 'Pixtral')mistral_models_path.mkdir(parents=True, exist_ok=True)
snapshot_download(repo_id="mistralai/Pixtral-12B-2409", allow_patterns=["params.json", "consolidated.safetensors", "tekken.json"], local_dir=mistral_models_path)```
**_Chat_**
After installing `mistral_inference`, a `mistral-chat` CLI command should be available in your environment. You can pass text and images or image urls to the model in *instruction-following* mode as follows:
```mistral-chat $HOME/mistral_models/Pixtral --instruct --max_tokens 256 --temperature 0.35```
*E.g.* Try out something like:
```Text prompt: What can you see on the following picture?[You can input zero, one or more images now.]Image path or url [Leave empty and press enter to finish image input]: https://picsum.photos/id/237/200/300Image path or url [Leave empty and press enter to finish image input]:I see a black dog lying on a wooden surface. The dog appears to be looking up, and its eyes are clearly visible.```
**_Python_**
You can also run the model in a Python shell as follows.
```pyfrom mistral_inference.transformer import Transformerfrom mistral_inference.generate import generate
from mistral_common.tokens.tokenizers.mistral import MistralTokenizerfrom mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageURLChunkfrom mistral_common.protocol.instruct.request import ChatCompletionRequest
tokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json")model = Transformer.from_folder(mistral_models_path)
url = "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"prompt = "Describe the image."
completion_request = ChatCompletionRequest(messages=[UserMessage(content=[ImageURLChunk(image_url=url), TextChunk(text=prompt)])])
encoded = tokenizer.encode_chat_completion(completion_request)
images = encoded.imagestokens = encoded.tokens
out_tokens, _ = generate([tokens], model, images=[images], max_tokens=256, temperature=0.35, eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id)result = tokenizer.decode(out_tokens[0])
print(result)```
## Limitations
The Pixtral model does not have any moderation mechanisms. We're looking forward to engaging with the community on ways tomake the model finely respect guardrails, allowing for deployment in environments requiring moderated outputs.
## The Mistral AI Team
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 Marshall12345678910111213141516171819202122232425{ "dim": 5120, "n_layers": 40, "head_dim": 128, "hidden_dim": 14336, "n_heads": 32, "n_kv_heads": 8, "rope_theta": 1000000000.0, "norm_eps": 1e-05, "vocab_size": 131072, "max_position_embeddings": 131072, "vision_encoder": { "hidden_size": 1024, "num_channels": 3, "image_size": 1024, "patch_size": 16, "rope_theta": 10000.0, "intermediate_size": 4096, "num_hidden_layers": 24, "num_attention_heads": 16, "image_token_id": 10, "image_break_token_id": 12, "image_end_token_id": 13 }}1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2024 Alibaba Cloud
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502---license: apache-2.0language:- enpipeline_tag: image-text-to-texttags:- multimodallibrary_name: transformersbase_model:- Qwen/Qwen2-VL-7Bnew_version: Qwen/Qwen2.5-VL-7B-Instruct---
# Qwen2-VL-7B-Instruct<a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;"> <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;"/></a>
## Introduction
We're excited to unveil **Qwen2-VL**, the latest iteration of our Qwen-VL model, representing nearly a year of innovation.
### What’s New in Qwen2-VL?
#### Key Enhancements:
* **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.
* **Understanding videos of 20min+**: Qwen2-VL can understand videos over 20 minutes for high-quality video-based question answering, dialog, content creation, etc.
* **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.
* **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.
#### Model Architecture Updates:
* **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.
<p align="center"> <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/qwen2_vl.jpg" width="80%"/><p>
* **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.
<p align="center"> <img src="http://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/mrope.png" width="80%"/><p>
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).
## Evaluation
### Image Benchmarks
| Benchmark | InternVL2-8B | MiniCPM-V 2.6 | GPT-4o-mini | **Qwen2-VL-7B** || :--- | :---: | :---: | :---: | :---: || MMMU<sub>val</sub> | 51.8 | 49.8 | **60**| 54.1 || DocVQA<sub>test</sub> | 91.6 | 90.8 | - | **94.5** || InfoVQA<sub>test</sub> | 74.8 | - | - |**76.5** || ChartQA<sub>test</sub> | **83.3** | - |- | 83.0 || TextVQA<sub>val</sub> | 77.4 | 80.1 | -| **84.3** || OCRBench | 794 | **852** | 785 | 845 || MTVQA | - | - | -| **26.3** || VCR<sub>en easy</sub> | - | 73.88 | 83.60 | **89.70** || VCR<sub>zh easy</sub> | - | 10.18| 1.10 | **59.94** | | RealWorldQA | 64.4 | - | - | **70.1** || MME<sub>sum</sub> | 2210.3 | **2348.4** | 2003.4| 2326.8 || MMBench-EN<sub>test</sub> | 81.7 | - | - | **83.0** || MMBench-CN<sub>test</sub> | **81.2** | - | - | 80.5 || MMBench-V1.1<sub>test</sub> | 79.4 | 78.0 | 76.0| **80.7** || MMT-Bench<sub>test</sub> | - | - | - |**63.7** || MMStar | **61.5** | 57.5 | 54.8 | 60.7 || MMVet<sub>GPT-4-Turbo</sub> | 54.2 | 60.0 | **66.9** | 62.0 || HallBench<sub>avg</sub> | 45.2 | 48.1 | 46.1| **50.6** || MathVista<sub>testmini</sub> | 58.3 | **60.6** | 52.4 | 58.2 || MathVision | - | - | - | **16.3** |
### Video Benchmarks
| Benchmark | Internvl2-8B | LLaVA-OneVision-7B | MiniCPM-V 2.6 | **Qwen2-VL-7B** || :--- | :---: | :---: | :---: | :---: || MVBench | 66.4 | 56.7 | - | **67.0** || PerceptionTest<sub>test</sub> | - | 57.1 | - | **62.3** || EgoSchema<sub>test</sub> | - | 60.1 | - | **66.7** || Video-MME<sub>wo/w subs</sub> | 54.0/56.9 | 58.2/- | 60.9/63.6 | **63.3**/**69.0** |
## RequirementsThe 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:```KeyError: 'qwen2_vl'```
## QuickstartWe 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:
```bashpip install qwen-vl-utils```
Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
```pythonfrom transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessorfrom qwen_vl_utils import process_vision_info
# default: Load the model on the available device(s)model = Qwen2VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto")
# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.# model = Qwen2VLForConditionalGeneration.from_pretrained(# "Qwen/Qwen2-VL-7B-Instruct",# torch_dtype=torch.bfloat16,# attn_implementation="flash_attention_2",# device_map="auto",# )
# default processerprocessor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
# 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.# min_pixels = 256*28*28# max_pixels = 1280*28*28# processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", }, {"type": "text", "text": "Describe this image."}, ], }]
# Preparation for inferencetext = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True)image_inputs, video_inputs = process_vision_info(messages)inputs = processor( text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt",)inputs = inputs.to("cuda")
# Inference: Generation of the outputgenerated_ids = model.generate(**inputs, max_new_tokens=128)generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)print(output_text)```<details><summary>Without qwen_vl_utils</summary>
```pythonfrom PIL import Imageimport requestsimport torchfrom torchvision import iofrom typing import Dictfrom transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
# Load the model in half-precision on the available device(s)model = Qwen2VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto")processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
# Imageurl = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"image = Image.open(requests.get(url, stream=True).raw)
conversation = [ { "role": "user", "content": [ { "type": "image", }, {"type": "text", "text": "Describe this image."}, ], }]
# Preprocess the inputstext_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)# 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'
inputs = processor( text=[text_prompt], images=[image], padding=True, return_tensors="pt")inputs = inputs.to("cuda")
# Inference: Generation of the outputoutput_ids = model.generate(**inputs, max_new_tokens=128)generated_ids = [ output_ids[len(input_ids) :] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]output_text = processor.batch_decode( generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)print(output_text)```</details><details><summary>Multi image inference</summary>
```python# Messages containing multiple images and a text querymessages = [ { "role": "user", "content": [ {"type": "image", "image": "file:///path/to/image1.jpg"}, {"type": "image", "image": "file:///path/to/image2.jpg"}, {"type": "text", "text": "Identify the similarities between these images."}, ], }]
# Preparation for inferencetext = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True)image_inputs, video_inputs = process_vision_info(messages)inputs = processor( text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt",)inputs = inputs.to("cuda")
# Inferencegenerated_ids = model.generate(**inputs, max_new_tokens=128)generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)print(output_text)```</details>
<details><summary>Video inference</summary>
```python# Messages containing a images list as a video and a text querymessages = [ { "role": "user", "content": [ { "type": "video", "video": [ "file:///path/to/frame1.jpg", "file:///path/to/frame2.jpg", "file:///path/to/frame3.jpg", "file:///path/to/frame4.jpg", ], "fps": 1.0, }, {"type": "text", "text": "Describe this video."}, ], }]# Messages containing a video and a text querymessages = [ { "role": "user", "content": [ { "type": "video", "video": "file:///path/to/video1.mp4", "max_pixels": 360 * 420, "fps": 1.0, }, {"type": "text", "text": "Describe this video."}, ], }]
# Preparation for inferencetext = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True)image_inputs, video_inputs = process_vision_info(messages)inputs = processor( text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt",)inputs = inputs.to("cuda")
# Inferencegenerated_ids = model.generate(**inputs, max_new_tokens=128)generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)print(output_text)```</details>
<details><summary>Batch inference</summary>
```python# Sample messages for batch inferencemessages1 = [ { "role": "user", "content": [ {"type": "image", "image": "file:///path/to/image1.jpg"}, {"type": "image", "image": "file:///path/to/image2.jpg"}, {"type": "text", "text": "What are the common elements in these pictures?"}, ], }]messages2 = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who are you?"},]# Combine messages for batch processingmessages = [messages1, messages1]
# Preparation for batch inferencetexts = [ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages]image_inputs, video_inputs = process_vision_info(messages)inputs = processor( text=texts, images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt",)inputs = inputs.to("cuda")
# Batch Inferencegenerated_ids = model.generate(**inputs, max_new_tokens=128)generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_texts = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)print(output_texts)```</details>
### More Usage Tips
For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
```python# You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.## Local file pathmessages = [ { "role": "user", "content": [ {"type": "image", "image": "file:///path/to/your/image.jpg"}, {"type": "text", "text": "Describe this image."}, ], }]## Image URLmessages = [ { "role": "user", "content": [ {"type": "image", "image": "http://path/to/your/image.jpg"}, {"type": "text", "text": "Describe this image."}, ], }]## Base64 encoded imagemessages = [ { "role": "user", "content": [ {"type": "image", "image": "data:image;base64,/9j/..."}, {"type": "text", "text": "Describe this image."}, ], }]```#### Image Resolution for performance boost
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.
```pythonmin_pixels = 256 * 28 * 28max_pixels = 1280 * 28 * 28processor = AutoProcessor.from_pretrained( "Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)```
Besides, We provide two methods for fine-grained control over the image size input to the model:
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. 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
```python# min_pixels and max_pixelsmessages = [ { "role": "user", "content": [ { "type": "image", "image": "file:///path/to/your/image.jpg", "resized_height": 280, "resized_width": 420, }, {"type": "text", "text": "Describe this image."}, ], }]# resized_height and resized_widthmessages = [ { "role": "user", "content": [ { "type": "image", "image": "file:///path/to/your/image.jpg", "min_pixels": 50176, "max_pixels": 50176, }, {"type": "text", "text": "Describe this image."}, ], }]```
## Limitations
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:
1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.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.4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.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.
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.
## Citation
If you find our work helpful, feel free to give us a cite.
```@article{Qwen2VL, title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution}, 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}, journal={arXiv preprint arXiv:2409.12191}, year={2024}}
@article{Qwen-VL, title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond}, 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}, journal={arXiv preprint arXiv:2308.12966}, year={2023}}```123{ "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 %}"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "architectures": [ "Qwen2VLForConditionalGeneration" ], "attention_dropout": 0.0, "bos_token_id": 151643, "eos_token_id": 151645, "vision_start_token_id": 151652, "vision_end_token_id": 151653, "vision_token_id": 151654, "image_token_id": 151655, "video_token_id": 151656, "hidden_act": "silu", "hidden_size": 3584, "initializer_range": 0.02, "intermediate_size": 18944, "max_position_embeddings": 32768, "max_window_layers": 28, "model_type": "qwen2_vl", "num_attention_heads": 28, "num_hidden_layers": 28, "num_key_value_heads": 4, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window": 32768, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.41.2", "use_cache": true, "use_sliding_window": false, "vision_config": { "depth": 32, "embed_dim": 1280, "mlp_ratio": 4, "num_heads": 16, "in_chans": 3, "hidden_size": 3584, "patch_size": 14, "spatial_merge_size": 2, "spatial_patch_size": 14, "temporal_patch_size": 2 }, "rope_scaling": { "type": "mrope", "mrope_section": [ 16, 24, 24 ] }, "vocab_size": 152064}1234567891011121314{ "bos_token_id": 151643, "pad_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "repetition_penalty": 1.0, "temperature": 0.01, "top_p": 0.001, "top_k": 1, "transformers_version": "4.37.0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737{ "metadata": { "total_size": 16582751232 }, "weight_map": { "lm_head.weight": "model-00005-of-00005.safetensors", "model.embed_tokens.weight": "model-00001-of-00005.safetensors", "model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.10.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.10.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.11.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.11.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.11.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.12.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.12.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.13.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.14.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.15.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.16.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.17.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.18.mlp.down_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.input_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.19.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00005.safetensors", "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", "model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.2.mlp.down_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.mlp.up_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.20.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.20.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.20.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.21.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.21.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.22.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.22.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.23.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.23.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.24.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.24.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.25.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.25.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.26.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.26.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.input_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.27.mlp.down_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.mlp.up_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.k_proj.bias": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.q_proj.bias": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.v_proj.bias": "model-00004-of-00005.safetensors", "model.layers.27.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", "model.layers.3.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.3.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.3.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.3.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.4.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.4.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.5.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.6.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.7.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.8.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.input_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.9.mlp.down_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.mlp.up_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00005.safetensors", "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.norm.weight": "model-00004-of-00005.safetensors", "visual.blocks.0.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.0.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.0.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.0.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.0.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.0.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.0.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.1.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.1.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.10.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.10.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.11.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.11.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.12.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.12.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.13.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.13.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.14.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.14.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.15.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.15.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.16.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.16.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.17.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.17.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.18.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.18.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.19.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.19.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.2.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.2.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.20.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.20.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.21.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.21.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.22.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.22.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.23.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.23.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.24.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.24.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.25.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.25.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.26.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.26.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.27.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.27.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.28.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.28.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.29.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.29.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.3.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.3.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.30.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.30.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.31.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.31.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.4.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.4.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.5.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.5.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.6.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.6.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.7.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.7.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.8.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.8.norm2.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.attn.proj.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.attn.proj.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.attn.qkv.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.attn.qkv.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.mlp.fc1.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.mlp.fc1.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.mlp.fc2.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.mlp.fc2.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.norm1.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.norm1.weight": "model-00001-of-00005.safetensors", "visual.blocks.9.norm2.bias": "model-00001-of-00005.safetensors", "visual.blocks.9.norm2.weight": "model-00001-of-00005.safetensors", "visual.merger.ln_q.bias": "model-00001-of-00005.safetensors", "visual.merger.ln_q.weight": "model-00001-of-00005.safetensors", "visual.merger.mlp.0.bias": "model-00001-of-00005.safetensors", "visual.merger.mlp.0.weight": "model-00001-of-00005.safetensors", "visual.merger.mlp.2.bias": "model-00001-of-00005.safetensors", "visual.merger.mlp.2.weight": "model-00001-of-00005.safetensors", "visual.patch_embed.proj.weight": "model-00001-of-00005.safetensors" }}12345678910111213141516171819{ "min_pixels": 3136, "max_pixels": 12845056, "patch_size": 14, "temporal_patch_size": 2, "merge_size": 2, "image_mean": [ 0.48145466, 0.4578275, 0.40821073 ], "image_std": [ 0.26862954, 0.26130258, 0.27577711 ], "image_processor_type": "Qwen2VLImageProcessor", "processor_class": "Qwen2VLProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129{ "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "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|>"], "bos_token": null, "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 %}", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "padding_side": "left", "errors": "replace", "model_max_length": 32768, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}12345678910111213141516171819202122232425262728293031323334353637*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textonnx/decoder_model_merged.onnx_data filter=lfs diff=lfs merge=lfs -textonnx/decoder_model_merged_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191---library_name: transformerslicense: apache-2.0datasets:- HuggingFaceM4/the_cauldron- HuggingFaceM4/Docmatixpipeline_tag: image-text-to-textlanguage:- enbase_model:- HuggingFaceTB/SmolLM2-1.7B-Instruct- google/siglip-so400m-patch14-384---
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/SmolVLM.png" width="800" height="auto" alt="Image description">
# SmolVLM
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.
## Model Summary
- **Developed by:** Hugging Face 🤗- **Model type:** Multi-modal model (image+text)- **Language(s) (NLP):** English- **License:** Apache 2.0- **Architecture:** Based on [Idefics3](https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3) (see technical summary)
## Resources
- **Demo:** [SmolVLM Demo](https://huggingface.co/spaces/HuggingFaceTB/SmolVLM)- **Blog:** [Blog post](https://huggingface.co/blog/smolvlm)
## Uses
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.
To fine-tune SmolVLM on a specific task, you can follow the fine-tuning tutorial.<!-- todo: add link to fine-tuning tutorial -->
### Technical Summary
SmolVLM leverages the lightweight SmolLM2 language model to provide a compact yet powerful multimodal experience. It introduces several changes compared to previous Idefics models:
- **Image compression:** We introduce a more radical image compression compared to Idefics3 to enable the model to infer faster and use less RAM.- **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.
More details about the training and architecture are available in our technical report.
### How to get started
You can use transformers to load, infer and fine-tune SmolVLM.
```pythonimport torchfrom PIL import Imagefrom transformers import AutoProcessor, AutoModelForVision2Seqfrom transformers.image_utils import load_image
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Load imagesimage1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")image2 = load_image("https://huggingface.co/spaces/merve/chameleon-7b/resolve/main/bee.jpg")
# Initialize processor and modelprocessor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct")model = AutoModelForVision2Seq.from_pretrained( "HuggingFaceTB/SmolVLM-Instruct", torch_dtype=torch.bfloat16, _attn_implementation="flash_attention_2" if DEVICE == "cuda" else "eager",).to(DEVICE)
# Create input messagesmessages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "image"}, {"type": "text", "text": "Can you describe the two images?"} ] },]
# Prepare inputsprompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt, images=[image1, image2], return_tensors="pt")inputs = inputs.to(DEVICE)
# Generate outputsgenerated_ids = model.generate(**inputs, max_new_tokens=500)generated_texts = processor.batch_decode( generated_ids, skip_special_tokens=True,)
print(generated_texts[0])"""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. 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. The sky is clear and there are no clouds. The second image shows a bee on a pink flower. The bee is black and yellow and is collecting pollen from the flower. The flower is surrounded by green leaves."""```
### Model optimizations
**Precision**: For better performance, load and run the model in half-precision (`torch.float16` or `torch.bfloat16`) if your hardware supports it.
```pythonfrom transformers import AutoModelForVision2Seqimport torch
model = AutoModelForVision2Seq.from_pretrained( "HuggingFaceTB/SmolVLM-Instruct", torch_dtype=torch.bfloat16).to("cuda")```
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.
```pythonfrom transformers import AutoModelForVision2Seq, BitsAndBytesConfigimport torch
quantization_config = BitsAndBytesConfig(load_in_8bit=True)model = AutoModelForVision2Seq.from_pretrained( "HuggingFaceTB/SmolVLM-Instruct", quantization_config=quantization_config,)```
**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 ofsize 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.
## Misuse and Out-of-scope Use
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:
- Prohibited Uses: - Evaluating or scoring individuals (e.g., in employment, education, credit) - Critical automated decision-making - Generating unreliable factual content- Malicious Activities: - Spam generation - Disinformation campaigns - Harassment or abuse - Unauthorized surveillance
### License
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.
We release the SmolVLM checkpoints under the Apache 2.0 license.
## Training Details
### Training Data
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.<img src="https://huggingface.co/HuggingFaceTB/SmolVLM-Instruct/resolve/main/mixture_the_cauldron.png" alt="Example Image" style="width:90%;" />
## Evaluation
| Model | MMMU (val) | MathVista (testmini) | MMStar (val) | DocVQA (test) | TextVQA (val) | Min GPU RAM required (GB) ||-------------------|------------|----------------------|--------------|---------------|---------------|---------------------------|| SmolVLM | 38.8 | 44.6 | 42.1 | 81.6 | 72.7 | 5.02 || Qwen-VL 2B | 41.1 | 47.8 | 47.5 | 90.1 | 79.7 | 13.70 || InternVL2 2B | 34.3 | 46.3 | 49.8 | 86.9 | 73.4 | 10.52 || PaliGemma 3B 448px| 34.9 | 28.7 | 48.3 | 32.2 | 56.0 | 6.72 || moondream2 | 32.4 | 24.3 | 40.3 | 70.5 | 65.2 | 3.87 || MiniCPM-V-2 | 38.2 | 39.8 | 39.1 | 71.9 | 74.1 | 7.88 || MM1.5 1B | 35.8 | 37.2 | 0.0 | 81.0 | 72.5 | NaN |
# Citation informationYou can cite us in the following way:```bibtex@article{marafioti2025smolvlm, title={SmolVLM: Redefining small and efficient multimodal models}, 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}, journal={arXiv preprint arXiv:2504.05299}, year={2025}}```12345{ "<end_of_utterance>": 49154, "<fake_token_around_image>": 49152, "<image>": 49153}123{ "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 %}"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267{ "architectures": [ "Idefics3ForConditionalGeneration" ], "image_seq_len": 81, "image_token_id": 49153, "model_type": "idefics3", "scale_factor": 3, "text_config": { "_attn_implementation_autoset": false, "_flash_attn_2_enabled": true, "_name_or_path": "/fsx/m4/experiments/local_experiment_dir/s3_async_temporary_checkpoint_folder/tr_324_opt_400/unwrapped_model", "add_cross_attention": false, "architectures": [ "VLlama3ForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": 0, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": 0, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "head_dim": 64, "hidden_act": "silu", "hidden_size": 2048, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "initializer_range": 0.02, "intermediate_size": 8192, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "length_penalty": 1.0, "max_length": 20, "max_position_embeddings": 16384, "min_length": 0, "mlp_bias": false, "model_type": "llama", "neftune_noise_alpha": 0.0, "no_repeat_ngram_size": 0, "num_attention_heads": 32, "num_beam_groups": 1, "num_beams": 1, "num_hidden_layers": 24, "num_key_value_heads": 32, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": 2, "perceiver_config": { "_attn_implementation_autoset": false, "_name_or_path": "", "add_cross_attention": false, "architectures": null, "attention_dropout": 0.0, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": null, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "hidden_act": "silu", "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "length_penalty": 1.0, "max_length": 20, "min_length": 0, "model_type": "vllama3", "no_repeat_ngram_size": 0, "num_beam_groups": 1, "num_beams": 1, "num_key_value_heads": 1, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": null, "prefix": null, "problem_type": null, "pruned_heads": {}, "qk_layer_norms_perceiver": false, "remove_invalid_values": false, "repetition_penalty": 1.0, "resampler_depth": 6, "resampler_head_dim": 96, "resampler_n_heads": 16, "resampler_n_latents": 64, "return_dict": true, "return_dict_in_generate": false, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": true, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "transformers_version": "4.46.0", "typical_p": 1.0, "use_bfloat16": false }, "prefix": null, "pretraining_tp": 1, "problem_type": null, "pruned_heads": {}, "qk_layer_norms": false, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 273768.0, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": false, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": "bfloat16", "torchscript": false, "typical_p": 1.0, "use_bfloat16": false, "use_cache": true, "use_resampler": false, "vocab_size": 49155 }, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.46.0", "transformers.js_config": { "kv_cache_dtype": { "q4f16": "float16", "fp16": "float16" }, "dtype": { "embed_tokens": "auto", "vision_encoder": "auto", "decoder_model_merged": "q4" }, "use_external_data_format": { "decoder_model_merged.onnx": true, "decoder_model_merged_fp16.onnx": true } }, "use_cache": true, "vision_config": { "size": {"longest_edge": 1920}, "max_image_size": {"longest_edge": 384}, "_attn_implementation_autoset": false, "_name_or_path": "", "add_cross_attention": false, "architectures": null, "attention_dropout": 0.0, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": null, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "hidden_act": "gelu_pytorch_tanh", "hidden_size": 1152, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "image_size": 384, "initializer_range": 0.02, "intermediate_size": 4304, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "layer_norm_eps": 1e-06, "length_penalty": 1.0, "max_length": 20, "min_length": 0, "model_type": "idefics3", "no_repeat_ngram_size": 0, "num_attention_heads": 16, "num_beam_groups": 1, "num_beams": 1, "num_channels": 3, "num_hidden_layers": 27, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": null, "patch_size": 14, "prefix": null, "problem_type": null, "pruned_heads": {}, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": false, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "typical_p": 1.0, "use_bfloat16": false }, "vocab_size": 49155}1234567{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 49154, "pad_token_id": 2, "transformers_version": "4.46.0"}12345678910111213141516171819202122232425262728{ "do_convert_rgb": true, "do_image_splitting": true, "do_normalize": true, "do_pad": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Idefics3ImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "max_image_size": { "longest_edge": 384 }, "processor_class": "Idefics3Processor", "resample": 1, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 1536 }}1234{ "processor_class": "Idefics3Processor", "image_seq_len": 81}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "additional_special_tokens": [ { "content": "<fake_token_around_image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<end_of_utterance>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false } ], "bos_token": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}models/Phi-4-multimodal-instruct/model.safetensors.index.jsonAdded
models/Phi-4-multimodal-instruct/modeling_phi4mm.pyAdded
models/Phi-4-multimodal-instruct/preprocessor_config.jsonAdded+14
models/Phi-4-multimodal-instruct/processing_phi4mm.pyAdded+733
models/Phi-4-multimodal-instruct/processor_config.jsonAdded+6
models/Phi-4-multimodal-instruct/sample_finetune_speech.pyAdded+478
models/Phi-4-multimodal-instruct/sample_finetune_vision.pyAdded+556
models/Phi-4-multimodal-instruct/sample_inference_phi4mm.pyAdded+243
models/Phi-4-multimodal-instruct/special_tokens_map.jsonAdded+24
models/Phi-4-multimodal-instruct/speech-lora/adapter_config.jsonAdded+23
models/Phi-4-multimodal-instruct/speech-lora/added_tokens.jsonAdded+12
models/Phi-4-multimodal-instruct/speech-lora/special_tokens_map.jsonAdded+24
models/Phi-4-multimodal-instruct/speech-lora/tokenizer_config.jsonAdded+125
models/Phi-4-multimodal-instruct/speech-lora/vocab.jsonAdded
models/Phi-4-multimodal-instruct/speech_conformer_encoder.pyAdded
models/Phi-4-multimodal-instruct/tokenizer_config.jsonAdded+125
models/Phi-4-multimodal-instruct/vision-lora/adapter_config.jsonAdded+23
models/Phi-4-multimodal-instruct/vision-lora/added_tokens.jsonAdded+12
models/Phi-4-multimodal-instruct/vision-lora/special_tokens_map.jsonAdded+24
models/Phi-4-multimodal-instruct/vision-lora/tokenizer_config.jsonAdded+125
models/Phi-4-multimodal-instruct/vision-lora/vocab.jsonAdded
models/Phi-4-multimodal-instruct/vision_siglip_navit.pyAdded+1717
models/Phi-4-multimodal-instruct/vocab.jsonAdded
models/Pixtral-12B-2409/.gitattributesAdded+36
models/Pixtral-12B-2409/README.mdAdded+294
models/Pixtral-12B-2409/params.jsonAdded+25
models/Qwen2-VL-7B-Instruct/.gitattributesAdded+35
models/Qwen2-VL-7B-Instruct/LICENSEAdded+202
models/Qwen2-VL-7B-Instruct/README.mdAdded+502
models/Qwen2-VL-7B-Instruct/chat_template.jsonAdded+3
models/Qwen2-VL-7B-Instruct/config.jsonAdded+52
models/Qwen2-VL-7B-Instruct/generation_config.jsonAdded+14
models/Qwen2-VL-7B-Instruct/merges.txtAdded
models/Qwen2-VL-7B-Instruct/model.safetensors.index.jsonAdded+737
models/Qwen2-VL-7B-Instruct/preprocessor_config.jsonAdded+19
models/Qwen2-VL-7B-Instruct/tokenizer.jsonAdded
models/Qwen2-VL-7B-Instruct/tokenizer_config.jsonAdded+129
models/Qwen2-VL-7B-Instruct/vocab.jsonAdded
models/SmolVLM-Instruct/.gitattributesAdded+37
models/SmolVLM-Instruct/README.mdAdded+191
models/SmolVLM-Instruct/added_tokens.jsonAdded+5
models/SmolVLM-Instruct/chat_template.jsonAdded+3
models/SmolVLM-Instruct/config.jsonAdded+267
models/SmolVLM-Instruct/generation_config.jsonAdded+7
models/SmolVLM-Instruct/merges.txtAdded
models/SmolVLM-Instruct/preprocessor_config.jsonAdded+28
models/SmolVLM-Instruct/processor_config.jsonAdded+4
models/SmolVLM-Instruct/smolvlm-data.pdfAdded
models/SmolVLM-Instruct/special_tokens_map.jsonAdded+53
models/SmolVLM-Instruct/tokenizer.jsonAdded