Transformers 文档

Pixtral

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

Pixtral

PyTorch

概述

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

该博客的介绍如下:

Pixtral 经过训练可以理解自然图像和文档,在 MMMU 推理基准测试中达到 52.5%,超过了许多更大的模型。该模型在图表和图形理解、文档问答、多模态推理和指令跟随等任务中表现出强大的能力。Pixtral 能够以其自然分辨率和宽高比摄取图像,使用户可以灵活地控制用于处理图像的 tokens 数量。Pixtral 还能够在 128K tokens 的长上下文窗口中处理任意数量的图像。与之前的开源模型不同,Pixtral 在文本基准测试性能上没有妥协,从而在多模态任务中表现出色。

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

提示

  • Pixtral 是一个多模态模型,以图像和文本作为输入,并生成文本作为输出。
  • 此模型遵循 Llava 架构。该模型使用 PixtralVisionModel 作为其视觉编码器,并使用 MistralForCausalLM 作为其语言解码器。
  • 主要的贡献是在图像上使用 2d ROPE(旋转位置嵌入),以及支持任意图像尺寸(图像不一起填充,也不调整大小)。
  • Llava 类似,该模型在内部将 [IMG] token 占位符替换为来自视觉编码器的图像嵌入。一个或多个提示的格式如下:
"<s>[INST][IMG]\nWhat are the things I should be cautious about when I visit this place?[/INST]"

然后,处理器会将每个 [IMG] token 替换为多个 [IMG] token,token 的数量取决于每张图像的高度和宽度。图像的每一都用一个 [IMG_BREAK] token 分隔,每张图像都用一个 [IMG_END] token 分隔。建议使用处理器的 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 (PixtralVisionConfig) — 包含视觉编码器所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法来加载模型权重。

裸 Pixtral 视觉编码器输出原始隐藏状态,顶部没有任何特定的 head。 此模型继承自 PreTrainedModel。 查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。

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

forward

< >

( 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

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 AutoImageProcessor.__call__()
  • image_sizes (torch.LongTensor,形状为 (batch_size, 2), 可选) — 批次中图像的大小,对于每个图像为 (高度, 宽度)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

pixel_values

形状为 (N_toks, D) 的所有图像的所有 token 的 token 特征张量

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

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

PixtralImageProcessor

class transformers.PixtralImageProcessor

< >

( 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 )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。 可以被 preprocess 方法中的 do_resize 覆盖。
  • size (Dict[str, int] 可选, 默认为 {"longest_edge" -- 1024}):图像的高度或宽度维度的最大尺寸。 用于控制图像的调整大小方式。 如果高度或宽度大于 size["longest_edge"],则高度和宽度都按 height / ratiowidth /ratio 缩放,其中 ratio = max(height / longest_edge, width / longest_edge)
  • patch_size (Dict[str, int] 可选, 默认为 {"height" -- 16, "width": 16}):模型中 patch 的大小,用于计算输出图像大小。 可以被 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 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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 )

参数

  • 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) — 模型中的 Patch 大小。 用于计算调整大小后的图像。
  • 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, 可选) — 返回张量的类型。 可以是以下之一:
    • Unset: 返回 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)。
    • Unset: 使用输入图像的通道维度格式。
  • 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] )

