#
Pixtral

##
Overview

The Pixtral model was released by the Mistral AI team in a blog post. Pixtral is a multimodal version of Mistral, incorporating a 400 million parameter vision encoder trained from scratch.

The intro from the blog says the following:

Pixtral is trained to understand both natural images and documents, achieving 52.5% on the MMMU reasoning benchmark, surpassing a number of larger models. The model shows strong abilities in tasks such as chart and figure understanding, document question answering, multimodal reasoning and instruction following. Pixtral is able to ingest images at their natural resolution and aspect ratio, giving the user flexibility on the number of tokens used to process an image. Pixtral is also able to process any number of images in its long context window of 128K tokens. Unlike previous open-source models, Pixtral does not compromise on text benchmark performance to excel in multimodal tasks.

Pixtral architecture. Taken from the blog post.

Tips:

- Pixtral is a multimodal model, taking images and text as input, and producing text as output.
- This model follows the Llava architecture. The model uses PixtralVisionModel for its vision encoder, and MistralForCausalLM for its language decoder.
- The main contribution is the 2d ROPE (rotary position embeddings) on the images, and support for arbitrary image sizes (the images are not padded together nor are they resized).
- Similar to Llava, the model internally replaces the `[IMG]` token placeholders by image embeddings from the vision encoder. The format for one or multiple prompts is the following:

    "<s>[INST][IMG]\nWhat are the things I should be cautious about when I visit this place?[/INST]"

Then, the processor will replace each `[IMG]` token with a number of `[IMG]` tokens that depend on the height and the width of each image. Each row of the image is separated by an `[IMG_BREAK]` token, and each image is separated by an `[IMG_END]` token. It’s advised to use the `apply_chat_template` method of the processor, which takes care of all of this and formats the text for you. If you’re using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the usage section for more info.

This model was contributed by amyeroberts and ArthurZ. The original code can be found here.

##
Usage

At inference time, it’s advised to use the processor’s `apply_chat_template` method, which correctly formats the prompt for the model:

    from transformers import AutoProcessor, LlavaForConditionalGeneration

    model_id = "mistral-community/pixtral-12b"
    processor = AutoProcessor.from_pretrained(model_id)
    model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map="cuda")

    chat = [
        {
          "role": "user", "content": [
            {"type": "text", "content": "Can this animal"},
            {"type": "image", "ur": "https://picsum.photos/id/237/200/300"},
            {"type": "text", "content": "live here?"},
            {"type": "image", "url": "https://picsum.photos/seed/picsum/200/300"}
          ]
        }
    ]

    inputs = processor.apply_chat_template(
        chat,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt"
    ).to(model.device)

    generate_ids = model.generate(**inputs, max_new_tokens=500)
    output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]

##
PixtralVisionConfig

###
class transformers.PixtralVisionConfig

< source >

( hidden_size = 1024 intermediate_size = 4096 num_hidden_layers = 24 num_attention_heads = 16 num_channels = 3 image_size = 1024 patch_size = 16 hidden_act = 'gelu' attention_dropout = 0.0 rope_theta = 10000.0 initializer_range = 0.02 **kwargs )

Parameters

- hidden_size (`int`, optional, defaults to 1024) — Dimension of the hidden representations.
- intermediate_size (`int`, optional, defaults to 4096) — Dimension of the MLP representations.
- num_hidden_layers (`int`, optional, defaults to 24) — Number of hidden layers in the Transformer encoder.
- num_attention_heads (`int`, optional, defaults to 16) — Number of attention heads in the Transformer encoder.
- num_channels (`int`, optional, defaults to 3) — Number of input channels in the input images.
- image_size (`int`, optional, defaults to 1024) — Max dimension of the input images.
- patch_size (`int`, optional, defaults to 16) — Size of the image patches.
- hidden_act (`str`, optional, defaults to `"gelu"`) — Activation function used in the hidden layers.
- attention_dropout (`float`, optional, defaults to 0.0) — Dropout probability for the attention layers.
- rope_theta (`float`, optional, defaults to 10000.0) — The base period of the RoPE embeddings.
- initializer_range (`float`, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

This is the configuration class to store the configuration of a PixtralVisionModel. It is used to instantiate an Pixtral vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to the vision encoder used by Pixtral-12B.

e.g. pixtral-hf/pixtral-9b

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 PixtralVisionModel, PixtralVisionConfig

    >>> # Initializing a Pixtral-12B style configuration
    >>> config = PixtralVisionConfig()

    >>> # Initializing a model (with randomly initialized weights) from the configuration
    >>> model = PixtralVisionModel(configuration)

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

##
PixtralVisionModel

###
class transformers.PixtralVisionModel

< source >

( config )

Parameters

- config (PixtralVisionConfig) — Model configuration class with all the parameters of the vision encoder. 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 Pixtral vision encoder outputting raw hidden-states without any specific head on top. 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 >

( pixel_values: Tensor image_sizes: Tensor output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None *args **kwargs ) →
pixel_values

Parameters

- pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values. Pixel values can be obtained using AutoImageProcessor. See `AutoImageProcessor.__call__()` for details.
- image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, optional) — The sizes of the images in the batch, being (height, width) for each image.
- 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.

