Transformers 文件

Mistral3

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Mistral3

概述

在 Mistral Small 3 (2501) 的基礎上,Mistral Small 3.1 (2503) 增加了最先進的視覺理解能力,並將長上下文能力提升至 128k 詞元,同時不影響文字效能。該模型擁有 240 億個引數,在文字和視覺任務中均達到了頂尖水平。

它適用於

  • 快速響應的對話代理。
  • 低延遲函式呼叫。
  • 透過微調實現主題專家功能。
  • 針對愛好者和處理敏感資料的組織進行本地推理。
  • 程式設計和數學推理。
  • 長文件理解。
  • 視覺理解。

此模型由 cyrilvallezyonigozlan 貢獻。

原始程式碼可在 此處此處 找到。

使用示例

使用 Pipeline 進行推理

以下是如何使用 image-text-to-text pipeline,僅需幾行程式碼即可對 Mistral3 模型進行推理:

>>> from transformers import pipeline

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "image",
...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
...             },
...             {"type": "text", "text": "Describe this image."},
...         ],
...     },
... ]

>>> pipe = pipeline("image-text-to-text", model="mistralai/Mistral-Small-3.1-24B-Instruct-2503", torch_dtype=torch.bfloat16)
>>> outputs = pipe(text=messages, max_new_tokens=50, return_full_text=False)
>>> outputs[0]["generated_text"]
'The image depicts a vibrant and lush garden scene featuring a variety of wildflowers and plants. The central focus is on a large, pinkish-purple flower, likely a Greater Celandine (Chelidonium majus), with a'

對單張影像進行推理

此示例演示瞭如何使用聊天模板對 Mistral3 模型進行單張影像推理。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
...             {"type": "text", "text": "Describe this image"},
...         ],
...     }
... ]

>>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

>>> generate_ids = model.generate(**inputs, max_new_tokens=20)
>>> decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)

>>> decoded_output
"The image depicts two cats lying on a pink blanket. The larger cat, which appears to be an"...

僅文字生成

此示例展示瞭如何在不提供任何影像輸入的情況下,使用 Mistral3 模型生成文字。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = ".mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> SYSTEM_PROMPT = "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat."
>>> user_prompt = "Give me 5 non-formal ways to say 'See you later' in French."

>>> messages = [
...    {"role": "system", "content": SYSTEM_PROMPT},
...    {"role": "user", "content": user_prompt},
... ]

>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=text, return_tensors="pt").to(0, dtype=torch.float16)
>>> generate_ids = model.generate(**inputs, max_new_tokens=50, do_sample=False)
>>> decoded_output = processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)[0]

>>> print(decoded_output)
"1. À plus tard!
2. Salut, à plus!
3. À toute!
4. À la prochaine!
5. Je me casse, à plus!

```
 /\_/\
( o.o )
 > ^ <
```"

批次影像和文字輸入

Mistral3 模型還支援批次影像和文字輸入。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> messages = [
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"},
...                 {"type": "text", "text": "Write a haiku for this image"},
...             ],
...         },
...     ],
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
...                 {"type": "text", "text": "Describe this image"},
...             ],
...         },
...     ],
... ]


>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

>>> output = model.generate(**inputs, max_new_tokens=25)

>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
>>> decoded_outputs
["Write a haiku for this imageCalm waters reflect\nWhispers of the forest's breath\nPeace on wooden path"
, "Describe this imageThe image depicts a vibrant street scene in what appears to be a Chinatown district. The focal point is a traditional Chinese"]

批次多影像輸入和使用 BitsAndBytes 進行量化

此 Mistral3 模型的實現支援帶有不同影像數量的批次文字影像輸入。此示例還展示瞭如何使用 BitsAndBytes 載入 4 位量化模型。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> quantization_config = BitsAndBytesConfig(load_in_4bit=True)
>>> model = AutoModelForImageTextToText.from_pretrained(
...     model_checkpoint, quantization_config=quantization_config
... )

>>> messages = [
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"},
...                 {"type": "text", "text": "Write a haiku for this image"},
...             ],
...         },
...     ],
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"},
...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"},
...                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"},
...             ],
...         },
...     ],
>>> ]

