Transformers 文件
Qwen2Audio
並獲得增強的文件體驗
開始使用
Qwen2Audio
概述
Qwen2-Audio是Qwen團隊推出的大型音訊-語言模型新系列。Qwen2-Audio能夠接收各種音訊訊號輸入,並根據語音指令執行音訊分析或直接文字響應。我們引入了兩種不同的音訊互動模式
- 語音聊天:使用者可以自由地與Qwen2-Audio進行語音互動,無需文字輸入
- 音訊分析:使用者可以在互動過程中提供音訊和文字指令進行分析
該模型由Yunfei Chu, Jin Xu, Qian Yang, Haojie Wei, Xipin Wei, Zhifang Guo, Yichong Leng, Yuanjun Lv, Jinzheng He, Junyang Lin, Chang Zhou, Jingren Zhou在Qwen2-Audio 技術報告中提出。
論文摘要如下:
我們介紹了Qwen-Audio的最新進展,這是一個名為Qwen2-Audio的大型音訊-語言模型,它能夠接收各種音訊訊號輸入,並根據語音指令執行音訊分析或直接文字響應。與複雜的層次化標籤不同,我們透過利用自然語言提示進行不同的資料和任務,簡化了預訓練過程,並進一步擴大了資料量。我們提升了Qwen2-Audio的指令遵循能力,並實現了語音聊天和音訊分析兩種不同的音訊互動模式。在語音聊天模式下,使用者可以自由地與Qwen2-Audio進行語音互動,無需文字輸入。在音訊分析模式下,使用者可以在互動過程中提供音訊和文字指令進行分析。請注意,我們不使用任何系統提示來切換語音聊天和音訊分析模式。Qwen2-Audio能夠智慧地理解音訊內容,並遵循語音命令進行適當響應。例如,在一個同時包含聲音、多說話人對話和語音命令的音訊片段中,Qwen2-Audio可以直接理解命令並提供對音訊的解釋和響應。此外,DPO優化了模型在事實性和遵循預期行為方面的效能。根據AIR-Bench的評估結果,Qwen2-Audio在以音訊為中心的指令遵循能力測試中,表現優於之前的SOTA模型,如Gemini-1.5-pro。Qwen2-Audio是開源的,旨在促進多模態語言社群的進步。
使用提示
Qwen2-Audio-7B
和Qwen2-Audio-7B-Instruct
可在Huggingface Hub上找到
[!注意] 當使用除“eager”之外的所有注意力實現時,`head_mask`引數將被忽略。如果你有`head_mask`並且希望它生效,請使用`XXXModel.from_pretrained(model_id, attn_implementation="eager")`載入模型。
推理
from io import BytesIO
from urllib.request import urlopen
import librosa
from transformers import AutoProcessor, Qwen2AudioForConditionalGeneration
model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B", trust_remote_code=True, device_map="auto")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B", trust_remote_code=True)
prompt = "<|audio_bos|><|AUDIO|><|audio_eos|>Generate the caption in English:"
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Audio/glass-breaking-151256.mp3"
audio, sr = librosa.load(BytesIO(urlopen(url).read()), sr=processor.feature_extractor.sampling_rate)
inputs = processor(text=prompt, audios=audio, return_tensors="pt").to(model.device)
generate_ids = model.generate(**inputs, max_length=256)
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
# We can also omit the audio_bos and audio_eos tokens
prompt = "<|AUDIO|>Generate the caption in English:"
inputs = processor(text=prompt, audios=audio, return_tensors="pt").to(model.device)
generate_ids = model.generate(**inputs, max_length=256)
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
下面,我們演示如何使用Qwen2-Audio-7B-Instruct
進行推理,支援語音聊天和音訊分析兩種模式。請注意,我們使用ChatML格式進行對話,在此演示中,我們展示如何利用apply_chat_template
來實現此目的。
語音聊天推理
在語音聊天模式下,使用者可以自由地與Qwen2-Audio進行語音互動,無需文字輸入
from io import BytesIO
from urllib.request import urlopen
import librosa
from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct")
model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct", device_map="auto")
conversation = [
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/guess_age_gender.wav"},
]},
{"role": "assistant", "content": "Yes, the speaker is female and in her twenties."},
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav"},
]},
]
text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
audios = []
for message in conversation:
if isinstance(message["content"], list):
for ele in message["content"]:
if ele["type"] == "audio":
audios.append(librosa.load(
BytesIO(urlopen(ele['audio_url']).read()),
sr=processor.feature_extractor.sampling_rate)[0]
)
inputs = processor(text=text, audios=audios, return_tensors="pt", padding=True)
inputs.input_ids = inputs.input_ids.to("cuda")
generate_ids = model.generate(**inputs, max_length=256)
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
音訊分析推理
在音訊分析中,使用者可以同時提供音訊和文字指令進行分析
from io import BytesIO
from urllib.request import urlopen
import librosa
from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct")
model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct", device_map="auto")
conversation = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"},
{"type": "text", "text": "What's that sound?"},
]},
{"role": "assistant", "content": "It is the sound of glass shattering."},
{"role": "user", "content": [
{"type": "text", "text": "What can you do when you hear that?"},
]},
{"role": "assistant", "content": "Stay alert and cautious, and check if anyone is hurt or if there is any damage to property."},
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/1272-128104-0000.flac"},
{"type": "text", "text": "What does the person say?"},
]},
]
text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
audios = []
for message in conversation:
if isinstance(message["content"], list):
for ele in message["content"]:
if ele["type"] == "audio":
audios.append(
librosa.load(
BytesIO(urlopen(ele['audio_url']).read()),
sr=processor.feature_extractor.sampling_rate)[0]
)
inputs = processor(text=text, audios=audios, return_tensors="pt", padding=True)
inputs.input_ids = inputs.input_ids.to("cuda")
generate_ids = model.generate(**inputs, max_length=256)
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
批次推理
我們也支援批次推理
from io import BytesIO
from urllib.request import urlopen
import librosa
from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct")
model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct", device_map="auto")
conversation1 = [
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"},
{"type": "text", "text": "What's that sound?"},
]},
{"role": "assistant", "content": "It is the sound of glass shattering."},
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav"},
{"type": "text", "text": "What can you hear?"},
]}
]
conversation2 = [
{"role": "user", "content": [
{"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/1272-128104-0000.flac"},
{"type": "text", "text": "What does the person say?"},
]},
]
conversations = [conversation1, conversation2]
text = [processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False) for conversation in conversations]
audios = []
for conversation in conversations:
for message in conversation:
if isinstance(message["content"], list):
for ele in message["content"]:
if ele["type"] == "audio":
audios.append(
librosa.load(
BytesIO(urlopen(ele['audio_url']).read()),
sr=processor.feature_extractor.sampling_rate)[0]
)
inputs = processor(text=text, audios=audios, return_tensors="pt", padding=True)
inputs['input_ids'] = inputs['input_ids'].to("cuda")
inputs.input_ids = inputs.input_ids.to("cuda")
generate_ids = model.generate(**inputs, max_length=256)
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
Qwen2AudioConfig
class transformers.Qwen2AudioConfig
< 來源 >( audio_config = None text_config = None audio_token_index = 151646 **kwargs )
這是用於儲存Qwen2AudioForConditionalGeneration配置的配置類。它用於根據指定的引數例項化Qwen2-Audio模型,定義模型架構。使用預設值例項化配置將生成類似於Qwen2-Audio的配置。
配置物件繼承自PretrainedConfig,可用於控制模型輸出。有關更多資訊,請參閱PretrainedConfig的文件。
示例
>>> from transformers import Qwen2AudioForConditionalGeneration, Qwen2AudioConfig, Qwen2AudioEncoderConfig, Qwen2Config
>>> # Initializing a Qwen2AudioEncoder config
>>> audio_config = Qwen2AudioEncoderConfig()
>>> # Initializing a Qwen2 config
>>> text_config = Qwen2Config()
>>> # Initializing a Qwen2Audio configuration
>>> configuration = Qwen2AudioConfig(audio_config, text_config)
>>> # Initializing a model from the qwen2-audio style configuration
>>> model = Qwen2AudioForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Qwen2AudioEncoderConfig
class transformers.Qwen2AudioEncoderConfig
< 來源 >( num_mel_bins = 128 encoder_layers = 32 encoder_attention_heads = 20 encoder_ffn_dim = 5120 encoder_layerdrop = 0.0 d_model = 1280 dropout = 0.0 attention_dropout = 0.0 activation_function = 'gelu' activation_dropout = 0.0 scale_embedding = False initializer_range = 0.02 max_source_positions = 1500 **kwargs )
引數
- num_mel_bins (
int
, 可選, 預設為 128) — 每個輸入特徵中使用的梅爾特徵數量。應與Qwen2AudioProcessor
類中使用的值對應。 - encoder_layers (
int
, 可選, 預設為 32) — 編碼器層數。 - encoder_attention_heads (
int
, 可選, 預設為 20) — Transformer編碼器中每個注意力層的注意力頭數量。 - encoder_ffn_dim (
int
, 可選, 預設為 5120) — 編碼器中“中間”(通常稱為前饋)層的維度。 - encoder_layerdrop (
float
, 可選, 預設為 0.0) — 編碼器的LayerDrop機率。更多詳情請參閱[LayerDrop論文](參見https://huggingface.co/papers/1909.11556)。 - d_model (
int
, 可選, 預設為 1280) — 各層的維度。 - dropout (
float
, 可選, 預設為 0.0) — 嵌入、編碼器和池化器中所有全連線層的丟棄機率。 - attention_dropout (
float
, 可選, 預設為 0.0) — 注意力機率的丟棄率。 - activation_function (
str
, 可選, 預設為"gelu"
) — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果是字串,支援"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - activation_dropout (
float
, 可選, 預設為 0.0) — 全連線層內部啟用的丟棄率。 - scale_embedding (
bool
, 可選, 預設為False
) — 透過除以sqrt(d_model)來縮放嵌入。 - initializer_range (
float
, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態分佈初始化器的標準差。 - max_source_positions (
int
, 可選, 預設為 1500) — 此模型可能使用的對數梅爾濾波器組特徵的最大序列長度。
這是用於儲存Qwen2AudioEncoder配置的配置類。它用於根據指定的引數例項化Qwen2-Audio音訊編碼器,定義模型架構。使用預設值例項化配置將生成類似於Qwen2-Audio架構的音訊編碼器的配置。
配置物件繼承自PretrainedConfig,可用於控制模型輸出。有關更多資訊,請參閱PretrainedConfig的文件。
示例
>>> from transformers import Qwen2AudioEncoderConfig, Qwen2AudioEncoder
>>> # Initializing a Qwen2AudioEncoderConfig
>>> configuration = Qwen2AudioEncoderConfig()
>>> # Initializing a Qwen2AudioEncoder (with random weights)
>>> model = Qwen2AudioEncoder(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Qwen2AudioProcessor
class transformers.Qwen2AudioProcessor
< 來源 >( feature_extractor = None tokenizer = None chat_template = None audio_token = '<|AUDIO|>' audio_bos_token = '<|audio_bos|>' audio_eos_token = '<|audio_eos|>' )
引數
- feature_extractor (WhisperFeatureExtractor, 可選) — 特徵提取器是必需的輸入。
- tokenizer (Qwen2TokenizerFast, 可選) — 分詞器是必需的輸入。
- chat_template (
Optional[str]
, 可選) — 用於格式化對話的Jinja模板。如果未提供,則使用預設的聊天模板。 - audio_token (
str
, 可選, 預設為"<|AUDIO|>"
) — 用於音訊標記的標記。 - audio_bos_token (
str
, 可選, 預設為"<|audio_bos|>"
) — 用於音訊bos標記的標記。 - audio_eos_token (
str
, 可選, 預設為"<|audio_eos|>"
) — 用於音訊eos標記的標記。
構建一個Qwen2Audio處理器,它將Qwen2Audio特徵提取器和Qwen2Audio分詞器包裝到一個單獨的處理器中。
Qwen2AudioProcessor提供了WhisperFeatureExtractor和Qwen2TokenizerFast的所有功能。更多資訊請參閱__call__()
和decode()。
此方法將其所有引數轉發至 Qwen2TokenizerFast 的 batch_decode()。有關更多資訊,請參閱此方法的文件字串。
此方法將其所有引數轉發至 Qwen2TokenizerFast 的 decode()。有關更多資訊,請參閱此方法的文件字串。
Qwen2AudioEncoder
class transformers.Qwen2AudioEncoder
< source >( config: Qwen2AudioEncoderConfig )
引數
- config (Qwen2AudioEncoderConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法以載入模型權重。
Qwen2Audio 的音訊模型,沒有任何頭部或頂層投影。
此模型繼承自 PreTrainedModel。請查閱超類文件,瞭解庫為所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並查閱 PyTorch 文件以瞭解所有與一般用法和行為相關的事宜。
forward
< source >( input_features attention_mask = None head_mask = None output_attentions = None output_hidden_states = None return_dict = None )
引數
- input_features (
torch.LongTensor
,形狀為(batch_size, feature_size, sequence_length)
) — 從原始語音波形中提取的 Mel 特徵的浮點值。原始語音波形可以透過將.flac
或.wav
音訊檔案載入到型別為list[float]
或numpy.ndarray
的陣列中來獲得,例如透過 soundfile 庫(pip install soundfile
)。為了將陣列準備為input_features
,應使用 AutoFeatureExtractor 來提取 Mel 特徵、填充並轉換為torch.FloatTensor
型別張量。參見 call() - attention_mask (
torch.Tensor
), *可選*) -- Qwen2Audio 不支援對
input_features` 進行掩碼,此引數保留用於相容性,但未使用。預設情況下,輸入 log mel 頻譜圖中的靜音會被忽略。 - head_mask (
torch.Tensor
,形狀為(encoder_layers, encoder_attention_heads)
,可選) — 用於使注意力模組的選定頭部無效的掩碼。掩碼值選擇在[0, 1]
之間:- 1 表示頭部未被掩碼,
- 0 表示頭部被掩碼。
- output_attentions (
bool
,可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參閱返回張量中的attentions
。 - output_hidden_states (
bool
,可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參閱返回張量中的hidden_states
。 - return_dict (
bool
,可選) — 是否返回 ModelOutput 而不是普通元組。
Qwen2AudioForConditionalGeneration
class transformers.Qwen2AudioForConditionalGeneration
< source >( config: Qwen2AudioConfig )
引數
- config (Qwen2AudioConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法以載入模型權重。
QWEN2AUDIO 模型,由音訊主幹和語言模型組成。
此模型繼承自 PreTrainedModel。請查閱超類文件,瞭解庫為所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並查閱 PyTorch 文件以瞭解所有與一般用法和行為相關的事宜。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None input_features: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None feature_attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = 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 ) → transformers.models.qwen2_audio.modeling_qwen2_audio.Qwen2AudioCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
,形狀為(batch_size, sequence_length)
,可選) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。可以使用 AutoTokenizer 獲取索引。更多詳細資訊請參閱 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- input_features (
torch.FloatTensor
,形狀為(batch_size, feature_size, feature_sequence_length)
) — 從原始語音波形中提取的浮點值 Mel 特徵。原始語音波形可以透過將.flac
或.wav
音訊檔案載入到型別為list[float]
或numpy.ndarray
的陣列中來獲得,例如透過 soundfile 庫(pip install soundfile
)。為了將陣列準備為input_features
,應使用 AutoFeatureExtractor 來提取 Mel 特徵、填充並轉換為torch.FloatTensor
型別張量。參見 call() - attention_mask (
torch.Tensor
,形狀為(batch_size, sequence_length)
,可選) — 避免對填充 token 索引執行注意力的掩碼。掩碼值選擇在[0, 1]
之間:- 1 表示 token 未被掩碼,
- 0 表示 token 被掩碼。
- feature_attention_mask (
torch.Tensor
,形狀為(batch_size, feature_sequence_length)
) — 避免對填充特徵索引執行注意力的掩碼。掩碼值選擇在[0, 1]
之間:- 1 表示 token 未被掩碼,
- 0 表示 token 被掩碼。
- position_ids (
torch.LongTensor
,形狀為(batch_size, sequence_length)
,可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為[0, config.n_positions - 1]
。 - past_key_values (
~cache_utils.Cache
,可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常包括模型在解碼上一階段返回的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
(那些沒有將它們的過去鍵值狀態提供給此模型的 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 而不是普通元組。
返回
transformers.models.qwen2_audio.modeling_qwen2_audio.Qwen2AudioCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
transformers.models.qwen2_audio.modeling_qwen2_audio.Qwen2AudioCausalLMOutputWithPast
或 torch.FloatTensor
的元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),包含根據配置(Qwen2AudioConfig)和輸入而定的各種元素。
-
loss (
torch.FloatTensor
形狀為(1,)
,可選,當提供labels
時返回) — 語言建模損失(用於下一個 token 預測)。 -
logits (形狀為
(batch_size, sequence_length, config.vocab_size)
的torch.FloatTensor
) — 語言建模頭部的預測分數(SoftMax 之前的每個詞彙標記的分數)。 -
past_key_values (
Cache
,可選,當傳入use_cache=True
或當config.use_cache=True
時返回) — 預先計算的隱藏狀態,可用於加速自迴歸(順序)解碼。有兩組預先計算的隱藏狀態:自注意力塊中的鍵和值狀態。當傳入use_cache=True
或當config.use_cache=True
時,將返回past_key_values
。它是一個 Cache 例項。如果使用
past_key_values
,使用者可以選擇只輸入形狀為(batch_size, 1)
的最後一個input_ids
(那些沒有將它們的過去鍵值狀態提供給此模型的 token),而不是形狀為(batch_size, sequence_length)
的所有input_ids
。 -
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 後的注意力權重,用於計算自注意力頭中的加權平均值。
-
attention_mask (
torch.FloatTensor
,可選) — 注意力掩碼,用於更新注意力掩碼和位置 ID。
Qwen2AudioForConditionalGeneration 的 forward 方法,覆蓋了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但此後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者會默默忽略它們。
示例
>>> from io import BytesIO
>>> from urllib.request import urlopen
>>> import librosa
>>> from transformers import AutoProcessor, Qwen2AudioForConditionalGeneration
>>> model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B")
>>> prompt = "<|audio_bos|><|AUDIO|><|audio_eos|>Generate the caption in English:"
>>> url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"
>>> audio, _ = librosa.load(BytesIO(urlopen(url).read()), sr=self.processor.feature_extractor.sampling_rate)
>>> inputs = processor(text=prompt, audios=audio, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Generate the caption in English: Glass is breaking."