#
Pixtral

##
Overview

The Pixtral model was released by the Mistral AI team on Vllm, where a version of the code can be found!

Tips:

- Pixtral is a multimodal model, the main contribution is the 2d ROPE on the images, and support for arbitrary image size (the images are not padded together nor are they resized)
- This model follows the `Llava` familiy, meaning image embeddings are placed instead of the `[IMG]` token placeholders.
- The format for one or mulitple 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]` token that depends on the height and the width of the image. Each row of the image is separated by a `[IMG_BREAK]` token, and each image is separated by a `[IMG_END]` token.

This model was contributed by amyeroberts and ArthurZ

Here is an example of how to run it:

    from transformers import LlavaForConditionalGeneration, AutoProcessor
    from PIL import Image

    model_id = "hf-internal-testing/pixtral-12b"
    model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cuda")
    processor = AutoProcessor.from_pretrained(model_id)

    IMG_URLS = [
        "https://picsum.photos/id/237/400/300",
        "https://picsum.photos/id/231/200/300",
        "https://picsum.photos/id/27/500/500",
        "https://picsum.photos/id/17/150/600",
    ]
    PROMPT = "<s>[INST]Describe the images.\n[IMG][IMG][IMG][IMG][/INST]"

    inputs = processor(images=IMG_URLS, text=PROMPT, return_tensors="pt").to("cuda")
    generate_ids = model.generate(**inputs, max_new_tokens=500)
    ouptut = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]

    EXPECTED_GENERATION = """
    Describe the images.
    Sure, let's break down each image description:

    1. **Image 1:**
       - **Description:** A black dog with a glossy coat is sitting on a wooden floor. The dog has a focused expression and is looking directly at the camera.
       - **Details:** The wooden floor has a rustic appearance with visible wood grain patterns. The dog's eyes are a striking color, possibly brown or amber, which contrasts with its black fur.

    2. **Image 2:**
       - **Description:** A scenic view of a mountainous landscape with a winding road cutting through it. The road is surrounded by lush green vegetation and leads to a distant valley.
       - **Details:** The mountains are rugged with steep slopes, and the sky is clear, indicating good weather. The winding road adds a sense of depth and perspective to the image.

    3. **Image 3:**
       - **Description:** A beach scene with waves crashing against the shore. There are several people in the water and on the beach, enjoying the waves and the sunset.
       - **Details:** The waves are powerful, creating a dynamic and lively atmosphere. The sky is painted with hues of orange and pink from the setting sun, adding a warm glow to the scene.

    4. **Image 4:**
       - **Description:** A garden path leading to a large tree with a bench underneath it. The path is bordered by well-maintained grass and flowers.
       - **Details:** The path is made of small stones or gravel, and the tree provides a shaded area with the bench invitingly placed beneath it. The surrounding area is lush and green, suggesting a well-kept garden.

    Each image captures a different scene, from a close-up of a dog to expansive natural landscapes, showcasing various elements of nature and human interaction with it.
    """

##
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 tie_word_embeddings = False **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.
- tie_word_embeddings (`bool`, optional, defaults to `False`) — Whether to tie the word embeddings with the input embeddings.

This is the configuration class to store the configuration of a PixtralModel. It is used to instantiate an Pixtral 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 Pixtral-9B.

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 PixtralModel, PixtralVisionConfig, CLIPVisionConfig, LlamaConfig

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

    >>> # Initializing a model from the pixtral 12B style configuration
    >>> model = PixtralModel(configuration)

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

##
PixtralModel

###
class transformers.PixtralModel

< source >

( config )

Parameters

- config (PixtralVisionConfig or PixtralVisionConfig) — 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 PIXTRAL 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 >

( pixel_values: List output_hidden_states: Optional = False output_attentions: Optional = None return_dict: Optional = None *args **kwargs ) →
pixel_values

Parameters

- 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 PixtralModel 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: Dict = None patch_size: Dict = None resample: Resampling = <Resampling.BICUBIC: 3> do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = 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: Union do_resize: bool = None size: Dict = None patch_size: Dict = None resample: Resampling = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: Union = None image_std: Union = None do_convert_rgb: bool = None return_tensors: Union = None data_format: Optional = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = 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.

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