#
Mistral3

##
Overview

Building upon Mistral Small 3 (2501), Mistral Small 3.1 (2503) adds state-of-the-art vision understanding and enhances long context capabilities up to 128k tokens without compromising text performance. With 24 billion parameters, this model achieves top-tier capabilities in both text and vision tasks.

It is ideal for:

- Fast-response conversational agents.
- Low-latency function calling.
- Subject matter experts via fine-tuning.
- Local inference for hobbyists and organizations handling sensitive data.
- Programming and math reasoning.
- Long document understanding.
- Visual understanding.

This model was contributed by cyrilvallez and yonigozlan.

The original code can be found here and here.

##
Usage example

###
Inference with Pipeline

Here is how you can use the `image-text-to-text` pipeline to perform inference with the `Mistral3` models in just a few lines of code:

    >>> from transformers import pipeline

    >>> messages = [
    ...     {
    ...         "role": "user",
    ...         "content": [
    ...             {
    ...                 "type": "image",
    ...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
    ...             },
    ...             {"type": "text", "text": "Describe this image."},
    ...         ],
    ...     },
    ... ]

    >>> pipe = pipeline("image-text-to-text", model="mistralai/Mistral-Small-3.1-24B-Instruct-2503", torch_dtype=torch.bfloat16)
    >>> outputs = pipe(text=messages, max_new_tokens=50, return_full_text=False)
    >>> outputs[0]["generated_text"]
    'The image depicts a vibrant and lush garden scene featuring a variety of wildflowers and plants. The central focus is on a large, pinkish-purple flower, likely a Greater Celandine (Chelidonium majus), with a'

###
Inference on a single image

This example demonstrates how to perform inference on a single image with the Mistral3 models using chat templates.

    >>> from transformers import AutoProcessor, AutoModelForImageTextToText
    >>> import torch

    >>> torch_device = "cuda"
    >>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
    >>> processor = AutoProcessor.from_pretrained(model_checkpoint)
    >>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

    >>> messages = [
    ...     {
    ...         "role": "user",
    ...         "content": [
    ...             {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
    ...             {"type": "text", "text": "Describe this image"},
    ...         ],
    ...     }
    ... ]

    >>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

    >>> generate_ids = model.generate(**inputs, max_new_tokens=20)
    >>> decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)

    >>> decoded_output
    "The image depicts two cats lying on a pink blanket. The larger cat, which appears to be an"...

###
Text-only generation

This example shows how to generate text using the Mistral3 model without providing any image input.

    >>> from transformers import AutoProcessor, AutoModelForImageTextToText
    >>> import torch

    >>> torch_device = "cuda"
    >>> model_checkpoint = ".mistralai/Mistral-Small-3.1-24B-Instruct-2503"
    >>> processor = AutoProcessor.from_pretrained(model_checkpoint)
    >>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

    >>> SYSTEM_PROMPT = "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat."
    >>> user_prompt = "Give me 5 non-formal ways to say 'See you later' in French."

    >>> messages = [
    ...    {"role": "system", "content": SYSTEM_PROMPT},
    ...    {"role": "user", "content": user_prompt},
    ... ]

    >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    >>> inputs = processor(text=text, return_tensors="pt").to(0, dtype=torch.float16)
    >>> generate_ids = model.generate(**inputs, max_new_tokens=50, do_sample=False)
    >>> decoded_output = processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)[0]

    >>> print(decoded_output)
    "1. À plus tard!
    2. Salut, à plus!
    3. À toute!
    4. À la prochaine!
    5. Je me casse, à plus!

    ```
     /\_/\
    ( o.o )
     > ^ <
    ```"

###
Batched image and text inputs