>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16)

>>> output = model.generate(**inputs, max_new_tokens=25)

>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
>>> decoded_outputs
["Write a haiku for this imageSure, here is a haiku inspired by the image:\n\nCalm lake's wooden path\nSilent forest stands guard\n", "These images depict two different landmarks. Can you identify them? Certainly! The images depict two iconic landmarks:\n\n1. The first image shows the Statue of Liberty in New York City."]

Mistral3Config

class transformers.Mistral3Config

< >

( vision_config = None text_config = None image_token_index = 10 projector_hidden_act = 'gelu' vision_feature_layer = -1 multimodal_projector_bias = False spatial_merge_size = 2 **kwargs )

引數

  • vision_config (Union[AutoConfig, dict], 可選, 預設為 PixtralVisionConfig) — 視覺骨幹網路的配置物件或字典。
  • text_config (Union[AutoConfig, dict], 可選, 預設為 MistralConfig) — 文字骨幹網路的配置物件或字典。
  • image_token_index (int, 可選, 預設為 10) — 用於編碼影像提示的影像詞元索引。
  • projector_hidden_act (str, 可選, 預設為 "gelu") — 多模態投影器使用的啟用函式。
  • vision_feature_layer (Union[int, list[int]], 可選, 預設為 -1) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將連線起來形成視覺特徵。
  • multimodal_projector_bias (bool, 可選, 預設為 False) — 是否在多模態投影器中使用偏差。
  • spatial_merge_size (int, 可選, 預設為 2) — 空間合併操作的下采樣因子。

這是用於儲存 Mistral3ForConditionalGeneration 配置的配置類。它用於根據指定的引數例項化 Mistral3 模型,定義模型架構。使用預設配置例項化將產生與 mistralai/Mistral-Small-3.1-24B-Instruct-2503 類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請參閱 PretrainedConfig 的文件。

示例

>>> from transformers import Mistral3ForConditionalGeneration, Mistral3Config, PixtralVisionConfig, MistralConfig

>>> # Initializing a Pixtral-vision config
>>> vision_config = PixtralVisionConfig()

>>> # Initializing a Mistral config
>>> text_config = MistralConfig()

>>> # Initializing a Mistral3 configuration
>>> configuration = Mistral3Config(vision_config, text_config)

>>> # Initializing a model from the mistral3.1 configuration
>>> model = Mistral3ForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Mistral3Model

class transformers.Mistral3Model

< >

( config: Mistral3Config )

引數

  • config (Mistral3Config) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。檢視 from_pretrained() 方法以載入模型權重。

Mistral3 模型由視覺骨幹網路和語言模型組成,不包含語言建模頭。

此模型繼承自 PreTrainedModel。查閱超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)

此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件以獲取所有與通用用法和行為相關的事項。

正向

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, list[int], NoneType] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None image_sizes: Tensor = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) transformers.models.mistral3.modeling_mistral3.Mistral3ModelOutputWithPasttuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor, 形狀為 (batch_size, sequence_length)) — 詞彙表中輸入序列詞元的索引。預設情況下會忽略填充。

    索引可以使用 AutoTokenizer 獲取。詳情請參見 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • pixel_values (torch.FloatTensor, 形狀為 (batch_size, num_channels, image_size, image_size)) — 對應輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。詳情請參見 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 進行影像處理)。
  • attention_mask (torch.Tensor, 形狀為 (batch_size, sequence_length), 可選) — 掩碼,避免對填充詞元索引執行注意力。掩碼值選擇在 [0, 1] 之間:

    • 1 表示未被掩蓋的詞元,
    • 0 表示被掩蓋的詞元。

    什麼是注意力掩碼?

  • position_ids (torch.LongTensor, 形狀為 (batch_size, sequence_length), 可選) — 每個輸入序列詞元在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是位置 ID?

  • past_key_values (list[torch.FloatTensor], 可選) — 預計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常包括模型在解碼上一階段返回的 past_key_values,當 use_cache=Trueconfig.use_cache=True 時。

    允許兩種格式:

    • 一個 Cache 例項,請參閱我們的 kv 快取指南
    • 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量)。這也被稱為傳統快取格式。

    模型將輸出與輸入相同的快取格式。如果未傳遞 past_key_values,則將返回傳統快取格式。

    如果使用 past_key_values,使用者可以選擇僅輸入形狀為 (batch_size, 1) 的最新 input_ids(那些沒有將其過去的鍵值狀態提供給此模型的),而不是所有形狀為 (batch_size, sequence_length)input_ids

  • inputs_embeds (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size), 可選) — 可選地,您可以使用嵌入表示直接傳遞,而不是傳遞 input_ids。如果您希望對如何將 input_ids 索引轉換為相關向量有更多控制,而不是模型內部的嵌入查詢矩陣,這將非常有用。
  • vision_feature_layer (Union[int, list[int], NoneType]) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將連線起來形成視覺特徵。
  • use_cache (bool, 可選) — 如果設定為 True,將返回 past_key_values 鍵值狀態,可用於加速解碼(參見 past_key_values)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參見返回張量中的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參見返回張量中的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 物件而不是純元組。
  • cache_position (torch.LongTensor, 形狀為 (sequence_length), 可選) — 表示輸入序列詞元在序列中位置的索引。與 position_ids 相反,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。
  • image_sizes (torch.Tensor, 形狀為 (batch_size, 2)) — 批次影像的大小,每張影像為 (高度, 寬度)。

