Transformers 文件
Idefics2
並獲得增強的文件體驗
開始使用
Idefics2
概述
Idefics2 模型由 Léo Tronchon、Hugo Laurencon 和 Victor Sanh 在構建視覺語言模型時什麼重要?中提出。隨附的部落格文章可在此處找到。
Idefics2 是一個開放的多模態模型,它接受任意影像和文字輸入序列並生成文字輸出。該模型可以回答關於影像的問題,描述視覺內容,建立基於多幅影像的故事,或者在沒有視覺輸入的情況下簡單地作為純語言模型執行。它在文件理解、OCR 或視覺推理方面比 IDEFICS-1 有顯著改進。Idefics2 輕量級(80 億引數),並以其原始寬高比和解析度處理影像,這使得推理效率各異。
論文摘要如下:
大型語言模型和視覺 Transformer 的改進推動了人們對視覺語言模型(VLM)日益增長的興趣。儘管關於這個主題的文獻很多,但我們發現關於 VLM 設計的關鍵決策往往沒有得到證實。我們認為這些未經支援的決策阻礙了該領域的進展,因為它使識別哪些選擇能提高模型效能變得困難。為了解決這個問題,我們圍繞預訓練模型、架構選擇、資料和訓練方法進行了大量實驗。我們的研究結果整合包括開發 Idefics2,一個高效的基礎 VLM,擁有 80 億引數。Idefics2 在各種多模態基準測試中,在其規模類別內實現了最先進的效能,並且通常與大小是其四倍的模型不相上下。我們釋出了該模型(基礎版、指令版和聊天版)以及為其訓練建立的資料集。

