Transformers 文档

Pixtral

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Pixtral

PyTorch

概述

Pixtral 模型由 Mistral AI 团队在一篇博客文章中发布。Pixtral 是 Mistral 的多模态版本,其中包含一个从零开始训练的 4 亿参数视觉编码器。

博客文章中的介绍如下:

Pixtral 经过训练,可以理解自然图像和文档,在 MMMU 推理基准测试中达到了 52.5% 的准确率,超越了许多更大的模型。该模型在图表理解、文档问答、多模态推理和指令遵循等任务中表现出强大的能力。Pixtral 能够以原始分辨率和纵横比处理图像,为用户提供了处理图像时所用令牌数量的灵活性。Pixtral 还能够在 128K 令牌的长期上下文窗口中处理任意数量的图像。与以前的开源模型不同,Pixtral 不会为了在多模态任务中表现出色而牺牲文本基准性能。

drawing Pixtral 架构。摘自博客文章。

技巧

  • 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 方法,该方法负责所有这些并将文本格式化。如果您使用 transformers>=4.49.0,您还可以从 apply_chat_template 获取矢量化输出。更多信息请参见用法部分

此模型由 amyerobertsArthurZ 贡献。原始代码可在此处找到。

用法

在推理时,建议使用处理器的 apply_chat_template 方法,该方法可以正确地为模型格式化提示。

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", "url": "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

< >

( 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, 可选, 默认为 1024) — 隐藏表示的维度。
  • intermediate_size (int, 可选, 默认为 4096) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 24) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 16) — Transformer 编码器中的注意力头数量。
  • num_channels (int, 可选, 默认为 3) — 输入图像中的输入通道数量。
  • image_size (int, 可选, 默认为 1024) — 输入图像的最大维度。
  • patch_size (int, 可选, 默认为 16) — 图像块的大小。
  • hidden_act (str, 可选, 默认为 "gelu") — 隐藏层中使用的激活函数。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力层的 dropout 概率。
  • rope_theta (float, 可选, 默认为 10000.0) — RoPE 嵌入的基周期。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 PixtralVisionModel 配置的配置类。它用于根据指定的参数实例化 Pixtral 视觉编码器,定义模型架构。使用默认值实例化配置将产生与 Pixtral-12B 使用的视觉编码器类似的配置。

例如 pixtral-hf/pixtral-9b

配置对象继承自 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

class transformers.PixtralVisionModel

< >

( config )

参数

  • config (PixtralVisionModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。

裸 Pixtral 模型,输出原始隐藏状态,顶部没有任何特定头部。

此模型继承自 PreTrainedModel。有关库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等),请查看超类文档。

此模型也是 PyTorch torch.nn.Module 的子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

forward

< >

( pixel_values: Tensor image_sizes: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None *args **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • image_sizes (torch.Tensor,形状为 (batch_size, 2)可选) — 批次中图像的大小,对于每张图像为 (高度, 宽度)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参见返回张量下的 attentions
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),包含根据配置(PixtralVisionConfig)和输入而变化的各种元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层输出,如果模型有嵌入层,+ 每个层的输出一个)形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传入 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

PixtralVisionModel 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在此函数中定义,但在此之后应调用 Module 实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

PixtralImageProcessor

class transformers.PixtralImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None patch_size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的 (高度, 宽度) 维度调整到指定的 size。可以通过 preprocess 方法中的 do_resize 覆盖。
  • size (dict[str, int] 可选, 默认为 {"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 (intfloat, 可选, 默认为 1/255) — 如果缩放图像,要使用的缩放因子。可以通过 preprocess 方法中的 rescale_factor 覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否标准化图像。可以通过 preprocess 方法中的 do_normalize 覆盖。
  • image_mean (floatlist[float], 可选, 默认为 [0.48145466, 0.4578275, 0.40821073]) — 如果标准化图像,要使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 [0.26862954, 0.26130258, 0.27577711]) — 标准差,用于图像归一化。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以在 preprocess 方法中的 image_std 参数中覆盖。可以在 preprocess 方法中的 image_std 参数中覆盖。
  • do_convert_rgb (bool, 可选, 默认为 True) — 是否将图像转换为 RGB。

构造 Pixtral 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None patch_size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: typing.Optional[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 )

参数

  • images (ImageInput) — 要预处理的图像。期望单个或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 描述模型最大输入维度。
  • patch_size (dict[str, int], 可选, 默认为 self.patch_size) — 模型中的补丁大小。用于计算调整大小后的图像。
  • resample (int, 可选, 默认为 self.resample) — 如果调整图像大小,要使用的重采样过滤器。可以是枚举 PILImageResampling 之一。仅在 do_resize 设置为 True 时有效。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则图像的缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否归一化图像。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 用于归一化的图像平均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。

预处理一张或一批图像。

PixtralImageProcessorFast

class transformers.PixtralImageProcessorFast

< >

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

构造一个快速 Pixtral 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.pixtral.image_processing_pixtral_fast.PixtralFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 要预处理的图像。期望单个或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型最大输入维度。
  • default_to_square (bool, 可选) — 调整大小时,如果大小为 int,是否默认为方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果调整图像大小,要使用的重采样过滤器。可以是枚举 PILImageResampling 之一。仅在 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选) — 是否中心裁剪图像。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的大小。
  • do_rescale (bool, 可选) — 是否重新缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,则图像的缩放因子。
  • do_normalize (bool, 可选) — 是否归一化图像。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像平均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt,则返回堆叠的张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 输出图像的通道维度格式。仅支持 ChannelDimension.FIRST。为了与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。
  • device (torch.device, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组以单独处理而不是批量处理。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详情请参阅此处:https://github.com/huggingface/transformers/pull/38157
  • patch_size (dict[str, int] 可选, 默认为 {"height" -- 16, "width": 16}) — 模型中补丁的大小,用于计算输出图像的大小。可以在 preprocess 方法中的 patch_size 覆盖。

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

PixtralProcessor

class transformers.PixtralProcessor

< >

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

参数

  • image_processor (PixtralImageProcessor, 可选) — 图像处理器是必需输入。
  • tokenizer (LlamaTokenizerFast, 可选) — 分词器是必需输入。
  • patch_size (int, 可选, 默认为 16) — 来自视觉塔的补丁大小。
  • spatial_merge_size (int, 可选, 默认为 1) — 空间合并操作的下采样因子。
  • chat_template (str, 可选) — 用于将聊天中的消息列表转换为可标记字符串的 Jinja 模板。
  • image_token (str, 可选, 默认为 "[IMG]") — 用于表示图像位置的特殊标记。
  • image_break_token (str, 可选, 默认为 "[IMG_BREAK]") — 用于表示图像中像素行结束的特殊标记。
  • image_end_token (str, 可选, 默认为 "[IMG_END]") — 用于表示图像输入结束的特殊标记。

构造一个 Pixtral 处理器,它将 Pixtral 图像处理器和 Pixtral 分词器包装成一个单一的处理器。

PixtralProcessor 提供了 CLIPImageProcessorLlamaTokenizerFast 的所有功能。有关更多信息,请参阅 __call__()decode()

批量解码

< >

( *args **kwargs )

此方法将其所有参数转发到 LlamaTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。

解码

< >

( *args **kwargs )

此方法将其所有参数转发给 LlamaTokenizerFast 的 decode()。有关更多信息,请参阅此方法的文档字符串。

< > 在 GitHub 上更新