Transformers documentation
Granite4Vision
This model was released on 2026-03-27 and added to Hugging Face Transformers on 2026-05-05.
Granite4Vision
Granite Vision 4.1 is a vision-language model from IBM Research designed for enterprise-grade document data extraction. It specializes in chart extraction (Chart2CSV, Chart2Summary, Chart2Code), table extraction (JSON, HTML, OTSL), and semantic key-value pair extraction.
The model builds on LLaVA-NeXT with several architectural innovations:
- SigLIP2 Vision Encoder (
google/siglip2-so400m-patch16-384): images are tiled into 384x384 patches. - Window Q-Former Projectors: compress visual features 4x using windowed cross-attention over 4x4 patch windows into 2x2 tokens.
- DeepStack Feature Injection with 8 vision-to-LLM injection points:
- LayerDeepstack: features from 4 vision encoder depths are projected into different early LLM layers.
- SpatialDeepstack: deepest vision features are split into 4 spatial groups and injected at later LLM layers.
- Language Model: Granite 4.1 (4B params) with LoRA adapters (rank 256) across all self-attention and MLP layers.
The model is delivered as a LoRA adapter on top of the base LLM, enabling single deployments to support both multimodal and text-only workloads. Total parameter count is ~4B.
This model was contributed by the IBM Granite Vision Team.
Usage Tips
- Set
padding_side="left"during batched generation for more accurate results.
processor.tokenizer.padding_side = "left"The model supports specialized task tags for document extraction:
<chart2csv>,<chart2summary>,<chart2code>,<tables_html>,<tables_otsl>,<tables_json>. Pass these as the text prompt along with a document image.For key-value pair extraction, provide a JSON schema describing the fields to extract. The model returns structured JSON matching the schema.
The example below demonstrates how to generate text based on an image with Pipeline or the AutoModel class.
from transformers import pipeline
pipe = pipeline(
task="image-text-to-text",
model="ibm-granite/granite-vision-4.1-4b",
)
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."},
],
}
]
pipe(text=messages, max_new_tokens=100, return_full_text=False)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 torch
from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_quant_type="nf4",
)
model_id = "ibm-granite/granite-vision-4.1-4b"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(
model_id, quantization_config=quant_config, device_map="auto"
)
conversation = [
{
"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."},
],
},
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
output = model.generate(**inputs, max_new_tokens=100)
print(processor.decode(output[0], skip_special_tokens=True))Granite4VisionConfig
class transformers.Granite4VisionConfig
< source >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None image_token_index: int = 32000 vision_feature_select_strategy: typing.Literal['default', 'full'] = 'default' vision_feature_layer: int | list[int] = -2 tie_word_embeddings: bool = False image_grid_pinpoints: list | None = None image_seq_length: int = 576 downsample_rate: str | None = None deepstack_layer_map: list | None = None spatial_vision_layer: int = -1 spatial_target_layers: list | None = None projector_dropout: float = 0.1 qformer_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )
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 to32000) — The image token index used as a placeholder for input images. - vision_feature_select_strategy (
Literal[default, full], optional, defaults todefault) — 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. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - image_grid_pinpoints (
list, optional) — 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 to576) — Sequence length of one image embedding. - downsample_rate (
str, optional) — Fractional downsample rate for the Window Q-Former projector, e.g."1/4"or"3/8". The numerator is the query window side, the denominator is the key window side. - deepstack_layer_map (
list, optional) — List of[vision_layer_idx, llm_layer_idx]pairs. Features from each vision encoder layer are projected and injected at the corresponding LLM decoder layer during forward pass. - spatial_vision_layer (
int, optional, defaults to-1) — Index of the vision encoder layer used for spatial sampling. - spatial_target_layers (
list, optional, defaults to[12, 15, 18, 21]) — Target LLM layers for the 4 spatial offset groups. - projector_dropout (
float, optional, defaults to0.1) — Dropout probability in the Window Q-Former projector. - qformer_config (
dictorBlip2QFormerConfig, optional) — Configuration for the Window Q-Former projector. IfNone, defaults are derived fromvision_config.hidden_size.
This is the configuration class to store the configuration of a Granite4VisionModel. It is used to instantiate a Granite4 Vision 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.
Granite4VisionTextConfig
class transformers.Granite4VisionTextConfig
< source >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None vocab_size: int = 32000 hidden_size: int = 4096 intermediate_size: int = 11008 num_hidden_layers: int = 32 num_attention_heads: int = 32 num_key_value_heads: int | None = None hidden_act: str = 'silu' max_position_embeddings: int = 2048 initializer_range: float = 0.02 rms_norm_eps: float = 1e-06 use_cache: bool = True pad_token_id: int | None = None bos_token_id: int | None = 1 eos_token_id: int | list[int] | None = 2 tie_word_embeddings: bool = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None attention_bias: bool = False attention_dropout: float | int = 0.0 mlp_bias: bool = False embedding_multiplier: float | int = 1.0 logits_scaling: float | int = 1.0 residual_multiplier: float | int = 1.0 attention_multiplier: float | int = 1.0 )
Parameters
- vocab_size (
int, optional, defaults to32000) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to4096) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to11008) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to32) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to32) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - hidden_act (
str, optional, defaults tosilu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to2048) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to1e-06) — The epsilon used by the rms normalization layers. - use_cache (
bool, optional, defaults toTrue) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - pad_token_id (
int, optional) — Token id used for padding in the vocabulary. - bos_token_id (
int, optional, defaults to1) — Token id used for beginning-of-stream in the vocabulary. - eos_token_id (
Union[int, list[int]], optional, defaults to2) — Token id used for end-of-stream in the vocabulary. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - attention_bias (
bool, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - mlp_bias (
bool, optional, defaults toFalse) — Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers. - embedding_multiplier (
Union[float, int], optional, defaults to1.0) — Scaling factor applied to the word embeddings. Used to scale the embeddings relative to the hidden size. - logits_scaling (
Union[float, int], optional, defaults to1.0) — Scaling factor applied to the output logits before computing the probability distribution. - residual_multiplier (
Union[float, int], optional, defaults to1.0) — Scaling factor applied to the residual connections. - attention_multiplier (
Union[float, int], optional, defaults to1.0) — Scaling factor applied to the attention weights.
This is the configuration class to store the configuration of a Granite4VisionModel. It is used to instantiate a Granite4 Vision 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 ibm-granite4_vision_text/granite4_vision_text-3.0-8b-base
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
>>> from transformers import Granite4VisionTextModel, Granite4VisionTextConfig
>>> # Initializing a Granite4VisionText granite4_vision_text-3b style configuration
>>> configuration = Granite4VisionTextConfig()
>>> # Initializing a model from the granite4_vision_text-7b style configuration
>>> model = Granite4VisionTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configGranite4VisionProcessor
class transformers.Granite4VisionProcessor
< source >( image_processor = None tokenizer = None patch_size = None vision_feature_select_strategy = None chat_template = None image_token = '<image>' num_additional_image_tokens = 0 downsample_rate = None **kwargs )
Parameters
- image_processor (
LlavaNextImageProcessor) — The image processor is a required input. - tokenizer (
tokenizer_class) — 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 to0) — Number of additional tokens added to the image embeddings, such as CLS (+1). - downsample_rate (
str, optional) — Fractional downsample rate (e.g."1/4"), used to adjust the number of image tokens when computing token counts for padding/truncation.
Constructs a Granite4VisionProcessor which wraps a image processor and a tokenizer into a single processor.
Granite4VisionProcessor offers all the functionalities of LlavaNextImageProcessor and tokenizer_class. See the
~LlavaNextImageProcessor and ~tokenizer_class for more information.
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None text: str | list[str] | list[list[str]] = None **kwargs: typing_extensions.Unpack[transformers.models.granite4_vision.processing_granite4_vision.Granite4VisionProcessorKwargs] ) → BatchFeature
Parameters
- 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, setdo_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.
Returns
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.
Granite4VisionModel
class transformers.Granite4VisionModel
< source >( config: Granite4VisionConfig )
Parameters
- config (Granite4VisionConfig) — 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.
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.
forward
< source >( input_ids: torch.LongTensor | None = None pixel_values: torch.FloatTensor | None = None image_sizes: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None vision_feature_layer: int | list[int] | None = None vision_feature_select_strategy: str | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → Granite4VisionModelOutputWithPast or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensorof 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 (Granite4VisionProcessor 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).
Returns
Granite4VisionModelOutputWithPast or tuple(torch.FloatTensor)
A Granite4VisionModelOutputWithPast 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 (Granite4VisionConfig) and inputs.
The Granite4VisionModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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), optional) — Sequence of hidden-states at the output of the last layer of the model.past_key_values (
~cache_utils.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 and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seepast_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.FloatTensorof shape(batch_size, num_images, sequence_length, hidden_size), optional, defaults toNone) — Image hidden states of the model produced by the vision encoder and after projecting the last hidden state.deepstack_features (
list[tuple[int, list[torch.Tensor]]], optional) — List of(llm_layer_idx, packed_features)pairs produced by the deepstack and spatial projectors. Each entry targets one LLM decoder layer;packed_featuresis a per-image list of tensors of shape(num_image_tokens, hidden_size).
get_image_features
< source >( pixel_values: FloatTensor image_sizes: Tensor vision_feature_layer: int | list[int] | None = None vision_feature_select_strategy: str | None = None output_hidden_states: bool | None = None **kwargs ) → Granite4VisionImageFeaturesOutput or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensor]of shape(batch_size, num_patches, channels, height, width)) — The tensors corresponding to the input images. - image_sizes (
torch.Tensorof 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.Tensorof 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. Seehidden_statesunder returned tensors for more detail.
Returns
Granite4VisionImageFeaturesOutput or tuple(torch.FloatTensor)
A Granite4VisionImageFeaturesOutput 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 (Granite4VisionConfig) and inputs.
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), optional) — Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size), optional) — Last layer hidden-state after a pooling operation on the spatial dimensions.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.
deepstack_features (
list[tuple[int, list[torch.Tensor]]], optional) — List of(llm_layer_idx, packed_features)pairs produced by the deepstack and spatial projectors. Each entry targets one LLM decoder layer;packed_featuresis a per-image list of tensors of shape(num_image_tokens, hidden_size).
get_placeholder_mask
< source >( input_ids: LongTensor inputs_embeds: FloatTensor image_features: FloatTensor )
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
< source >( image_features image_sizes vision_feature_select_strategy image_newline = None )
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
Overrides the parent to apply downsample_rate to height/width calculations.
Granite4VisionTextModel
class transformers.Granite4VisionTextModel
< source >( config: Granite4VisionTextConfig )
Parameters
- config (Granite4VisionTextConfig) — 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.
The bare Granite4 Vision Text Model outputting raw hidden-states without any specific head on to.
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.
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None vision_mask: torch.BoolTensor | None = None deepstack_features: dict[int, torch.Tensor] | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutputWithPast or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensorof 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.
- 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. - 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). - vision_mask (
torch.BoolTensorof shape(batch_size, sequence_length, hidden_size), optional) — Boolean mask marking image token positions. Required whendeepstack_featuresis provided. - deepstack_features (
dict[int, torch.Tensor], optional) — Mapping from LLM layer index to projected vision features of shape(num_image_tokens, hidden_size). Features are added into image-token positions of hidden states before the corresponding decoder layer.
Returns
BaseModelOutputWithPast or tuple(torch.FloatTensor)
A BaseModelOutputWithPast 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 (Granite4VisionConfig) and inputs.
The Granite4VisionTextModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seepast_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.
Granite4VisionForConditionalGeneration
class transformers.Granite4VisionForConditionalGeneration
< source >( config: Granite4VisionConfig )
Parameters
- config (Granite4VisionConfig) — 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.
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.
forward
< source >( input_ids: torch.LongTensor | None = None pixel_values: torch.FloatTensor | None = None image_sizes: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None vision_feature_layer: int | list[int] | None = None vision_feature_select_strategy: str | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → Granite4VisionCausalLMOutputWithPast or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensorof 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 (Granite4VisionProcessor 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).
Returns
Granite4VisionCausalLMOutputWithPast or tuple(torch.FloatTensor)
A Granite4VisionCausalLMOutputWithPast 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 (Granite4VisionConfig) and inputs.
The Granite4VisionForConditionalGeneration forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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_utils.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 and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seepast_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.FloatTensorof shape(batch_size, num_images, sequence_length, hidden_size), optional, defaults toNone) — Image hidden states of the model produced by the vision encoder and after projecting the last hidden state.deepstack_features (
list[tuple[int, list[torch.Tensor]]], optional) — List of(llm_layer_idx, packed_features)pairs produced by the deepstack and spatial projectors. Each entry targets one LLM decoder layer;packed_featuresis a per-image list of tensors of shape(num_image_tokens, hidden_size).
Example:
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, Granite4VisionForConditionalGeneration
>>> model = Granite4VisionForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
>>> prompt = "[INST] <image>\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 (...)"get_image_features
< source >( pixel_values: FloatTensor image_sizes: Tensor vision_feature_layer: int | list[int] | None = None vision_feature_select_strategy: str | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensor]of shape(batch_size, num_patches, channels, height, width)) — The tensors corresponding to the input images. - image_sizes (
torch.Tensorof 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.Tensorof 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 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 (Granite4VisionConfig) and inputs.
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, Granite4VisionForConditionalGeneration
>>> model = Granite4VisionForConditionalGeneration.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]