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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.