返回

transformers.models.mistral3.modeling_mistral3.Mistral3ModelOutputWithPasttuple(torch.FloatTensor)

一個 transformers.models.mistral3.modeling_mistral3.Mistral3ModelOutputWithPast 或一個 torch.FloatTensor 元組(如果傳遞 return_dict=False 或當 config.return_dict=False 時),包含根據配置(Mistral3Config)和輸入的不同元素。

  • last_hidden_state (形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可選) — 模型最後一層輸出的隱藏狀態序列。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可選, 當傳遞 use_cache=True 或當 config.use_cache=True 時返回) — 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含兩個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量。

    包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • hidden_states (tuple[torch.FloatTensor, ...], 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — 形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元組(如果模型有嵌入層,則一個用於嵌入層的輸出,加上一個用於每個層的輸出)。

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple[torch.FloatTensor, ...], 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元組(每個層一個)。

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

  • image_hidden_states (torch.FloatTensor, 可選) — 形狀為 (batch_size, num_images, sequence_length, hidden_size)torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的模型 image_hidden_states

Mistral3Model 的 forward 方法,覆蓋了 __call__ 特殊方法。

雖然前向傳播的實現需要在該函式中定義,但之後應該呼叫 Module 例項而不是此函式,因為前者會處理執行預處理和後處理步驟,而後者會靜默忽略它們。

get_image_features

< >

( pixel_values: FloatTensor image_sizes: Tensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None **kwargs ) image_features (torch.Tensor)

引數

  • pixel_values (torch.FloatTensor],形狀為 (batch_size, channels, height, width)) — 對應輸入影像的張量。
  • vision_feature_layer (Union[int, list[int]], 可選) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線以形成視覺特徵。
  • image_sizes (torch.Tensor, 可選) — 包含由處理器返回的影像尺寸的張量。

返回

image_features (torch.Tensor)

形狀為 (num_images, image_length, embed_dim) 的影像特徵張量。

從視覺塔獲取影像最後隱藏狀態並應用多模態投影。

Mistral3ForConditionalGeneration

class transformers.Mistral3ForConditionalGeneration

< >

( config: Mistral3Config )

引數

  • config (Mistral3Config) — 模型的配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法載入模型權重。

MISTRAL3 模型,由視覺骨幹和語言模型組成。

此模型繼承自 PreTrainedModel。查閱超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)

此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件以獲取所有與通用用法和行為相關的事項。