此模型由amyeroberts貢獻。原始程式碼可在此處找到。
使用技巧
- 每個樣本可以包含多個影像,並且影像數量在不同樣本之間可以變化。處理器會將輸入填充到批處理中影像的最大數量,以供模型輸入。
- 處理器有一個 `do_image_splitting` 選項。如果為 `True`,則每個輸入影像將被分割成 4 個子影像,並與原始影像連線形成 5 個影像。這對於提高模型效能很有用。如果模型在訓練時沒有使用此選項,請確保將 `processor.image_processor.do_image_splitting` 設定為 `False`。
- 傳遞給處理器的 `text` 應在應插入影像的位置包含 `
` 標記。如果文字是聊天訊息,則在每個話語的末尾應包含 ` `。 - 處理器有自己的 `apply_chat_template` 方法,用於將聊天訊息轉換為文字,然後可以將該文字作為 `text` 傳遞給處理器。
如何在聊天訊息上使用處理器的示例
import requests
from PIL import Image
from transformers import Idefics2Processor, Idefics2ForConditionalGeneration
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg"
image_1 = Image.open(requests.get(url_1, stream=True).raw)
image_2 = Image.open(requests.get(url_2, stream=True).raw)
images = [image_1, image_2]
messages = [{
"role": "user",
"content": [
{"type": "text", "text": "What’s the difference between these two images?"},
{"type": "image"},
{"type": "image"},
],
}]
processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b")
model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b")
model.to(device)
# at inference time, one needs to pass `add_generation_prompt=True` in order to make sure the model completes the prompt
text = processor.apply_chat_template(messages, add_generation_prompt=True)
print(text)
# 'User: What’s the difference between these two images?<image><image><end_of_utterance>\nAssistant:'
inputs = processor(images=images, text=text, return_tensors="pt").to(device)
generated_text = model.generate(**inputs, max_new_tokens=500)
generated_text = processor.batch_decode(generated_text, skip_special_tokens=True)[0]
print("Generated text:", generated_text)
- 在訓練期間,確定模型不應學習哪些 token 非常重要。對於 Idefics2 來說,這通常歸結為影像和填充 token。這意味著可以按如下方式建立標籤:
import requests
from PIL import Image
from transformers import Idefics2Processor, Idefics2ForConditionalGeneration
import torch
url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg"
image_1 = Image.open(requests.get(url_1, stream=True).raw)
image_2 = Image.open(requests.get(url_2, stream=True).raw)
images = [image_1, image_2]
messages = [{
"role": "user",
"content": [
{"type": "text", "text": "What’s the difference between these two images?"},
{"type": "image"},
{"type": "image"},
],
},
{
"role": "assistant",
"content": [
{"type": "text", "text": "The difference is that one image is about dogs and the other one about cats."},
],
}]
device = "cuda" if torch.cuda.is_available() else "cpu"
processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b")
model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b")
model.to(device)
text = processor.apply_chat_template(messages, add_generation_prompt=False)
inputs = processor(images=images, text=text, return_tensors="pt").to(device)
labels = inputs.input_ids.clone()
labels[labels == processor.tokenizer.pad_token_id] = -100
labels[labels == model.config.image_token_id] = -100
inputs["labels"] = labels
outputs = model(**inputs)
loss = outputs.loss
loss.backward()
請注意,當在使用者和助手之間的多輪對話中訓練 Idefics2 時,通常還會將所有對應於使用者訊息的 token 設定為 -100。
模型最佳化:Flash Attention
上述程式碼片段展示了沒有任何最佳化技巧的推理。然而,透過利用模型內部使用的更快注意力機制實現 Flash Attention,可以大大加快模型速度。
首先,請確保安裝最新版本的 Flash Attention 2,以包含滑動視窗注意力功能。
pip install -U flash-attn --no-build-isolation
另外,請確保您的硬體與 Flash-Attention 2 相容。有關更多資訊,請參閱 Flash Attention 倉庫的官方文件。同時,請確保以半精度(例如 `torch.float16`)載入模型。
要使用 Flash Attention-2 載入和執行模型,只需將上面的程式碼片段更改為以下內容
model = Idefics2ForConditionalGeneration.from_pretrained(
"HuggingFaceM4/idefics2-8b",
+ torch_dtype=torch.float16,
+ attn_implementation="flash_attention_2",
).to(device)
使用量化縮小 Idefics2
由於 Idefics2 模型有 80 億引數,在半精度(float16)下大約需要 16GB 的 GPU RAM,因為每個引數儲存為 2 位元組。但是,可以使用量化來縮小模型大小。如果模型量化到 4 位(或每個引數半位元組),則只需要大約 3.5GB 的 RAM。
量化模型只需將 `quantization_config` 傳遞給模型即可。可以將上述程式碼片段更改為以下內容。我們將利用 BitsAndyBytes 量化(但請參閱此頁面瞭解其他量化方法)
+ from transformers import BitsAndBytesConfig
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_quant_type="nf4",
+ bnb_4bit_use_double_quant=True,
+ bnb_4bit_compute_dtype=torch.float16
+ )
model = Idefics2ForConditionalGeneration.from_pretrained(
"HuggingFaceM4/idefics2-8b",
+ torch_dtype=torch.float16,
+ quantization_config=quantization_config,
).to(device)
資源
一份官方 Hugging Face 和社群(用🌎表示)資源列表,幫助您開始使用 Idefics2。如果您有興趣提交資源以包含在此處,請隨時開啟 Pull Request,我們將對其進行稽核!資源最好能展示一些新內容,而不是重複現有資源。
- 關於如何使用 Trainer 在自定義資料集上微調 Idefics2 的 Notebook 可以在此處找到。它支援完全微調和(量化)LoRa。
- 有關如何使用 TRL 庫微調 Idefics2 的指令碼可在此處找到。
- 有關微調 Idefics2 用於 JSON 提取用例的演示 Notebook 可以在此處找到。🌎
Idefics2Config
class transformers.Idefics2Config
< 來源 >( use_cache = True image_token_id = 32001 tie_word_embeddings = False vision_config = None perceiver_config = None text_config = None **kwargs )
引數
- use_cache (
bool
, 可選, 預設為True
) — 模型是否應快取注意力機制的關鍵/值對。 - image_token_id (
int
, 可選, 預設為 32001) — “影像” token 的 ID。 - tie_word_embeddings (
bool
, 可選, 預設為False
) — 是否將詞嵌入與 token 嵌入繫結。 - vision_config (
IdeficsVisionConfig
或dict
, 可選) — 自定義視覺配置或字典 - perceiver_config (
IdeficsPerceiverConfig
或dict
, 可選) — 自定義感知器配置或字典 - text_config (
MistralConfig
或dict
, 可選) — 文字模型的自定義文字配置或字典
這是儲存 Idefics2Model 配置的配置類。它用於根據指定引數例項化 Idefics2 模型,定義模型架構。使用預設值例項化配置將產生與 Idefics2 HuggingFaceM4/idefics2-8b 架構模型相似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
Idefics2Model
class transformers.Idefics2Model
< 來源 >( config: Idefics2Config )
引數
- config (Idefics2Config) — 包含模型所有引數的模型配置類。使用配置檔案初始化並不會載入與模型相關的權重,僅載入配置。請查閱 from_pretrained() 方法以載入模型權重。
Idefics2 模型由 SIGLIP 視覺編碼器和 Mistral 語言解碼器組成
此模型繼承自 PreTrainedModel。請查閱超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。請將其作為常規 PyTorch 模組使用,並參閱 PyTorch 文件以瞭解所有與一般使用和行為相關的事項。
forward
< 來源 >( input_ids: typing.Optional[torch.LongTensor] = 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 pixel_values: typing.Optional[torch.FloatTensor] = None pixel_attention_mask: typing.Optional[torch.BoolTensor] = None image_hidden_states: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None return_dict: typing.Optional[bool] = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) → transformers.models.idefics2.modeling_idefics2.Idefics2BaseModelOutputWithPast
或 tuple(torch.FloatTensor)
引數
- input_ids (形狀為
(batch_size, sequence_length)
的torch.LongTensor
, 可選) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參見 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (形狀為
(batch_size, sequence_length)
的torch.Tensor
, 可選) — 避免對填充 token 索引執行注意力的掩碼。掩碼值選擇在[0, 1]
:- 1 表示未被掩碼的 token,
- 0 表示被掩碼的 token。
- position_ids (形狀為
(batch_size, sequence_length)
的torch.LongTensor
, 可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為[0, config.n_positions - 1]
。 - past_key_values (
list[torch.FloatTensor]
, 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常包括模型在解碼上一階段返回的past_key_values
,當use_cache=True
或config.use_cache=True
時。允許兩種格式:
- Cache 例項,請參閱我們的kv 快取指南;
- 長度為
config.n_layers
的tuple(torch.FloatTensor)
元組,每個元組包含形狀為(batch_size, num_heads, sequence_length, embed_size_per_head)
的 2 個張量)。這也稱為舊版快取格式。
模型將輸出與輸入相同的快取格式。如果未傳遞
past_key_values
,則將返回舊版快取格式。如果使用
past_key_values
,使用者可以選擇僅輸入形狀為(batch_size, 1)
的最後一個input_ids
(那些沒有將其過去的鍵值狀態提供給此模型的),而不是形狀為(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (形狀為
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可選) — 或者,您可以選擇直接傳遞嵌入表示,而不是傳遞input_ids
。如果您希望對如何將input_ids
索引轉換為相關向量有比模型內部嵌入查詢矩陣更多的控制,這很有用。 - pixel_values (形狀為
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
, 可選) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}
獲得。有關詳細資訊,請參見{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - pixel_attention_mask (形狀為
(batch_size, image_size, image_size)
的torch.Tensor
, 可選) — 避免對填充畫素索引執行注意力的掩碼。 - image_hidden_states (形狀為
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 經過模態投影和感知器重取樣後,影像編碼器的隱藏狀態。 - use_cache (
bool
, 可選) — 如果設定為True
,則返回past_key_values
鍵值狀態,可用於加速解碼(參見past_key_values
)。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參見返回張量下的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參見返回張量下的hidden_states
。 - cache_position (形狀為
(sequence_length)
的torch.LongTensor
, 可選) — 指示輸入序列 token 在序列中位置的索引。與position_ids
不同,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是普通元組。
返回
transformers.models.idefics2.modeling_idefics2.Idefics2BaseModelOutputWithPast
或 tuple(torch.FloatTensor)
一個 transformers.models.idefics2.modeling_idefics2.Idefics2BaseModelOutputWithPast
或一個 torch.FloatTensor
元組(如果傳遞了 return_dict=False
或 config.return_dict=False
),包含根據配置(Idefics2Config)和輸入的不同元素。
-
last_hidden_state (形狀為
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型最後一層輸出的隱藏狀態序列。如果使用past_key_values
,則只輸出形狀為(batch_size, 1, hidden_size)
的序列的最後一個隱藏狀態。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可選, 當use_cache=True
或config.use_cache=True
時返回) — 長度為config.n_layers
的tuple(torch.FloatTensor)
元組,每個元組包含形狀為(batch_size, num_heads, sequence_length, embed_size_per_head)
的 2 個張量),如果config.is_encoder_decoder=True
則可選地包含形狀為(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的 2 個額外張量。包含預先計算的隱藏狀態(自注意力塊中的鍵和值,如果config.is_encoder_decoder=True
則可選地包含交叉注意力塊中的鍵和值),可用於(參見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 (
tuple(torch.FloatTensor)
, 可選) —torch.FloatTensor
的元組(一個用於影像嵌入的輸出,(batch_size, num_images, sequence_length, hidden_size)
)。影像編碼器和可選的感知器生成的模型影像隱藏狀態。
輸入到模型的影像數量可以任意。為了解決這個問題,輸入到模型的畫素值具有影像填充 -> (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是批處理中 batch_size 樣本中影像的最大數量。
除了在模型入口處填充畫素值外,不需要填充影像。為了提高效率,我們只通過 vision_model 的前向傳遞實際影像,丟棄填充影像,例如大小為 (image_batch_size, 3, height, width) 的畫素值,其中當 num_images_per_sample=[1, 3, 1, 2] 時,image_batch_size 為 7,max_num_images 為 3。
Idefics2ForConditionalGeneration
class transformers.Idefics2ForConditionalGeneration
< 來源 >( config )
引數
- config (Idefics2ForConditionalGeneration) — 模型的配置類,包含模型的所有引數。用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法來載入模型權重。
帶有語言建模頭的 Idefics2 模型。它由一個 SigLIP 視覺編碼器組成,頂部帶有一個語言建模頭。
此模型繼承自 PreTrainedModel。請查閱超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。請將其作為常規 PyTorch 模組使用,並參閱 PyTorch 文件以瞭解所有與一般使用和行為相關的事項。
forward
< 原始碼 >( input_ids: typing.Optional[torch.LongTensor] = 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 pixel_values: typing.Optional[torch.FloatTensor] = None pixel_attention_mask: typing.Optional[torch.BoolTensor] = None image_hidden_states: 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 **kwargs: typing_extensions.Unpack[transformers.models.idefics2.modeling_idefics2.KwargsForCausalLM] ) → transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPast
或 tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
形狀為(batch_size, sequence_length)
,可選) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。索引可以使用 AutoTokenizer 獲取。有關詳細資訊,請參見 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- 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]
之間。 - past_key_values (
list[torch.FloatTensor]
,可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速序列解碼。這通常包括模型在解碼上一階段返回的past_key_values
,當use_cache=True
或config.use_cache=True
時。允許兩種格式:
- Cache 例項,請參見我們的 kv 快取指南;
- 長度為
config.n_layers
的tuple(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
索引如何轉換為相關向量有比模型內部嵌入查詢矩陣更多的控制,這將很有用。 - pixel_values (
torch.FloatTensor
形狀為(batch_size, num_channels, image_size, image_size)
,可選) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}
獲取。有關詳細資訊,請參見{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - pixel_attention_mask (
torch.Tensor
形狀為(batch_size, image_size, image_size)
,可選) — 用於避免對填充畫素索引執行注意力操作的掩碼。 - image_hidden_states (
torch.FloatTensor
形狀為(batch_size, num_channels, image_size, image_size)
) — 影像編碼器在模態投影和感知器重取樣後的隱藏狀態。 - labels (
torch.LongTensor
形狀為(batch_size, sequence_length)
,可選) — 用於計算掩碼語言建模損失的標籤。索引應在[0, ..., config.vocab_size]
或model.image_token_id
(其中model
是Idefics2ForConditionalGeneration
的例項)中。索引設定為model.image_token_id
的 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,對應於在序列長度維度中要保留的索引。這在使用 packed tensor 格式(批次和序列長度的單維度)時很有用。
返回
transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPast
或 tuple(torch.FloatTensor)
一個 transformers.models.idefics2.modeling_idefics2.Idefics2CausalLMOutputWithPast
或一個 torch.FloatTensor
元組(如果傳入 return_dict=False
或 config.return_dict=False
),包含根據配置 (Idefics2Config) 和輸入的不同元素。
-
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_layers
的tuple(torch.FloatTensor)
元組,每個元組包含 2 個形狀為(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 (
tuple(torch.FloatTensor)
, 可選) —torch.FloatTensor
的元組(一個用於影像嵌入的輸出,(batch_size, num_images, sequence_length, hidden_size)
)。影像編碼器和可選的感知器生成的模型影像隱藏狀態。
Idefics2ForConditionalGeneration 的 forward 方法,重寫了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是直接呼叫此函式,因為前者會處理執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AutoModelForVision2Seq
>>> from transformers.image_utils import load_image
>>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
>>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
>>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
>>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
>>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base")
>>> model = AutoModelForVision2Seq.from_pretrained("HuggingFaceM4/idefics2-8b-base", device_map="auto")
>>> BAD_WORDS_IDS = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
>>> EOS_WORDS_IDS = [processor.tokenizer.eos_token_id]
>>> # Create inputs
>>> prompts = [
... "<image>In this image, we can see the city of New York, and more specifically the Statue of Liberty.<image>In this image,",
... "In which city is that bridge located?<image>",
... ]
>>> images = [[image1, image2], [image3]]
>>> inputs = processor(images=images, text=prompts, padding=True, return_tensors="pt").to("cuda")
>>> # Generate
>>> generated_ids = model.generate(**inputs, bad_words_ids=BAD_WORDS_IDS, max_new_tokens=20)
>>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> print(generated_texts)
['In this image, we can see the city of New York, and more specifically the Statue of Liberty. In this image, we can see the city of New York, and more specifically the Statue of Liberty.\n\n', 'In which city is that bridge located?\n\nThe bridge is located in the city of Pittsburgh, Pennsylvania.\n\n\nThe bridge is']
Idefics2ImageProcessor
類 transformers.Idefics2ImageProcessor
< 原始碼 >( do_convert_rgb: bool = True do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: 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_pad: bool = True do_image_splitting: bool = False **kwargs )
引數
- do_convert_rgb (
bool
,可選,預設為True
) — 是否將影像轉換為 RGB。如果輸入影像是不同格式(例如 RGBA),這將很有用。僅當輸入影像為 PIL 格式時才有效。 - do_resize (
bool
,可選,預設為True
) — 是否調整影像大小。影像的最長邊將調整為小於等於size["longest_edge"]
,最短邊將保持輸入長寬比進行調整,最小尺寸為size["shortest_edge"]
。 - size (
Dict
,可選) — 控制輸出影像的大小。這是一個包含鍵 "shortest_edge" 和 "longest_edge" 的字典。 - resample (
Resampling
,可選,預設為Resampling.BILINEAR
) — 調整影像大小時使用的重取樣濾波器。 - do_rescale (
bool
,可選,預設為True
) — 是否重新縮放影像。如果設定為True
,影像將被重新縮放,使其畫素值在 0 和 1 之間。 - rescale_factor (
float
,可選,預設為1/255
) — 如果do_rescale
設定為True
,則用於重新縮放影像的縮放因子。 - do_normalize (
bool
,可選,預設為True
) — 是否對影像進行歸一化。如果設定為True
,影像將歸一化為具有image_mean
的均值和image_std
的標準差。 - image_mean (
float
或list[float]
,可選,預設為IDEFICS_STANDARD_MEAN
) — 如果對影像進行歸一化,則使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過preprocess
方法中的image_mean
引數覆蓋。 - image_std (
float
或list[float]
,可選,預設為IDEFICS_STANDARD_STD
) — 如果對影像進行歸一化,則使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過preprocess
方法中的image_std
引數覆蓋。 - do_pad (
bool
,可選,預設為True
) — 是否將影像填充到批次中最大的高度和寬度以及批次中每個樣本的影像數量,以便返回的張量形狀為 (batch_size, max_num_images, num_channels, max_height, max_width)。 - do_image_splitting (
bool
,可選,預設為False
) — 是否將影像分成 4 個相等的子影像序列,並與原始影像連線。此策略首次在 https://huggingface.co/papers/2311.06607 中引入。
構造一個 Idefics 影像處理器。
預處理
< 原始碼 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_convert_rgb: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None 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_pad: typing.Optional[bool] = None do_image_splitting: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None input_data_format: typing.Optional[transformers.image_utils.ChannelDimension] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> )
引數
- images (
ImageInput
) — 要預處理的影像列表。 - do_convert_rgb (
bool
,可選,預設為self.do_convert_rgb
) — 是否將影像轉換為 RGB。 - do_resize (
bool
,可選,預設為self.do_resize
) — 是否調整影像大小。 - size (
dict[str, int]
,可選,預設為self.size
) — 調整大小後圖像的尺寸。影像最短邊將調整為 size["shortest_edge"],最長邊將保持輸入長寬比進行調整。 - 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 (
float
或list[float]
,可選,預設為self.image_mean
) — 用於歸一化的影像均值。僅當do_normalize
設定為True
時才有效。 - image_std (
float
或list[float]
,可選,預設為self.image_std
) — 用於歸一化的影像標準差。僅當do_normalize
設定為True
時才有效。 - do_pad (
bool
,可選,預設為self.do_pad
) — 是否將影像填充到批次中最大的高度和寬度。 - do_image_splitting (
bool
,可選,預設為self.do_image_splitting
) — 是否將影像分成 4 個相等的子影像序列,並與原始影像連線。此策略首次在 https://huggingface.co/papers/2311.06607 中引入。 - 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) 格式。
預處理一批影像。
Idefics2ImageProcessorFast
類 transformers.Idefics2ImageProcessorFast
< 原始碼 >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
構建一個快速的Idefics2影像處理器。
預處理
< 來源 >( 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.idefics2.image_processing_idefics2_fast.Idefics2FastImageProcessorKwargs] ) → <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
, 可選) — 如果尺寸為整數,是否預設調整為方形影像。 - 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 - do_image_splitting (
bool
, 可選, 預設為False
) — 是否將影像分割成4個相等的子影像序列並與原始影像連線。 - do_pad (
bool
, 可選, 預設為True
) — 是否將影像填充到批次中的最大高度和寬度。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/陣列/張量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可選) — 您可以在此處提供一個`tensor_type`,以便在初始化時將整數列表轉換為PyTorch/TensorFlow/Numpy張量。
Idefics2Processor
class transformers.Idefics2Processor
< 來源 >( image_processor tokenizer = None image_seq_len: int = 64 chat_template: typing.Optional[str] = None **kwargs )
引數
- image_processor (
Idefics2ImageProcessor
) — Idefics2ImageProcessor的一個例項。影像處理器是必需輸入。 - tokenizer (
PreTrainedTokenizerBase
, 可選) — PreTrainedTokenizerBase的一個例項。這應該與模型的文字模型相對應。分詞器是必需輸入。 - image_seq_len (
int
, 可選, 預設為 64) — 影像序列的長度,即輸入中每張影像的
標記數量。此引數用於根據輸入提示和影像標記構建字串,應與所用模型的config.perceiver_config.resampler_n_latents值匹配。 - chat_template (
str
, 可選) — 一個Jinja模板,用於將聊天中的訊息列表轉換為可分詞字串。
構建一個IDEFICS2處理器,它將LLama分詞器和IDEFICS2影像處理器封裝成一個單一的處理器。
IdeficsProcessor提供了Idefics2ImageProcessor和LlamaTokenizerFast的所有功能。有關更多資訊,請參閱call()和decode()
的文件字串。
__call__
< 來源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], ForwardRef('torch.Tensor')], list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], ForwardRef('torch.Tensor']]], list[list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], ForwardRef('torch.Tensor']]]]] = None text: typing.Union[str, ForwardRef('PreTokenizedInput'), list[str], list['PreTokenizedInput']] = None audio = None videos = None **kwargs: typing_extensions.Unpack[transformers.models.idefics2.processing_idefics2.Idefics2ProcessorKwargs] )
引數
- images (
PIL.Image.Image
,np.ndarray
,torch.Tensor
,list[PIL.Image.Image]
,list[np.ndarray]
,list[torch.Tensor]
, 可選) — 要準備的影像或批次影像。每張影像可以是PIL影像、NumPy陣列或PyTorch張量。如果是list[ImageInput]
型別,則假定這是單個提示(即批次大小為1)。 - text (
Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]
, 可選) — 要編碼的序列或批次序列。每個序列可以是字串或字串列表(預分詞字串)。如果序列以字串列表(預分詞)形式提供,您必須設定is_split_into_words=True
(以消除與批次序列的歧義)。無論在哪裡遇到影像標記
,它都會擴充套件為
+image_seq_len
`。 - return_tensors (
Union[str, TensorType]
, 可選) — 如果設定,將返回特定框架的張量。有關更多資訊,請參閱PreTrainedTokenizerFast.call()。
處理輸入提示並返回BatchEncoding。
示例
>>> import requests
>>> from transformers import Idefics2Processor
>>> from transformers.image_utils import load_image
>>> processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b", image_seq_len=2)
>>> processor.image_processor.do_image_splitting = False # Force as False to simplify the example
>>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
>>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"
>>> image1, image2 = load_image(url1), load_image(url2)
>>> images = [[image1], [image2]]
>>> text = [
... "<image>In this image, we see",
... "bla bla bla<image>",
... ]
>>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
>>> input_ids = outputs.input_ids
>>> input_tokens = processor.tokenizer.batch_decode(input_ids)
>>> print(input_tokens)
['<s><fake_token_around_image><image><image><fake_token_around_image> In this image, we see', '<s> bla bla bla<fake_token_around_image><image><image><fake_token_around_image>']