Transformers 文档

Qwen2Audio

Qwen2Audio

概述

Qwen2-Audio 是 Qwen 团队推出的新系列大型音频语言模型。Qwen2-Audio 能够接受各种音频信号输入,并根据语音指令进行音频分析或直接文本响应。我们引入了两种不同的音频交互模式:

  • 语音聊天:用户可以在无需文本输入的情况下与Qwen2-Audio自由进行语音互动
  • 音频分析:用户可以在交互过程中提供音频和文本指令进行分析

它由褚云飞、徐进、杨倩、魏浩杰、魏西平、郭志芳、冷一冲、吕元君、何金正、林俊阳、周畅、周景仁在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-7BQwen2-Audio-7B-Instruct 可以在 Huggingface Hub 上找到

在下面,我们演示了如何使用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

transformers.Qwen2AudioConfig

< >

( audio_config = None text_config = None audio_token_index = 151646 **kwargs )

参数

  • audio_config (Union[AutoConfig, dict], 可选, 默认为 CLIPVisionConfig) — 音频主干的配置对象或字典.
  • text_config (Union[AutoConfig, dict], 可选, 默认为 LlamaConfig) — 文本主干的配置对象或字典。
  • audio_token_index (int, 可选, 默认为 151646) — 用于编码图像提示的图像令牌索引。

这是用于存储Qwen2AudioForConditionalGeneration配置的配置类。它用于根据指定的参数实例化一个Qwen2-Audio模型,定义模型架构。使用默认值实例化配置将产生与Qwen2-Audio类似的配置。

例如 Qwen/Qwen2-Audio-7B

配置对象继承自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

Qwen2AudioConfig

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 init_std = 0.02 max_source_positions = 1500 **kwargs )

参数

  • num_mel_bins (int, optional, 默认为 128) — 每个输入特征使用的梅尔特征数量。应与 Qwen2AudioProcessor 类中使用的值对应。
  • encoder_layers (int, optional, defaults to 32) — 编码器层数.
  • encoder_attention_heads (int, optional, 默认为 20) — Transformer 编码器中每个注意力层的注意力头数量。
  • encoder_ffn_dim (int, optional, 默认为 5120) — 编码器中“中间”(通常称为前馈)层的维度。
  • encoder_layerdrop (float, optional, 默认为 0.0) — 编码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。
  • d_model (int, optional, defaults to 1280) — 层的维度.
  • dropout (float, optional, defaults to 0.0) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的丢弃比率。
  • activation_function (str, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""silu""gelu_new"
  • activation_dropout (float, optional, defaults to 0.0) — 全连接层内激活函数的丢弃比例。
  • scale_embedding (bool, optional, defaults to False) — 通过除以 sqrt(d_model) 来缩放嵌入向量。
  • init_std (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • max_source_positions (int, optional, 默认为 1500) — 该模型可能使用的对数梅尔滤波器组特征的最大序列长度。

这是用于存储Qwen2AudioEncoder配置的配置类。它用于根据指定的参数实例化一个Qwen2-Audio音频编码器,定义模型架构。使用默认值实例化配置将产生与Qwen2-Audio架构的音频编码器类似的配置。

例如 Qwen/Qwen2-Audio-7B

配置对象继承自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

transformers.Qwen2AudioProcessor

< >

( feature_extractor = 无 tokenizer = 无 chat_template = 无 )

参数

  • feature_extractor (WhisperFeatureExtractor, optional) — 特征提取器是一个必需的输入。
  • tokenizer (Qwen2TokenizerFast, optional) — 分词器是一个必需的输入。
  • chat_template (Optional[str], optional) — 用于格式化对话的Jinja模板。如果未提供,则使用默认的聊天模板。

构建一个Qwen2Audio处理器,它将Qwen2Audio特征提取器和Qwen2Audio分词器封装到一个处理器中。

Qwen2AudioProcessor 提供了 WhisperFeatureExtractorQwen2TokenizerFast 的所有功能。更多信息请参见 __call__()decode()

batch_decode

< >

( *args **kwargs )

此方法将其所有参数转发给Qwen2TokenizerFast的batch_decode()。请参考该方法的文档字符串以获取更多信息。

解码

< >

( *args **kwargs )

此方法将其所有参数转发给Qwen2TokenizerFast的decode()。请参考该方法的文档字符串以获取更多信息。

Qwen2AudioForConditionalGeneration

transformers.Qwen2AudioForConditionalGeneration

< >

( config: Qwen2AudioConfig )

参数

  • config (Qwen2AudioConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

QWEN2AUDIO模型由一个音频骨干和一个语言模型组成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: LongTensor = None input_features: 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[typing.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 ) transformers.models.qwen2_audio.modeling_qwen2_audio.Qwen2AudioCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • input_features (torch.FloatTensor of shape (batch_size, feature_size, feature_sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is masked.
  • feature_attention_mask (torch.Tensor of shape (batch_size, feature_sequence_length)) — 用于避免对填充特征索引执行注意力的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示 未掩码 的标记,
    • 0 表示 掩码 的标记。
  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.n_positions - 1] 内。What are position IDs?
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

    包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见past_key_values输入)以加速顺序解码。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • 参数 — labels (torch.LongTensor of shape (batch_size, sequence_length), 可选): 用于计算掩码语言建模损失的标签。索引应在 [0, ..., config.vocab_size] 或 -100 之间(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略 (掩码),损失仅计算标签在 [0, ..., config.vocab_size] 之间的标记。

返回

transformers.models.qwen2_audio.modeling_qwen2_audio.Qwen2AudioCausalLMOutputWithPasttuple(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 时返回) — 语言建模损失(用于下一个标记预测)。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(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 时返回) — 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 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用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."
< > Update on GitHub