Returns

pixel_values

tensor of token features for all tokens of all images of shape (N_toks, D)

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

##
PixtralImageProcessor

###
class transformers.PixtralImageProcessor

< source >

( do_resize: bool = True size: typing.Dict[str, int] = None patch_size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

Parameters

- do_resize (`bool`, optional, defaults to `True`) — Whether to resize the image’s (height, width) dimensions to the specified `size`. Can be overridden by `do_resize` in the `preprocess` method.
- size (`Dict[str, int]` optional, defaults to `{"longest_edge" -- 1024}`): Size of the maximum dimension of either the height or width dimension of the image. Used to control how images are resized. If either the height or width are greater than `size["longest_edge"]` then both the height and width are rescaled by `height / ratio`, `width /ratio` where `ratio = max(height / longest_edge, width / longest_edge)`
- patch_size (`Dict[str, int]` optional, defaults to `{"height" -- 16, "width": 16}`): Size of the patches in the model, used to calculate the output image size. Can be overridden by `patch_size` in the `preprocess` method.
- resample (`PILImageResampling`, optional, defaults to `Resampling.BICUBIC`) — Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
- do_rescale (`bool`, optional, defaults to `True`) — Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in the `preprocess` method.
- rescale_factor (`int` or `float`, optional, defaults to `1/255`) — Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess` method.
- do_normalize (`bool`, optional, defaults to `True`) — Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
- image_mean (`float` or `List[float]`, optional, defaults to `[0.48145466, 0.4578275, 0.40821073]`) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
- image_std (`float` or `List[float]`, optional, defaults to `[0.26862954, 0.26130258, 0.27577711]`) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method.
- do_convert_rgb (`bool`, optional, defaults to `True`) — Whether to convert the image to RGB.

Constructs a Pixtral image processor.

####
preprocess

< source >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: bool = None size: typing.Dict[str, int] = None patch_size: typing.Dict[str, int] = None resample: Resampling = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

Parameters

- images (`ImageInput`) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
- do_resize (`bool`, optional, defaults to `self.do_resize`) — Whether to resize the image.
- size (`Dict[str, int]`, optional, defaults to `self.size`) — Describes the maximum input dimensions to the model.
- patch_size (`Dict[str, int]`, optional, defaults to `self.patch_size`) — Patch size in the model. Used to calculate the image after resizing.
- resample (`int`, optional, defaults to `self.resample`) — Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only has an effect if `do_resize` is set to `True`.
- do_rescale (`bool`, optional, defaults to `self.do_rescale`) — Whether to rescale the image.
- rescale_factor (`float`, optional, defaults to `self.rescale_factor`) — Rescale factor to rescale the image by if `do_rescale` is set to `True`.
- do_normalize (`bool`, optional, defaults to `self.do_normalize`) — Whether to normalize the image.
- image_mean (`float` or `List[float]`, optional, defaults to `self.image_mean`) — Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
- image_std (`float` or `List[float]`, optional, defaults to `self.image_std`) — Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`.
- do_convert_rgb (`bool`, optional, defaults to `self.do_convert_rgb`) — Whether to convert the image to RGB.
- return_tensors (`str` or `TensorType`, optional) — The type of tensors to return. Can be one of:
  - Unset: Return a list of `np.ndarray`.
  - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
- data_format (`ChannelDimension` or `str`, optional, defaults to `ChannelDimension.FIRST`) — The channel dimension format for the output image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  - Unset: Use the channel dimension format of the input image.
- input_data_format (`ChannelDimension` or `str`, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

Preprocess an image or batch of images.

##
PixtralImageProcessorFast

###
class transformers.PixtralImageProcessorFast

< source >

( **kwargs: typing_extensions.Unpack[transformers.models.pixtral.image_processing_pixtral_fast.PixtralFastImageProcessorInitKwargs] )

Parameters

- do_resize (`bool`, optional, defaults to `self.do_resize`) — Whether to resize the image’s (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
- size (`dict`, optional, defaults to `self.size`) — Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess` method.
- default_to_square (`bool`, optional, defaults to `self.default_to_square`) — Whether to default to a square image when resizing, if size is an int.
- resample (`PILImageResampling`, optional, defaults to `self.resample`) — Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be overridden by the `resample` parameter in the `preprocess` method.
- do_center_crop (`bool`, optional, defaults to `self.do_center_crop`) — Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the `preprocess` method.
- crop_size (`Dict[str, int]` optional, defaults to `self.crop_size`) — Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess` method.
- do_rescale (`bool`, optional, defaults to `self.do_rescale`) — Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method.
- rescale_factor (`int` or `float`, optional, defaults to `self.rescale_factor`) — Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be overridden by the `rescale_factor` parameter in the `preprocess` method.
- do_normalize (`bool`, optional, defaults to `self.do_normalize`) — Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
- image_mean (`float` or `List[float]`, optional, defaults to `self.image_mean`) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method.
- image_std (`float` or `List[float]`, optional, defaults to `self.image_std`) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method.
- do_convert_rgb (`bool`, optional, defaults to `self.image_std`) — Whether to convert the image to RGB.
- patch_size (`Dict[str, int]` optional, defaults to `{"height" -- 16, "width": 16}`): Size of the patches in the model, used to calculate the output image size. Can be overridden by `patch_size` in the `preprocess` method.

Constructs a fast ConvNeXT image processor.

####
preprocess

< source >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] **kwargs: typing_extensions.Unpack[transformers.models.pixtral.image_processing_pixtral_fast.PixtralFastImageProcessorPreprocessKwargs] )

Parameters

- images (`ImageInput`) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
- do_resize (`bool`, optional, defaults to `self.do_resize`) — Whether to resize the image.
- size (`Dict[str, int]`, optional, defaults to `self.size`) — Describes the maximum input dimensions to the model.
- resample (`PILImageResampling` or `InterpolationMode`, optional, defaults to `self.resample`) — Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only has an effect if `do_resize` is set to `True`.
- do_center_crop (`bool`, optional, defaults to `self.do_center_crop`) — Whether to center crop the image.
- crop_size (`Dict[str, int]`, optional, defaults to `self.crop_size`) — Size of the output image after applying `center_crop`.
- do_rescale (`bool`, optional, defaults to `self.do_rescale`) — Whether to rescale the image.
- rescale_factor (`float`, optional, defaults to `self.rescale_factor`) — Rescale factor to rescale the image by if `do_rescale` is set to `True`.
- do_normalize (`bool`, optional, defaults to `self.do_normalize`) — Whether to normalize the image.
- image_mean (`float` or `List[float]`, optional, defaults to `self.image_mean`) — Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
- image_std (`float` or `List[float]`, optional, defaults to `self.image_std`) — Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`.
- do_convert_rgb (`bool`, optional, defaults to `self.do_convert_rgb`) — Whether to convert the image to RGB.
- return_tensors (`str` or `TensorType`, optional) — Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
- data_format (`ChannelDimension` or `str`, optional, defaults to `ChannelDimension.FIRST`) — The channel dimension format for the output image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  - Unset: Use the channel dimension format of the input image.
- input_data_format (`ChannelDimension` or `str`, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
- device (`torch.device`, optional) — The device to process the images on. If unset, the device is inferred from the input images.
- patch_size (`Dict[str, int]` optional, defaults to `{"height" -- 16, "width": 16}`): Size of the patches in the model, used to calculate the output image size. Can be overridden by `patch_size` in the `preprocess` method.

Preprocess an image or batch of images.

##
PixtralProcessor

###
class transformers.PixtralProcessor

< source >

( image_processor = None tokenizer = None patch_size: int = 16 chat_template = None image_token = '[IMG]' image_break_token = '[IMG_BREAK]' image_end_token = '[IMG_END]' **kwargs )

Parameters

- image_processor (PixtralImageProcessor, optional) — The image processor is a required input.
- tokenizer (LlamaTokenizerFast, optional) — The tokenizer is a required input.
- patch_size (`int`, optional, defaults to 16) — Patch size from the vision tower.
- chat_template (`str`, optional) — A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string.
- image_token (`str`, optional, defaults to `"[IMG]"`) — Special token used to denote image location.
- image_break_token (`str`, optional, defaults to `"[IMG_BREAK]"`) — Special token used to denote the end of a line of pixels in an image.
- image_end_token (`str`, optional, defaults to `"[IMG_END]"`) — Special token used to denote the end of an image input.

Constructs a Pixtral processor which wraps a Pixtral image processor and a Pixtral tokenizer into a single processor.

PixtralProcessor offers all the functionalities of CLIPImageProcessor and LlamaTokenizerFast. See the `__call__()` and decode() for more information.

####
batch_decode

< source >

( *args **kwargs )

This method forwards all its arguments to LlamaTokenizerFast’s batch_decode(). Please refer to the docstring of this method for more information.

####
decode

< source >

( *args **kwargs )

This method forwards all its arguments to LlamaTokenizerFast’s decode(). Please refer to the docstring of this method for more information.

< > Update on GitHub