Transformers documentation
Pixtral
This model was published in HF papers on 2024-10-09 and contributed to Hugging Face Transformers on 2024-09-14.
Pixtral
Pixtral is a multimodal model trained to understand natural images and documents. It accepts images in their natural resolution and aspect ratio without resizing or padding due to its 2D RoPE embeddings. In addition, Pixtral has a long 128K token context window for processing a large number of images. Pixtral couples a 400M vision encoder with a 12B Mistral Nemo decoder.
Pixtral architecture. Taken from the blog post. You can find all the original Pixtral checkpoints under the Mistral AI organization.
This model was contributed by amyeroberts and ArthurZ. Click on the Pixtral models in the right sidebar for more examples of how to apply Pixtral to different vision and language tasks.
import torch
from transformers import AutoProcessor, LlavaForConditionalGeneration
model_id = "mistral-community/pixtral-12b"
model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
url_dog = "https://picsum.photos/id/237/200/300"
url_mountain = "https://picsum.photos/seed/picsum/200/300"
chat = [
{
"role": "user", "content": [
{"type": "text", "content": "Can this animal"},
{"type": "image", "url": url_dog},
{"type": "text", "content": "live here?"},
{"type": "image", "url" : url_mountain}
]
}
]
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]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 quantize the model to 4-bits.
import requests
import torch
from PIL import Image
from transformers import AutoProcessor, BitsAndBytesConfig, LlavaForConditionalGeneration
model_id = "mistral-community/pixtral-12b"
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
model = LlavaForConditionalGeneration.from_pretrained(
model_id,
quantization_config=quantization_config,
device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_id)
dog_url = "https://picsum.photos/id/237/200/300"
mountain_url = "https://picsum.photos/seed/picsum/200/300"
dog_image = Image.open(requests.get(dog_url, stream=True).raw)
mountain_image = Image.open(requests.get(mountain_url, stream=True).raw)
chat = [
{
"role": "user", "content": [
{"type": "text", "text": "Can this animal"},
{"type": "image"},
{"type": "text", "text": "live here?"},
{"type": "image"}
]
}
]
prompt = processor.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
inputs = processor(text=prompt, images=[dog_image, mountain_image], return_tensors="pt").to(model.device)
inputs["pixel_values"] = inputs["pixel_values"].to(model.dtype)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generate_ids = model.generate(**inputs, max_new_tokens=100)
output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
print(output)Notes
Pixtral uses PixtralVisionModel as the vision encoder and MistralForCausalLM for its language decoder.
The model internally replaces
[IMG]token placeholders with image embeddings."<s>[INST][IMG]\nWhat are the things I should be cautious about when I visit this place?[/INST]"The
[IMG]tokens are replaced with a number of[IMG]tokens that depend on the height and width of each image. Each row of the image is separated by a[IMG_BREAK]token and each image is separated by a[IMG_END]token. Use the~Processor.apply_chat_templatemethod to handle these tokens for you.
PixtralVisionConfig
class transformers.PixtralVisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonehidden_size: int = 1024intermediate_size: int = 4096num_hidden_layers: int = 24num_attention_heads: int = 16num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'attention_dropout: float | int = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneinitializer_range: float = 0.02 )
Parameters
- hidden_size (
int, optional, defaults to1024) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to4096) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to24) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to16) — Number of attention heads for each attention layer in the Transformer decoder. - num_channels (
int, optional, defaults to3) — The number of input channels. - image_size (
Union[int, list[int], tuple[int, int]], optional, defaults to1024) — The size (resolution) of each image. - patch_size (
Union[int, list[int], tuple[int, int]], optional, defaults to16) — The size (resolution) of each patch. - hidden_act (
str, optional, defaults togelu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - 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. - initializer_range (
float, optional, defaults to0.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 a 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 mistral-labs/pixtral-12b
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.configMistralCommonBackend
PixtralVisionModel
class transformers.PixtralVisionModel
< source >( config )
Parameters
- config (PixtralVisionModel) — 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 Pixtral Model 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: Tensorimage_sizes: typing.Optional[torch.Tensor] = None**kwargs: Unpack ) → BaseModelOutput or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size)) — The tensors corresponding to the input images. Pixel values can be obtained using PixtralImageProcessor. SeePixtralImageProcessor.__call__()for details (PixtralProcessor uses PixtralImageProcessor for processing images). - image_sizes (
torch.Tensorof shape(batch_size, 2), optional) — The sizes of the images in the batch, being (height, width) for each image.
Returns
BaseModelOutput or tuple(torch.FloatTensor)
A BaseModelOutput 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 (PixtralVisionConfig) and inputs.
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
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.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.
PixtralImageProcessor
class transformers.PixtralImageProcessor
< source >( **kwargs: Unpack )
Parameters
- do_convert_rgb (
bool, kwargs, optional, defaults toTrue) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional, defaults toTrue) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'longest_edge' -- 1024}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults toResampling.BICUBIC) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.48145466, 0.4578275, 0.40821073]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.26862954, 0.26130258, 0.27577711]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - patch_size (
Union[dict[str, *kwargs*, int], int]optional, defaults to{"height" -- 16, "width": 16}): Size of the patches in the model, used to calculate the output image size.
Constructs a PixtralImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False. - do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - patch_size (
Union[dict[str, *kwargs*, int], int]optional, defaults to{"height" -- 16, "width": 16}): Size of the patches in the model, used to calculate the output image size.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
PixtralImageProcessorPil
class transformers.PixtralImageProcessorPil
< source >( **kwargs: Unpack )
Parameters
- do_convert_rgb (
bool, kwargs, optional, defaults toTrue) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional, defaults toTrue) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'longest_edge' -- 1024}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults toResampling.BICUBIC) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.48145466, 0.4578275, 0.40821073]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.26862954, 0.26130258, 0.27577711]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - patch_size (
Union[dict[str, *kwargs*, int], int]optional, defaults to{"height" -- 16, "width": 16}): Size of the patches in the model, used to calculate the output image size.
Constructs a PixtralImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False. - do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - patch_size (
Union[dict[str, *kwargs*, int], int]optional, defaults to{"height" -- 16, "width": 16}): Size of the patches in the model, used to calculate the output image size.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
PixtralProcessor
class transformers.PixtralProcessor
< source >( image_processor = Nonetokenizer = Nonepatch_size: int = 16spatial_merge_size: int = 1chat_template = Noneimage_token = '[IMG]'image_break_token = '[IMG_BREAK]'image_end_token = '[IMG_END]'**kwargs )
Parameters
- image_processor (
PixtralImageProcessor) — The image processor is a required input. - tokenizer (
TokenizersBackend) — The tokenizer is a required input. - patch_size (
int, optional, defaults to 16) — Patch size from the vision tower. - spatial_merge_size (
int, optional, defaults to 1) — The downsampling factor for the spatial merge operation. - chat_template (
str) — A Jinja template 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 PixtralProcessor which wraps a image processor and a tokenizer into a single processor.
PixtralProcessor offers all the functionalities of PixtralImageProcessor and TokenizersBackend. See the ~PixtralImageProcessor and ~TokenizersBackend 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] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: Unpack )
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. - videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], optional) — Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If passing in videos with pixel values between 0 and 1, setdo_rescale=False. - audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], optional) — The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, and T is the sample length of the audio. - 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.