正向

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 image_sizes: typing.Optional[torch.Tensor] = None **kwargs: typing_extensions.Unpack[transformers.models.mistral3.modeling_mistral3.KwargsForCausalLM] ) transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPasttuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是 input ID?

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size)) — 對應輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • attention_mask (torch.Tensor,形狀為 (batch_size, sequence_length)可選) — 掩碼,用於避免在填充 token 索引上執行注意力。掩碼值選擇在 [0, 1] 中:

    • 1 表示 未被掩蓋 的 token,
    • 0 表示 被掩蓋 的 token。

    什麼是注意力掩碼?

  • position_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是位置 ID?

  • past_key_values (list[torch.FloatTensor], 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常由模型在解碼前一階段返回的 past_key_values 組成,當 use_cache=Trueconfig.use_cache=True 時。

    允許兩種格式:

    • Cache 例項,請參閱我們的 kv 快取指南
    • 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含兩個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量。這也被稱為傳統快取格式。

    模型將輸出與輸入相同的快取格式。如果未傳遞 past_key_values,將返回傳統快取格式。

    如果使用 past_key_values,使用者可以選擇只輸入形狀為 (batch_size, 1) 的最後一個 input_ids(那些沒有將其過去的鍵值狀態提供給此模型的 token),而不是形狀為 (batch_size, sequence_length) 的所有 input_ids

  • inputs_embeds (torch.FloatTensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 可選地,您可以選擇直接傳遞嵌入表示,而不是傳遞 input_ids。如果您希望對如何將 input_ids 索引轉換為相關向量有更多控制,而不是模型內部的嵌入查詢矩陣,這會很有用。
  • labels (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 用於計算掩碼語言模型損失的標籤。索引應為 [0, ..., config.vocab_size] 或 -100(請參閱 input_ids 文件字串)。索引設定為 -100 的 token 將被忽略(被掩蓋),損失僅針對標籤在 [0, ..., config.vocab_size] 中的 token 計算。
  • use_cache (bool, 可選) — 如果設定為 True,將返回 past_key_values 鍵值狀態,可用於加速解碼(請參閱 past_key_values)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是純元組。
  • cache_position (torch.LongTensor,形狀為 (sequence_length)可選) — 表示輸入序列 token 在序列中位置的索引。與 position_ids 不同,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。
  • logits_to_keep (Union[int, torch.Tensor], 預設為 0) — 如果是 int,則計算最後 logits_to_keep 個 token 的 logits。如果是 0,則計算所有 input_ids 的 logits(特殊情況)。生成時只需要最後一個 token 的 logits,只計算該 token 可以節省記憶體,這對於長序列或大詞彙量來說非常重要。如果是 torch.Tensor,則必須是 1D,對應於在序列長度維度中要保留的索引。這在使用打包張量格式(批次和序列長度的單一維度)時很有用。
  • image_sizes (torch.Tensor,形狀為 (batch_size, 2)可選) — 批次中影像的大小張量,每個影像為 (height, width)。

返回

transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPasttuple(torch.FloatTensor)

一個 transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPast 或一個 torch.FloatTensor 元組(如果傳遞 return_dict=False 或當 config.return_dict=False 時),包含根據配置(Mistral3Config)和輸入的不同元素。

  • loss (torch.FloatTensor 形狀為 (1,)可選,當提供 labels 時返回) — 語言建模損失(用於下一個 token 預測)。

  • logits (形狀為 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 語言建模頭部的預測分數(SoftMax 之前的每個詞彙標記的分數)。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可選, 當傳遞 use_cache=True 或當 config.use_cache=True 時返回) — 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含兩個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量。

    包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • hidden_states (tuple[torch.FloatTensor], 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — 形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元組(如果模型有嵌入層,則一個用於嵌入層的輸出,加上一個用於每個層的輸出)。

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple[torch.FloatTensor], 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元組(每個層一個)。

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

  • image_hidden_states (torch.FloatTensor, 可選) — 形狀為 (batch_size, num_images, sequence_length, hidden_size)torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的模型 image_hidden_states

Mistral3ForConditionalGeneration 的 forward 方法,覆蓋了 __call__ 特殊方法。

雖然前向傳播的實現需要在該函式中定義,但之後應該呼叫 Module 例項而不是此函式,因為前者會處理執行預處理和後處理步驟,而後者會靜默忽略它們。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration

>>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
>>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")

>>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(images=image, text=prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is the image?The image depicts two cats lying on a pink blanket."
< > 在 GitHub 上更新

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