Buckets:
LLaVA-NeXT
LLaVA‑NeXT improves on Llava by increasing the input image resolution by 4x more pixels and supporting 3 aspect ratios (up to 672x672, 336x1344, 1344x336) to better grasp visual details. It is also trained on an improved visual instruction tuning dataset covering more scenarios and applications to improve OCR and common sense reasoning.
You can find all the original LLaVA‑NeXT checkpoints under the LLaVA-NeXT collection.
This model was contributed by nielsr.
Click on the LLaVA‑NeXT models in the right sidebar for more examples of how to apply Llava-NeXT to different multimodal tasks.
The example below demonstrates how to generate text based on an image with Pipeline or the AutoModel class.
from transformers import pipeline
pipeline = pipeline(
task="image-text-to-text",
model="llava-hf/llava-v1.6-mistral-7b-hf",
device=0,
)
messages = [
{
"role": "user",
"content": [
{
"type": "image",
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
},
{ "type": "text", "text": "Describe this image."},
]
}
]
pipeline(text=messages, max_new_tokens=20, return_full_text=False)
import requests
from PIL import Image
from transformers import AutoProcessor, LlavaNextForConditionalGeneration
processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", device_map="auto")
url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
image = Image.open(requests.get(url, stream=True).raw)
conversation = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
inputs = processor(image, prompt, return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=100)
print(processor.decode(output[0], skip_special_tokens=True))
Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the Quantization overview for more available quantization backends.
The example below uses bitsandbytes to only quantize the weights to int4.
import requests
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig
quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4"
)
processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
model = AutoModelForImageTextToText.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=quant_config, device_map="auto")
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/llava_next_ocr.png"
image = Image.open(requests.get(url, stream=True).raw)
conversation = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What does this chart show?"},
],
},
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
inputs = processor(image, prompt, return_tensors="pt").to(model.device)
with torch.inference_mode():
output = model.generate(**inputs, max_new_tokens=100)
print(processor.decode(output[0], skip_special_tokens=True))
Notes
Different checkpoints (Mistral, Vicuna, etc.) require a specific prompt format depending on the underlying LLM. Always use apply_chat_template() to ensure correct formatting. Refer to the Templates guide for more details.
Set
padding_side="left"during batched generation for more accurate results.
processor.tokenizer.padding_side = "left"
LLaVA-NeXT uses different numbers of patches for images and pads the inputs inside the modeling code except when padding is done during processing. The default setting is left-padding if the model is in
eval()mode, otherwise it is right-padding.LLaVA models after v4.46 raises warnings about adding
processor.patch_size = {{patch_size}},processor.num_additional_image_tokens = {{num_additional_image_tokens}}, andprocessor.vision_feature_select_strategy = {{vision_feature_select_strategy}}. It is strongly recommended to add these attributes to the processor if you own the model checkpoint or open a PR if it isn't.Adding these attributes means LLaVA will try to infer the number of image tokens required per image and expand the text with the same number of
<image>token placeholders. There are usually ~500 tokens per image, so make sure the text is not truncated because it will cause a failure when merging the embeddings. The attributes can be found inmodel.config.vision_config.patch_sizeormodel.config.vision_feature_select_strategy.The
num_additional_image_tokensshould be1if the vision backbone adds aCLStoken or0if nothing extra is added.The example below demonstrates inference with multiple input images.
import requests
from PIL import Image
from transformers import LlavaNextForConditionalGeneration, LlavaNextProcessor
processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
model = LlavaNextForConditionalGeneration.from_pretrained(
"llava-hf/llava-v1.6-mistral-7b-hf", device_map="auto"
)
# Load multiple images
url1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/llava_next_ocr.png"
url2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/llava_next_comparison.png"
image1 = Image.open(requests.get(url1, stream=True).raw)
image2 = Image.open(requests.get(url2, stream=True).raw)
conversation = [
{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "Compare these two images and describe the differences."}]}
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
inputs = processor([image1, image2], prompt, return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=100)
print(processor.decode(output[0], skip_special_tokens=True))
LlavaNextConfig[[transformers.LlavaNextConfig]]
transformers.LlavaNextConfig[[transformers.LlavaNextConfig]]
This is the configuration class to store the configuration of a LlavaNextModel. It is used to instantiate a Llava Next model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the llava-hf/llava-v1.6-mistral-7b-hf
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import LlavaNextForConditionalGeneration, LlavaNextConfig, CLIPVisionConfig, LlamaConfig
>>> # Initializing a CLIP-vision config
>>> vision_config = CLIPVisionConfig()
>>> # Initializing a Llama config
>>> text_config = LlamaConfig()
>>> # Initializing a Llava-Next llava-hf/llava-v1.6-mistral-7b-hf style configuration
>>> configuration = LlavaNextConfig(vision_config, text_config)
>>> # Initializing a model from the llava-hf/llava-v1.6-mistral-7b-hf style configuration
>>> model = LlavaNextForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Parameters:
vision_config (Union[dict, ~configuration_utils.PreTrainedConfig], optional) : The config object or dictionary of the vision backbone.
text_config (Union[dict, ~configuration_utils.PreTrainedConfig], optional) : The config object or dictionary of the text backbone.
image_token_index (int, optional, defaults to 32000) : The image token index used as a placeholder for input images.
projector_hidden_act (str, optional, defaults to gelu) : The activation function used by the multimodal projector.
vision_feature_select_strategy (Literal[default, full], optional, defaults to default) : The feature selection strategy used to select the vision feature from the vision backbone.
vision_feature_layer (Union[int, list[int]], optional, defaults to -2) : The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.
multimodal_projector_bias (bool, optional, defaults to True) : Whether to use bias in the multimodal projector.
tie_word_embeddings (bool, optional, defaults to False) : Whether to tie weight embeddings according to model's tied_weights_keys mapping.
image_grid_pinpoints (List, optional, defaults to [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]) : A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list of the form (height, width).
image_seq_length (int, optional, defaults to 576) : Sequence length of one image embedding.
LlavaNextImageProcessor[[transformers.LlavaNextImageProcessor]]
transformers.LlavaNextImageProcessor[[transformers.LlavaNextImageProcessor]]
Constructs a LlavaNextImageProcessor image processor.
preprocesstransformers.LlavaNextImageProcessor.preprocesshttps://github.com/huggingface/transformers/blob/vr_43265/src/transformers/models/llava_next/image_processing_llava_next.py#L74[{"name": "images", "val": ": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]]"}, {"name": "*args", "val": ""}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessorKwargs]"}]- images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]]) --
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.
- image_grid_pinpoints (
list[list[int]], kwargs, optional) -- A list of possible resolutions to use for processing high resolution images. The best resolution is selected based on the original size of the image. Can be overridden byimage_grid_pinpointsin thepreprocessmethod. - return_tensors (
stror TensorType, optional) -- Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - **kwargs (ImagesKwargs, optional) --
Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class
for the complete list of supported arguments.0
~image_processing_base.BatchFeature- data (dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
Parameters:
image_grid_pinpoints (list[list[int]], kwargs, optional) : A list of possible resolutions to use for processing high resolution images. The best resolution is selected based on the original size of the image. Can be overridden by image_grid_pinpoints in the preprocess method.
- **kwargs (ImagesKwargs, optional) : Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Returns:
~image_processing_base.BatchFeature
- data (
dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
LlavaNextImageProcessorPil[[transformers.LlavaNextImageProcessorPil]]
transformers.LlavaNextImageProcessorPil[[transformers.LlavaNextImageProcessorPil]]
Constructs a LlavaNextImageProcessor image processor.
preprocesstransformers.LlavaNextImageProcessorPil.preprocesshttps://github.com/huggingface/transformers/blob/vr_43265/src/transformers/models/llava_next/image_processing_pil_llava_next.py#L71[{"name": "images", "val": ": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]]"}, {"name": "*args", "val": ""}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.models.llava_next.image_processing_pil_llava_next.LlavaNextImageProcessorKwargs]"}]- images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]]) --
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.
- image_grid_pinpoints (
list[list[int]], kwargs, optional) -- A list of possible resolutions to use for processing high resolution images. The best resolution is selected based on the original size of the image. Can be overridden byimage_grid_pinpointsin thepreprocessmethod. - return_tensors (
stror TensorType, optional) -- Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - **kwargs (ImagesKwargs, optional) --
Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class
for the complete list of supported arguments.0
~image_processing_base.BatchFeature- data (dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
Parameters:
image_grid_pinpoints (list[list[int]], kwargs, optional) : A list of possible resolutions to use for processing high resolution images. The best resolution is selected based on the original size of the image. Can be overridden by image_grid_pinpoints in the preprocess method.
- **kwargs (ImagesKwargs, optional) : Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Returns:
~image_processing_base.BatchFeature
- data (
dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
LlavaNextProcessor[[transformers.LlavaNextProcessor]]
transformers.LlavaNextProcessor[[transformers.LlavaNextProcessor]]
Constructs a LlavaNextProcessor which wraps a image processor and a tokenizer into a single processor.
LlavaNextProcessor offers all the functionalities of LlavaNextImageProcessor and TokenizersBackend. See the ~LlavaNextImageProcessor and ~TokenizersBackend for more information.
__call__transformers.LlavaNextProcessor.__call__https://github.com/huggingface/transformers/blob/vr_43265/src/transformers/models/llava_next/processing_llava_next.py#L82[{"name": "images", "val": ": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None"}, {"name": "text", "val": ": str | list[str] | list[list[str]] = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.models.llava_next.processing_llava_next.LlavaNextProcessorKwargs]"}]- images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], optional) --
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.
text (
Union[str, list[str], list[list[str]]], optional) -- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, setis_split_into_words=Trueto avoid ambiguity with batched inputs.return_tensors (
stror TensorType, optional) -- If set, will return tensors of a particular framework. Acceptable values are:'pt': Return PyTorchtorch.Tensorobjects.'np': Return NumPynp.ndarrayobjects.
**kwargs (ProcessingKwargs, optional) -- Additional processing options for each modality (text, images, videos, audio). Model-specific parameters are listed above; see the TypedDict class for the complete list of supported arguments.0BatchFeatureA BatchFeature with the following fields:
input_ids -- List of token ids to be fed to a model. Returned when
textis notNone.attention_mask -- List of indices specifying which tokens should be attended to by the model (when
return_attention_mask=Trueor if "attention_mask" is inself.model_input_namesand iftextis notNone).pixel_values -- Pixel values to be fed to a model. Returned when
imagesis notNone.
Parameters:
image_processor (LlavaNextImageProcessor) : The image processor is a required input.
tokenizer (TokenizersBackend) : The tokenizer is a required input.
patch_size (int, optional) : Patch size from the vision tower.
vision_feature_select_strategy (str, optional) : The feature selection strategy used to select the vision feature from the vision backbone. Should be same as in model's config
chat_template (str) : A Jinja template to convert lists of messages in a chat into a tokenizable string.
image_token (str, optional, defaults to "<image>") : Special token used to denote image location.
num_additional_image_tokens (int, optional, defaults to 0) : Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other extra tokens appended, no need to set this arg.
Returns:
[BatchFeature](/docs/transformers/pr_43265/en/main_classes/feature_extractor#transformers.BatchFeature)
A BatchFeature with the following fields:
- input_ids -- List of token ids to be fed to a model. Returned when
textis notNone. - attention_mask -- List of indices specifying which tokens should be attended to by the model (when
return_attention_mask=Trueor if "attention_mask" is inself.model_input_namesand iftextis notNone). - pixel_values -- Pixel values to be fed to a model. Returned when
imagesis notNone.
LlavaNextModel[[transformers.LlavaNextModel]]
transformers.LlavaNextModel[[transformers.LlavaNextModel]]
The Llava-Next model which consists of a vision backbone and a language model without language modeling head.
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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.LlavaNextModel.forwardhttps://github.com/huggingface/transformers/blob/vr_43265/src/transformers/models/llava_next/modeling_llava_next.py#L431[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "pixel_values", "val": ": torch.FloatTensor | None = None"}, {"name": "image_sizes", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "vision_feature_layer", "val": ": int | list[int] | None = None"}, {"name": "vision_feature_select_strategy", "val": ": str | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs]"}]- input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) -- The tensors corresponding to the input images. Pixel values can be obtained using LlavaNextImageProcessor. SeeLlavaNextImageProcessor.__call__()for details (LlavaNextProcessor uses LlavaNextImageProcessor for processing images).image_sizes (
torch.LongTensorof shape(batch_size, 2), optional) -- The sizes of the images in the batch, being (height, width) for each image.attention_mask (
torch.Tensorof 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.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].past_key_values (
~cache_utils.Cache, optional) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don't have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length).inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) -- Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model's internal embedding lookup matrix.vision_feature_layer (
Union[int, list[int]], optional) -- The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.vision_feature_select_strategy (
str, optional, defaults to"default") -- The feature selection strategy used to select the vision feature from the vision backbone. Can be one of"default"or"full". If"default", the CLS token is removed from the vision features. If"full", the full vision features are used.use_cache (
bool, optional) -- If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).0LlavaNextModelOutputWithPastortuple(torch.FloatTensor)ALlavaNextModelOutputWithPastor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (LlavaNextConfig) and inputs. The LlavaNextModel forward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.past_key_values (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) -- It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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_hidden_states (
torch.FloatTensor, optional) -- Atorch.FloatTensorof size(batch_size, num_images, sequence_length, hidden_size). image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
Parameters:
config (LlavaNextConfig) : 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 from_pretrained() method to load the model weights.
Returns:
LlavaNextModelOutputWithPast` or `tuple(torch.FloatTensor)
A LlavaNextModelOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LlavaNextConfig) and inputs.
get_image_features[[transformers.LlavaNextModel.get_image_features]]
Obtains image last hidden states from the vision tower and apply multimodal projection.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size)) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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.
Parameters:
pixel_values (torch.FloatTensor] of shape (batch_size, num_patches, channels, height, width)) : The tensors corresponding to the input images.
image_sizes (torch.Tensor of shape (num_images, 2)) : Actual image size of each images (H, W).
vision_feature_layer (Union[int, list[int]], optional) : The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.
image_sizes (torch.Tensor of shape (batch_size, 2)) : The sizes of the images in the batch, being (height, width) for each image.
vision_feature_layer (Union[int, list[int]], optional) : The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.
vision_feature_select_strategy (str, optional) : The feature selection strategy used to select the vision feature from the vision backbone. Can be one of "default" or "full"
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.
Returns:
[BaseModelOutputWithPooling](/docs/transformers/pr_43265/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or tuple(torch.FloatTensor)``
A BaseModelOutputWithPooling or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LlavaNextConfig) and inputs.
get_placeholder_mask[[transformers.LlavaNextModel.get_placeholder_mask]]
Obtains multimodal placeholder mask from input_ids or inputs_embeds, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
pack_image_features[[transformers.LlavaNextModel.pack_image_features]]
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
Parameters:
image_features (list[torch.Tensor] of length num_images, each of shape (num_patches, image_length, embed_dim)) : List of image feature tensor, each contains all the visual feature of all patches.
image_sizes (torch.Tensor of shape (num_images, 2)) : Actual image size of each images (H, W).
vision_feature_select_strategy (str) : The feature selection strategy used to select the vision feature from the vision backbone.
image_newline (torch.Tensor of shape (embed_dim)) : New line embedding vector.
Returns:
image_features (torch.Tensor of shape (all_feat_len, embed_dim))
feature_lens (list[int])
token length of each image in image_features
LlavaNextForConditionalGeneration[[transformers.LlavaNextForConditionalGeneration]]
transformers.LlavaNextForConditionalGeneration[[transformers.LlavaNextForConditionalGeneration]]
The LLAVA-NeXT model which consists of a vision backbone and a language model.
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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.LlavaNextForConditionalGeneration.forwardhttps://github.com/huggingface/transformers/blob/vr_43265/src/transformers/models/llava_next/modeling_llava_next.py#L549[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "pixel_values", "val": ": torch.FloatTensor | None = None"}, {"name": "image_sizes", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "vision_feature_layer", "val": ": int | list[int] | None = None"}, {"name": "vision_feature_select_strategy", "val": ": str | None = None"}, {"name": "labels", "val": ": torch.LongTensor | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "logits_to_keep", "val": ": int | torch.Tensor = 0"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) -- The tensors corresponding to the input images. Pixel values can be obtained using LlavaNextImageProcessor. SeeLlavaNextImageProcessor.__call__()for details (LlavaNextProcessor uses LlavaNextImageProcessor for processing images).image_sizes (
torch.LongTensorof shape(batch_size, 2), optional) -- The sizes of the images in the batch, being (height, width) for each image.attention_mask (
torch.Tensorof 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.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].past_key_values (
~cache_utils.Cache, optional) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don't have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length).inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) -- Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model's internal embedding lookup matrix.vision_feature_layer (
Union[int, list[int]], optional) -- The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.vision_feature_select_strategy (
str, optional, defaults to"default") -- The feature selection strategy used to select the vision feature from the vision backbone. Can be one of"default"or"full". If"default", the CLS token is removed from the vision features. If"full", the full vision features are used.labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].use_cache (
bool, optional) -- If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) -- If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).0LlavaNextCausalLMOutputWithPastortuple(torch.FloatTensor)ALlavaNextCausalLMOutputWithPastor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (LlavaNextConfig) and inputs. The LlavaNextForConditionalGeneration forward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Language modeling loss (for next-token prediction).logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) -- It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple[torch.FloatTensor], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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_hidden_states (
torch.FloatTensor, optional) -- Atorch.FloatTensorof size (batch_size * num_patches, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
Example:
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration
>>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> prompt = "[INST] \nWhat is shown in this image? [/INST]"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
Parameters:
config (LlavaNextConfig) : 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 from_pretrained() method to load the model weights.
Returns:
LlavaNextCausalLMOutputWithPast` or `tuple(torch.FloatTensor)
A LlavaNextCausalLMOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LlavaNextConfig) and inputs.
get_image_features[[transformers.LlavaNextForConditionalGeneration.get_image_features]]
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size)) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.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.
Example:
>>> from PIL import Image
>>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration
>>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Parameters:
pixel_values (torch.FloatTensor] of shape (batch_size, num_patches, channels, height, width)) : The tensors corresponding to the input images.
image_sizes (torch.Tensor of shape (num_images, 2)) : Actual image size of each images (H, W).
vision_feature_layer (Union[int, list[int]], optional) : The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.
image_sizes (torch.Tensor of shape (batch_size, 2)) : The sizes of the images in the batch, being (height, width) for each image.
vision_feature_layer (Union[int, list[int]], optional) : The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.
vision_feature_select_strategy (str, optional) : The feature selection strategy used to select the vision feature from the vision backbone. Can be one of "default" or "full"
Returns:
[BaseModelOutputWithPooling](/docs/transformers/pr_43265/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or tuple(torch.FloatTensor)``
A BaseModelOutputWithPooling or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LlavaNextConfig) and inputs.
Xet Storage Details
- Size:
- 53.8 kB
- Xet hash:
- eba0c4f61f6c174e89b1b40c36ea8b3a3d779a8b71ff293d51083d99c7fc0a1e
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.