Pixtral
概述
Pixtral模型由Mistral AI团队在博客文章中发布。Pixtral是Mistral的多模态版本,包含一个从头开始训练的4亿参数视觉编码器。
博客的简介如下:
Pixtral 经过训练,能够理解自然图像和文档,在 MMMU 推理基准测试中达到了 52.5% 的准确率,超越了许多更大的模型。该模型在图表和图形理解、文档问答、多模态推理和指令遵循等任务中表现出强大的能力。Pixtral 能够以其自然分辨率和宽高比处理图像,使用户在处理图像时使用的 token 数量具有灵活性。Pixtral 还能够在 128K token 的长上下文窗口中处理任意数量的图像。与之前的开源模型不同,Pixtral 在多模态任务中表现出色,同时不会在文本基准性能上做出妥协。
![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/pixtral_architecture.webp)
提示:
- Pixtral 是一个多模态模型,接受图像和文本作为输入,并生成文本作为输出。
- 该模型遵循Llava架构。模型使用PixtralVisionModel作为视觉编码器,使用MistralForCausalLM作为语言解码器。
- 主要贡献是在图像上使用了2d ROPE(旋转位置嵌入),并支持任意图像大小(图像不会被填充在一起,也不会被调整大小)。
- 类似于Llava,模型内部使用视觉编码器的图像嵌入替换
[IMG]
标记占位符。一个或多个提示的格式如下:
"<s>[INST][IMG]\nWhat are the things I should be cautious about when I visit this place?[/INST]"
然后,处理器将根据每张图像的高度和宽度,将每个[IMG]
标记替换为多个[IMG]
标记。图像的每一行由[IMG_BREAK]
标记分隔,每张图像由[IMG_END]
标记分隔。建议使用处理器的apply_chat_template
方法,该方法会处理所有这些。更多信息请参见使用部分。
该模型由amyeroberts和ArthurZ贡献。原始代码可以在这里找到。
用法
在推理时,建议使用处理器的apply_chat_template
方法,该方法会正确格式化模型的提示:
from transformers import AutoProcessor, LlavaForConditionalGeneration
from PIL import Image
model_id = "mistral-community/pixtral-12b"
processor = AutoProcessor.from_pretrained(model_id)
model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cuda")
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"},
{"type": "text", "content": "live here?"},
{"type": "image"}
]
}
]
prompt = processor.apply_chat_template(chat)
inputs = processor(text=prompt, images=[url_dog, url_mountain], 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
类 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 )
参数
- hidden_size (
int
, optional, defaults to 1024) — 隐藏表示的维度。 - intermediate_size (
int
, optional, 默认为 4096) — MLP 表示的维度。 - num_hidden_layers (
int
, optional, defaults to 24) — Transformer编码器中的隐藏层数量。 - num_attention_heads (
int
, optional, defaults to 16) — Transformer编码器中的注意力头数量。 - num_channels (
int
, optional, defaults to 3) — 输入图像中的输入通道数。 - image_size (
int
, optional, 默认为 1024) — 输入图像的最大尺寸。 - patch_size (
int
, optional, defaults to 16) — 图像块的大小。 - hidden_act (
str
, optional, defaults to"gelu"
) — 隐藏层中使用的激活函数。 - attention_dropout (
float
, optional, defaults to 0.0) — 注意力层的丢弃概率。 - rope_theta (
float
, optional, 默认为 10000.0) — RoPE 嵌入的基础周期。 - initializer_range (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
这是用于存储PixtralVisionModel配置的配置类。它用于根据指定的参数实例化一个Pixtral视觉编码器,定义模型架构。使用默认值实例化配置将产生与Pixtral-12B使用的视觉编码器类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> 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
类 transformers.PixtralVisionModel
< source >( config )
参数
- config (PixtralVisionConfig) — 模型配置类,包含视觉编码器的所有参数。使用配置文件初始化时,不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Pixtral视觉编码器输出原始隐藏状态,没有任何特定的头部。 此模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: typing.List[torch.Tensor] output_hidden_states: typing.Optional[bool] = False output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None *args **kwargs ) → pixel_values
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见AutoImageProcessor.__call__()
。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
像素值
所有图像的所有标记的特征张量,形状为 (N_toks, D)
PixtralVisionModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
PixtralImageProcessor
类 transformers.PixtralImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None patch_size: typing.Dict[str, int] = None resample: Resampling =
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以在preprocess
方法中被do_resize
覆盖。 - size (
Dict[str, int]
optional, defaults to{"longest_edge" -- 1024}
): 图像高度或宽度尺寸的最大尺寸。用于控制图像如何调整大小。如果高度或宽度大于size["longest_edge"]
,则高度和宽度都会通过height / ratio
,width /ratio
重新缩放,其中ratio = max(height / longest_edge, width / longest_edge)
- patch_size (
Dict[str, int]
可选, 默认为{"height" -- 16, "width": 16}
): 模型中补丁的大小,用于计算输出图像的大小。可以通过preprocess
方法中的patch_size
进行覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BICUBIC
) — 如果调整图像大小,则使用的重采样过滤器。可以在preprocess
方法中通过resample
覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否通过指定的比例rescale_factor
来重新缩放图像。可以在preprocess
方法中被do_rescale
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中被rescale_factor
覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以在preprocess
方法中通过do_normalize
进行覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为[0.48145466, 0.4578275, 0.40821073]
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度为图像中的通道数。可以通过preprocess
方法中的image_mean
参数进行覆盖。 - image_std (
float
或List[float]
, 可选, 默认为[0.26862954, 0.26130258, 0.27577711]
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在preprocess
方法中通过image_std
参数覆盖。 可以在preprocess
方法中通过image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为RGB.
构建一个Pixtral图像处理器。
预处理
< 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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围从0到255。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 描述模型的最大输入维度。 - patch_size (
Dict[str, int]
, optional, defaults toself.patch_size
) — 模型中的补丁大小。用于计算调整大小后的图像。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举PILImageResampling
中的一个。只有在do_resize
设置为True
时才会生效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为RGB. - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回一个类型为tf.Tensor
的批次。TensorType.PYTORCH
或'pt'
:返回一个类型为torch.Tensor
的批次。TensorType.NUMPY
或'np'
:返回一个类型为np.ndarray
的批次。TensorType.JAX
或'jax'
:返回一个类型为jax.numpy.ndarray
的批次。
- 未设置:返回一个
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张图像或一批图像。
PixtralImageProcessorFast
类 transformers.PixtralImageProcessorFast
< source >( do_resize: bool = True size: typing.Dict[str, int] = None patch_size: typing.Dict[str, int] = None resample: typing.Union[PIL.Image.Resampling, ForwardRef('F.InterpolationMode')] =
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以在preprocess
方法中被do_resize
覆盖。 - size (
Dict[str, int]
optional, defaults to{"longest_edge" -- 1024}
): 图像高度或宽度维度的最大尺寸。用于控制图像的缩放方式。如果高度或宽度大于size["longest_edge"]
,则高度和宽度都会按height / ratio
和width / ratio
进行缩放,其中ratio = max(height / longest_edge, width / longest_edge)
- patch_size (
Dict[str, int]
可选, 默认为{"height" -- 16, "width": 16}
): 模型中补丁的大小,用于计算输出图像的大小。可以通过preprocess
方法中的patch_size
进行覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BICUBIC
) — 如果调整图像大小,则使用的重采样过滤器。可以在preprocess
方法中通过resample
覆盖此设置。 - do_rescale (
bool
, 可选, 默认为True
) — 是否通过指定的比例rescale_factor
来重新缩放图像。可以在preprocess
方法中被do_rescale
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中被rescale_factor
覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以在preprocess
方法中通过do_normalize
进行覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为[0.48145466, 0.4578275, 0.40821073]
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度为图像中的通道数。可以通过preprocess
方法中的image_mean
参数进行覆盖。 - image_std (
float
或List[float]
, 可选, 默认为[0.26862954, 0.26130258, 0.27577711]
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在preprocess
方法中通过image_std
参数进行覆盖。 可以在preprocess
方法中通过image_std
参数进行覆盖。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为RGB.
构建一个利用torchvision的快速Pixtral图像处理器。
预处理
< 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: typing.Union[PIL.Image.Resampling, ForwardRef('F.InterpolationMode'), NoneType] = 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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 描述模型的最大输入维度。 - patch_size (
Dict[str, int]
, optional, defaults toself.patch_size
) — 模型中的补丁大小。用于计算调整大小后的图像。 - resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。这可以是PILImageResampling
枚举之一。只有在do_resize
设置为True
时才会生效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化处理. - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为RGB. - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回一个类型为tf.Tensor
的批次。TensorType.PYTORCH
或'pt'
:返回一个类型为torch.Tensor
的批次。TensorType.NUMPY
或'np'
:返回一个类型为np.ndarray
的批次。TensorType.JAX
或'jax'
:返回一个类型为jax.numpy.ndarray
的批次。
- 未设置:返回一个
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张图像或一批图像。
PixtralProcessor
类 transformers.PixtralProcessor
< source >( image_processor = 无 tokenizer = 无 patch_size: int = 16 chat_template = 无 image_token = '[IMG]' image_break_token = '[IMG_BREAK]' image_end_token = '[IMG_END]' **kwargs )
参数
- image_processor (PixtralImageProcessor, optional) — 图像处理器是一个必需的输入。
- tokenizer (LlamaTokenizerFast, optional) — 分词器是一个必需的输入。
- patch_size (
int
, optional, defaults to 16) — 视觉塔中的补丁大小。 - chat_template (
str
, optional) — 一个Jinja模板,用于将聊天中的消息列表转换为可标记的字符串。 - image_token (
str
, 可选, 默认为"[IMG]"
) — 用于表示图像位置的特殊标记。 - image_break_token (
str
, optional, defaults to"[IMG_BREAK]"
) — 用于表示图像中一行像素结束的特殊标记。 - image_end_token (
str
, optional, defaults to"[IMG_END]"
) — 用于表示图像输入结束的特殊标记。
构建一个Pixtral处理器,它将Pixtral图像处理器和Pixtral分词器封装成一个单一的处理器。
PixtralProcessor 提供了 CLIPImageProcessor 和 LlamaTokenizerFast 的所有功能。更多信息请参见
__call__()
和 decode()。
此方法将其所有参数转发给LlamaTokenizerFast的batch_decode()。请参考该方法的文档字符串以获取更多信息。
此方法将其所有参数转发给LlamaTokenizerFast的decode()。请参考该方法的文档字符串以获取更多信息。