Mistral3 models also support batched image and text inputs.

    >>> from transformers import AutoProcessor, AutoModelForImageTextToText
    >>> import torch

    >>> torch_device = "cuda"
    >>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
    >>> processor = AutoProcessor.from_pretrained(model_checkpoint)
    >>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

    >>> messages = [
    ...     [
    ...         {
    ...             "role": "user",
    ...             "content": [
    ...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"},
    ...                 {"type": "text", "text": "Write a haiku for this image"},
    ...             ],
    ...         },
    ...     ],
    ...     [
    ...         {
    ...             "role": "user",
    ...             "content": [
    ...                 {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
    ...                 {"type": "text", "text": "Describe this image"},
    ...             ],
    ...         },
    ...     ],
    ... ]

    >>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

    >>> output = model.generate(**inputs, max_new_tokens=25)

    >>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
    >>> decoded_outputs
    ["Write a haiku for this imageCalm waters reflect\nWhispers of the forest's breath\nPeace on wooden path"
    , "Describe this imageThe image depicts a vibrant street scene in what appears to be a Chinatown district. The focal point is a traditional Chinese"]

###
Batched multi-image input and quantization with BitsAndBytes

This implementation of the Mistral3 models supports batched text-images inputs with different number of images for each text. This example also how to use `BitsAndBytes` to load the model in 4bit quantization.

    >>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
    >>> import torch

    >>> torch_device = "cuda"
    >>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
    >>> processor = AutoProcessor.from_pretrained(model_checkpoint)
    >>> quantization_config = BitsAndBytesConfig(load_in_4bit=True)
    >>> model = AutoModelForImageTextToText.from_pretrained(
    ...     model_checkpoint, quantization_config=quantization_config
    ... )

    >>> messages = [
    ...     [
    ...         {
    ...             "role": "user",
    ...             "content": [
    ...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"},
    ...                 {"type": "text", "text": "Write a haiku for this image"},
    ...             ],
    ...         },
    ...     ],
    ...     [
    ...         {
    ...             "role": "user",
    ...             "content": [
    ...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"},
    ...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"},
    ...                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"},
    ...             ],
    ...         },
    ...     ],
    >>> ]

    >>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

    >>> output = model.generate(**inputs, max_new_tokens=25)

    >>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
    >>> decoded_outputs
    ["Write a haiku for this imageSure, here is a haiku inspired by the image:\n\nCalm lake's wooden path\nSilent forest stands guard\n", "These images depict two different landmarks. Can you identify them? Certainly! The images depict two iconic landmarks:\n\n1. The first image shows the Statue of Liberty in New York City."]

##
Mistral3Config

###
class transformers.Mistral3Config

< source >

( vision_config = None text_config = None image_token_index = 10 projector_hidden_act = 'gelu' vision_feature_layer = -1 multimodal_projector_bias = False spatial_merge_size = 2 **kwargs )

Parameters

- vision_config (`Union[AutoConfig, dict]`, optional, defaults to `PixtralVisionConfig`) — The config object or dictionary of the vision backbone.
- text_config (`Union[AutoConfig, dict]`, optional, defaults to `MistralConfig`) — The config object or dictionary of the text backbone.
- image_token_index (`int`, optional, defaults to 10) — The image token index to encode the image prompt.
- projector_hidden_act (`str`, optional, defaults to `"gelu"`) — The activation function used by the multimodal projector.
- vision_feature_layer (`Union[int, List[int]]`, optional, defaults to -1) — 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 `False`) — Whether to use bias in the multimodal projector.
- spatial_merge_size (`int`, optional, defaults to 2) — The downsampling factor for the spatial merge operation.

This is the configuration class to store the configuration of a Mistral3ForConditionalGeneration. It is used to instantiate an Mistral3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of mistralai/Mistral-Small-3.1-24B-Instruct-2503

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 Mistral3ForConditionalGeneration, Mistral3Config, PixtralVisionConfig, MistralConfig

    >>> # Initializing a Pixtral-vision config
    >>> vision_config = PixtralVisionConfig()

    >>> # Initializing a Mistral config
    >>> text_config = MistralConfig()

    >>> # Initializing a Mistral3 configuration
    >>> configuration = Mistral3Config(vision_config, text_config)

    >>> # Initializing a model from the mistral3.1 configuration
    >>> model = Mistral3ForConditionalGeneration(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config

##
Mistral3ForConditionalGeneration

###
class transformers.Mistral3ForConditionalGeneration

< source >

( config: Mistral3Config )

Parameters

- config (Mistral3Config or `Mistral3VisionConfig`) — 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 MISTRAL3 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: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, typing.List[int], NoneType] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 image_sizes: typing.Optional[torch.Tensor] = None **lm_kwargs ) →
`transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPast` or `tuple(torch.FloatTensor)`

Parameters

- 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?

- pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)) -- The tensors corresponding to the input images. Pixel values can be obtained using [AutoImageProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor). See [CLIPImageProcessor.__call__()](/docs/transformers/main/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) for details ([]`Mistral3Processor`] uses CLIPImageProcessor for processing images).
- 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?

  Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

  If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  If you want to change padding behavior, you should read `modeling_opt._prepare_decoder_attention_mask` and modify to your needs. See diagram 1 in the paper for more information on the default strategy.

  - 1 indicates the head is not masked,
  - 0 indicates the head is masked.
- 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.n_positions - 1]`. What are position IDs?
- past_key_values (`tuple(tuple(torch.FloatTensor))`, optional, returned when `use_cache=True` is passed or when `config.use_cache=True`) — Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

  Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

  If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.

- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, optional) — 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.
- 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.
- 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"`.
- use_cache (`bool`, optional) — If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
- 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 ModelOutput instead of a plain tuple.
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
- labels (`torch.LongTensor` of 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 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
- logits_to_keep (`int` or `torch.Tensor`, optional) — If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_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 a `torch.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

`transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPast` or `tuple(torch.FloatTensor)`

A `transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPast` 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 (Mistral3Config) and inputs.

- loss (`torch.FloatTensor` of shape `(1,)`, optional, returned when `labels` is provided) — Language modeling loss (for next-token prediction).

- logits (`torch.FloatTensor` of 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 (`tuple(tuple(torch.FloatTensor))`, optional, returned when `use_cache=True` is passed or when `config.use_cache=True`) — Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

  Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

- 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_hidden_states (`torch.FloatTensor`, optional) — A `torch.FloatTensor` of 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.

The Mistral3ForConditionalGeneration 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.

Example:

    >>> from PIL import Image
    >>> import requests
    >>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration

    >>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
    >>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")

    >>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
    >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
    >>> image = Image.open(requests.get(url, stream=True).raw)

    >>> inputs = processor(images=image, text=prompt, return_tensors="pt")

    >>> # Generate
    >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
    >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
    "What is the image?The image depicts two cats lying on a pink blanket."

< > Update on GitHub