参数

  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否将图像的 (高度, 宽度) 尺寸调整为指定的 size。 可以被 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict, 可选, 默认为 self.size) — 调整大小后输出图像的大小。 可以被 preprocess 方法中的 size 参数覆盖。
  • default_to_square (bool, 可选, 默认为 self.default_to_square) — 如果 size 是整数,是否在调整大小时默认使用方形图像。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。 仅当 do_resize 设置为 True 时才有效。 可以被 preprocess 方法中的 resample 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否将图像中心裁剪为指定的 crop_size。 可以被 preprocess 方法中的 do_center_crop 参数覆盖。
  • crop_size (Dict[str, int] 可选, 默认为 self.crop_size) — 应用 center_crop 后输出图像的大小。 可以被 preprocess 方法中的 crop_size 参数覆盖。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否通过指定的缩放比例 rescale_factor 来缩放图像。 可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 self.rescale_factor) — 如果缩放图像,则使用的缩放因子。 仅当 do_rescale 设置为 True 时才有效。 可以被 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化。可以通过 preprocess 方法中的 do_normalize 参数覆盖。可以通过 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], optional, defaults to self.image_mean) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 `image_mean` 参数覆盖。可以通过 preprocess 方法中的 `image_mean` 参数覆盖。
  • image_std (floatList[float], optional, defaults to self.image_std) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 `image_std` 参数覆盖。可以通过 preprocess 方法中的 `image_std` 参数覆盖。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (strTensorType, optional, defaults to self.return_tensors) — 如果设置为 `pt`,则返回堆叠的张量;否则返回张量列表。
  • data_format (ChannelDimensionstr, optional, defaults to self.data_format) — 仅支持 ChannelDimension.FIRST。为了与慢速处理器兼容而添加。
  • input_data_format (ChannelDimensionstr, optional, defaults to self.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 格式为 (通道数, 高度, 宽度) 的图像。
    • "channels_last"ChannelDimension.LAST: 格式为 (高度, 宽度, 通道数) 的图像。
    • "none"ChannelDimension.NONE: 格式为 (高度, 宽度) 的图像。
  • device (torch.device, optional, defaults to self.device) — 用于处理图像的设备。如果未设置,则从输入图像推断设备。
  • patch_size (Dict[str, int] optional, defaults to {"height" -- 16, "width": 16}): 模型中图像块的大小,用于计算输出图像大小。可以通过 preprocess 方法中的 `patch_size` 覆盖。

构建一个快速的 ConvNeXT 图像处理器。

preprocess

< >

( 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] )

参数

  • images (ImageInput) — 要预处理的图像。 期望是像素值范围为 0 到 255 的单个或一批图像。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], optional, defaults to self.size) — 描述模型的最大输入尺寸。
  • resample (PILImageResamplingInterpolationMode, optional, defaults to self.resample) — 如果调整图像大小,则使用的重采样滤波器。可以是 PILImageResampling 枚举之一。仅当 do_resize 设置为 `True` 时才有效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], optional, defaults to self.crop_size) — 应用 `center_crop` 后输出图像的尺寸。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 `True`,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化。
  • image_mean (floatList[float], optional, defaults to self.image_mean) — 用于归一化的图像均值。仅当 do_normalize 设置为 `True` 时才有效。
  • image_std (floatList[float], optional, defaults to self.image_std) — 用于归一化的图像标准差。仅当 do_normalize 设置为 `True` 时才有效。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (strTensorType, optional, defaults to self.return_tensors) — 如果设置为 `pt`,则返回堆叠的张量;否则返回张量列表。
  • data_format (ChannelDimensionstr, optional, defaults to self.data_format) — 仅支持 ChannelDimension.FIRST。为了与慢速处理器兼容而添加。
  • input_data_format (ChannelDimensionstr, optional, defaults to self.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 格式为 (通道数, 高度, 宽度) 的图像。
    • "channels_last"ChannelDimension.LAST: 格式为 (高度, 宽度, 通道数) 的图像。
    • "none"ChannelDimension.NONE: 格式为 (高度, 宽度) 的图像。
  • device (torch.device, optional, defaults to self.device) — 用于处理图像的设备。如果未设置,则从输入图像推断设备。
  • patch_size (Dict[str, int] optional, defaults to {"height" -- 16, "width": 16}): 模型中图像块的大小,用于计算输出图像大小。可以通过 preprocess 方法中的 `patch_size` 覆盖。

预处理单张或批量图像。

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

构建一个 Pixtral 处理器,它将 Pixtral 图像处理器和 Pixtral 分词器封装到一个处理器中。

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

batch_decode

< >

( *args **kwargs )

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

decode

< >

( *args **kwargs )

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

< > 在 GitHub 上更新