Transformers 文档

音乐生成

音乐生成

概述

MusicGen模型由Jade Copet、Felix Kreuk、Itai Gat、Tal Remez、David Kant、Gabriel Synnaeve、Yossi Adi和Alexandre Défossez在论文简单且可控的音乐生成中提出。

MusicGen 是一个单阶段自回归 Transformer 模型,能够根据文本描述或音频提示生成高质量的音乐样本。文本描述通过一个冻结的文本编码器模型传递,以获得一系列隐藏状态表示。然后,MusicGen 被训练来预测离散的音频标记,或称为音频代码,这些标记是基于这些隐藏状态的。然后使用音频压缩模型(如 EnCodec)解码这些音频标记,以恢复音频波形。

通过高效的令牌交错模式,MusicGen不需要文本/音频提示的自监督语义表示,从而消除了级联多个模型来预测一组代码本的需求(例如分层或上采样)。相反,它能够在一次前向传递中生成所有代码本。

论文的摘要如下:

我们解决了条件音乐生成的任务。我们引入了MusicGen,这是一个单一的语言模型(LM),它在多个压缩的离散音乐表示流(即标记)上运行。与之前的工作不同,MusicGen由一个单阶段的变压器LM和高效的标记交错模式组成,这消除了对级联多个模型的需求,例如分层或上采样。通过这种方法,我们展示了MusicGen如何生成高质量的样本,同时基于文本描述或旋律特征进行条件生成,从而更好地控制生成的输出。我们进行了广泛的实证评估,考虑了自动和人类研究,表明所提出的方法在标准的文本到音乐基准上优于评估的基线。通过消融研究,我们揭示了组成MusicGen的每个组件的重要性。

该模型由sanchit-gandhi贡献。原始代码可以在这里找到。预训练的检查点可以在Hugging Face Hub上找到。

使用提示

  • 这里下载原始检查点后,您可以使用转换脚本src/transformers/models/musicgen/convert_musicgen_transformers.py中使用以下命令进行转换:
python src/transformers/models/musicgen/convert_musicgen_transformers.py \
    --checkpoint small --pytorch_dump_folder /output/path --safe_serialization 

生成

MusicGen 兼容两种生成模式:贪婪模式和采样模式。实际上,采样模式的结果明显优于贪婪模式,因此我们鼓励尽可能使用采样模式。采样模式默认启用,可以通过在调用 MusicgenForConditionalGeneration.generate() 时设置 do_sample=True 来显式指定,或者通过覆盖模型的生成配置(见下文)来指定。

生成受限于正弦位置嵌入,最多只能处理30秒的输入。这意味着,MusicGen无法生成超过30秒的音频(1503个标记),而通过音频提示生成传递的输入音频也会计入这一限制。因此,如果输入了20秒的音频,MusicGen无法生成超过10秒的额外音频。

Transformers 支持 MusicGen 的单声道(1通道)和立体声(2通道)变体。单声道版本生成一组代码本。立体声版本生成两组代码本,每组对应一个通道(左/右),每组代码本通过音频压缩模型独立解码。每个通道的音频流被组合以生成最终的立体声输出。

无条件生成

无条件(或“空”)生成的输入可以通过方法 MusicgenForConditionalGeneration.get_unconditional_inputs()获得:

>>> from transformers import MusicgenForConditionalGeneration

>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
>>> unconditional_inputs = model.get_unconditional_inputs(num_samples=1)

>>> audio_values = model.generate(**unconditional_inputs, do_sample=True, max_new_tokens=256)

音频输出是一个形状为(batch_size, num_channels, sequence_length)的三维Torch张量。要收听生成的音频样本,您可以在ipynb笔记本中播放它们:

from IPython.display import Audio

sampling_rate = model.config.audio_encoder.sampling_rate
Audio(audio_values[0].numpy(), rate=sampling_rate)

或者使用第三方库将它们保存为.wav文件,例如scipy

>>> import scipy

>>> sampling_rate = model.config.audio_encoder.sampling_rate
>>> scipy.io.wavfile.write("musicgen_out.wav", rate=sampling_rate, data=audio_values[0, 0].numpy())

文本条件生成

该模型可以通过使用MusicgenProcessor来预处理输入,从而生成基于文本提示的音频样本:

>>> from transformers import AutoProcessor, MusicgenForConditionalGeneration

>>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

>>> inputs = processor(
...     text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"],
...     padding=True,
...     return_tensors="pt",
... )
>>> audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

guidance_scale 用于无分类器引导(CFG),设置条件对数(从文本提示预测)和无条件对数(从无条件或“空”提示预测)之间的权重。较高的引导比例鼓励模型生成与输入提示更紧密相关的样本,通常以音频质量较差为代价。通过设置 guidance_scale > 1 来启用 CFG。为了获得最佳效果,请使用 guidance_scale=3(默认值)。

音频提示生成

相同的MusicgenProcessor可以用于预处理用于音频延续的音频提示。在下面的示例中,我们使用🤗 Datasets库加载一个音频文件,可以通过以下命令进行pip安装:

pip install --upgrade pip
pip install datasets[audio]
>>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

>>> dataset = load_dataset("sanchit-gandhi/gtzan", split="train", streaming=True)
>>> sample = next(iter(dataset))["audio"]

>>> # take the first half of the audio sample
>>> sample["array"] = sample["array"][: len(sample["array"]) // 2]

>>> inputs = processor(
...     audio=sample["array"],
...     sampling_rate=sample["sampling_rate"],
...     text=["80s blues track with groovy saxophone"],
...     padding=True,
...     return_tensors="pt",
... )
>>> audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

对于批量音频提示生成,生成的audio_values可以通过使用MusicgenProcessor类进行后处理以去除填充:

>>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

>>> dataset = load_dataset("sanchit-gandhi/gtzan", split="train", streaming=True)
>>> sample = next(iter(dataset))["audio"]

>>> # take the first quarter of the audio sample
>>> sample_1 = sample["array"][: len(sample["array"]) // 4]

>>> # take the first half of the audio sample
>>> sample_2 = sample["array"][: len(sample["array"]) // 2]

>>> inputs = processor(
...     audio=[sample_1, sample_2],
...     sampling_rate=sample["sampling_rate"],
...     text=["80s blues track with groovy saxophone", "90s rock song with loud guitars and heavy drums"],
...     padding=True,
...     return_tensors="pt",
... )
>>> audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

>>> # post-process to remove padding from the batched audio
>>> audio_values = processor.batch_decode(audio_values, padding_mask=inputs.padding_mask)

生成配置

控制生成过程的默认参数,例如采样、指导比例和生成的标记数量,可以在模型的生成配置中找到,并根据需要进行更新:

>>> from transformers import MusicgenForConditionalGeneration

>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

>>> # inspect the default generation config
>>> model.generation_config

>>> # increase the guidance scale to 4.0
>>> model.generation_config.guidance_scale = 4.0

>>> # decrease the max length to 256 tokens
>>> model.generation_config.max_length = 256

请注意,传递给generate方法的任何参数将覆盖生成配置中的参数,因此在调用generate时设置do_sample=False将覆盖生成配置中的model.generation_config.do_sample设置。

模型结构

MusicGen模型可以分解为三个不同的阶段:

  1. 文本编码器:将文本输入映射到一系列隐藏状态表示。预训练的MusicGen模型使用来自T5或Flan-T5的冻结文本编码器。
  2. MusicGen解码器:一种语言模型(LM),它根据编码器隐藏状态表示自回归生成音频令牌(或代码)
  3. 音频编码器/解码器:用于将音频提示编码为提示令牌,并从解码器预测的音频令牌中恢复音频波形

因此,MusicGen模型可以作为独立的解码器模型使用,对应于类MusicgenForCausalLM,或者作为包含文本编码器和音频编码器/解码器的复合模型使用,对应于类MusicgenForConditionalGeneration。如果只需要从预训练检查点加载解码器,可以通过首先指定正确的配置来加载,或者通过复合模型的.decoder属性访问:

>>> from transformers import AutoConfig, MusicgenForCausalLM, MusicgenForConditionalGeneration

>>> # Option 1: get decoder config and pass to `.from_pretrained`
>>> decoder_config = AutoConfig.from_pretrained("facebook/musicgen-small").decoder
>>> decoder = MusicgenForCausalLM.from_pretrained("facebook/musicgen-small", **decoder_config)

>>> # Option 2: load the entire composite model, but only return the decoder
>>> decoder = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small").decoder

由于文本编码器和音频编码器/解码器模型在训练期间是冻结的,MusicGen解码器 MusicgenForCausalLM 可以在编码器隐藏状态和音频代码的数据集上独立训练。在推理时,训练好的解码器可以与冻结的文本编码器和音频编码器/解码器结合,以恢复复合的 MusicgenForConditionalGeneration 模型。

提示:

  • MusicGen 是在 Encodec 的 32kHz 检查点上训练的。你应该确保使用兼容版本的 Encodec 模型。
  • 采样模式通常比贪婪模式提供更好的结果 - 你可以在调用MusicgenForConditionalGeneration.generate()时通过变量do_sample来切换采样模式

MusicgenDecoderConfig

transformers.MusicgenDecoderConfig

< >

( vocab_size = 2048 max_position_embeddings = 2048 num_hidden_layers = 24 ffn_dim = 4096 num_attention_heads = 16 layerdrop = 0.0 use_cache = True activation_function = 'gelu' hidden_size = 1024 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 initializer_factor = 0.02 scale_embedding = False num_codebooks = 4 audio_channels = 1 pad_token_id = 2048 bos_token_id = 2048 eos_token_id = None tie_word_embeddings = False **kwargs )

参数

  • vocab_size (int, 可选, 默认为 2048) — MusicgenDecoder 模型的词汇表大小。定义了调用 MusicgenDecoder 时传递的 inputs_ids 可以表示的不同标记的数量。
  • hidden_size (int, optional, 默认为 1024) — 层的维度和池化层的维度。
  • num_hidden_layers (int, optional, defaults to 24) — 解码器层数.
  • num_attention_heads (int, optional, defaults to 16) — Transformer 块中每个注意力层的注意力头数。
  • ffn_dim (int, optional, 默认为 4096) — Transformer 块中“中间”(通常称为前馈)层的维度。
  • activation_function (strfunction, 可选, 默认为 "gelu") — 解码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""silu""gelu_new"
  • dropout (float, optional, defaults to 0.1) — 嵌入层、文本编码器和池化器中所有全连接层的 dropout 概率。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的丢弃比例。
  • activation_dropout (float, optional, defaults to 0.0) — 全连接层内部激活的dropout比率。
  • max_position_embeddings (int, optional, 默认为 2048) — 此模型可能使用的最大序列长度。通常,将此设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • initializer_factor (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layerdrop (float, optional, 默认为 0.0) — 解码器的LayerDrop概率。更多详情请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)
  • scale_embedding (bool, optional, defaults to False) — 通过除以 sqrt(hidden_size) 来缩放嵌入。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)
  • num_codebooks (int, 可选, 默认为 4) — 转发到模型的并行码本数量。
  • tie_word_embeddings(bool, 可选, 默认为 False) — 输入和输出的词嵌入是否应该绑定。
  • audio_channels (int, 可选, 默认为 1 — 音频数据中的声道数。1 表示单声道,2 表示立体声。立体声模型为左/右输出声道生成单独的音频流。单声道模型生成单个音频流输出。

这是用于存储MusicgenDecoder配置的配置类。它用于根据指定的参数实例化一个MusicGen解码器,定义模型架构。使用默认值实例化配置将产生类似于MusicGen facebook/musicgen-small架构的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

MusicgenConfig

transformers.MusicgenConfig

< >

( **kwargs )

参数

  • kwargs (可选) — 关键字参数字典。特别是:
    • text_encoder (PretrainedConfig, 可选) — 定义文本编码器配置的配置对象实例。
    • audio_encoder (PretrainedConfig, 可选) — 定义音频编码器配置的配置对象实例。
    • decoder (PretrainedConfig, 可选) — 定义解码器配置的配置对象实例。

这是用于存储MusicgenModel配置的配置类。它用于根据指定的参数实例化一个MusicGen模型,定义文本编码器、音频编码器和MusicGen解码器的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import (
...     MusicgenConfig,
...     MusicgenDecoderConfig,
...     T5Config,
...     EncodecConfig,
...     MusicgenForConditionalGeneration,
... )

>>> # Initializing text encoder, audio encoder, and decoder model configurations
>>> text_encoder_config = T5Config()
>>> audio_encoder_config = EncodecConfig()
>>> decoder_config = MusicgenDecoderConfig()

>>> configuration = MusicgenConfig.from_sub_models_config(
...     text_encoder_config, audio_encoder_config, decoder_config
... )

>>> # Initializing a MusicgenForConditionalGeneration (with random weights) from the facebook/musicgen-small style configuration
>>> model = MusicgenForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
>>> config_text_encoder = model.config.text_encoder
>>> config_audio_encoder = model.config.audio_encoder
>>> config_decoder = model.config.decoder

>>> # Saving the model, including its configuration
>>> model.save_pretrained("musicgen-model")

>>> # loading model and config from pretrained folder
>>> musicgen_config = MusicgenConfig.from_pretrained("musicgen-model")
>>> model = MusicgenForConditionalGeneration.from_pretrained("musicgen-model", config=musicgen_config)

from_sub_models_config

< >

( text_encoder_config: PretrainedConfig audio_encoder_config: PretrainedConfig decoder_config: MusicgenDecoderConfig **kwargs ) MusicgenConfig

返回

MusicgenConfig

配置对象的一个实例

从文本编码器、音频编码器和解码器配置实例化一个MusicgenConfig(或派生类)。

MusicgenProcessor

transformers.MusicgenProcessor

< >

( feature_extractor tokenizer )

参数

  • feature_extractor (EncodecFeatureExtractor) — 一个 EncodecFeatureExtractor 的实例。特征提取器是一个必需的输入。
  • tokenizer (T5Tokenizer) — 一个 T5Tokenizer 的实例。tokenizer 是一个必需的输入。

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

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

batch_decode

< >

( *args **kwargs )

此方法用于解码来自MusicGen模型的音频输出批次,或来自分词器的标记ID批次。在解码标记ID的情况下,此方法将其所有参数转发给T5Tokenizer的batch_decode()。有关更多信息,请参阅此方法的文档字符串。

解码

< >

( *args **kwargs )

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

MusicgenModel

transformers.MusicgenModel

< >

( config: MusicgenDecoderConfig )

参数

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

裸的Musicgen解码器模型输出原始隐藏状态,没有任何特定的头部。

Musicgen模型由Jade Copet、Felix Kreuk、Itai Gat、Tal Remez、David Kant、Gabriel Synnaeve、Yossi Adi和Alexandre Défossez在简单且可控的音乐生成中提出。它是一个在条件音乐生成任务上训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

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

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = 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 )

参数

  • input_ids (torch.LongTensor of shape (batch_size * num_codebooks, sequence_length)) — Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

    可以通过使用音频编码器模型对音频提示进行编码来获取索引,以预测音频代码,例如使用EncodecModel。详情请参见EncodecModel.encode()

    什么是输入ID?

    input_ids 在前向传递过程中会自动从形状 (batch_size * num_codebooks, target_sequence_length) 转换为 (batch_size, num_codebooks, target_sequence_length)。如果你从音频编码模型(如 EncodecModel)获取音频代码,请确保帧数等于1,并且在将它们作为 input_ids 传递之前,将音频代码从 (frames, batch_size, num_codebooks, target_sequence_length) 重塑为 (batch_size * num_codebooks, target_sequence_length)

  • 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.

    什么是注意力掩码?

  • encoder_hidden_states (torch.FloatTensor of shape (batch_size, encoder_sequence_length, hidden_size), optional) — 编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。
  • encoder_attention_mask (torch.LongTensor of shape (batch_size, encoder_sequence_length), optional) — Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择交叉注意力模块的头部,以避免在隐藏的头部上执行交叉注意力。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • 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 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

MusicgenModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

MusicgenForCausalLM

transformers.MusicgenForCausalLM

< >

( config: MusicgenDecoderConfig )

参数

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

带有语言建模头的MusicGen解码器模型。

Musicgen模型由Jade Copet、Felix Kreuk、Itai Gat、Tal Remez、David Kant、Gabriel Synnaeve、Yossi Adi和Alexandre Défossez在简单且可控的音乐生成中提出。它是一个在条件音乐生成任务上训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

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

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[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.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size * num_codebooks, sequence_length)) — Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

    可以通过使用音频编码器模型对音频提示进行编码来获取索引,以预测音频代码,例如使用EncodecModel。详情请参见EncodecModel.encode()

    什么是输入ID?

    input_ids 在前向传递过程中会自动从形状 (batch_size * num_codebooks, target_sequence_length) 转换为 (batch_size, num_codebooks, target_sequence_length)。如果你从音频编码模型(如 EncodecModel)获取音频代码,请确保帧数等于1,并且在将它们作为 input_ids 传递之前,将音频代码从 (frames, batch_size, num_codebooks, target_sequence_length) 重塑为 (batch_size * num_codebooks, target_sequence_length)

  • 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.

    什么是注意力掩码?

  • encoder_hidden_states (torch.FloatTensor of shape (batch_size, encoder_sequence_length, hidden_size), optional) — 编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。
  • encoder_attention_mask (torch.LongTensor of shape (batch_size, encoder_sequence_length), optional) — Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择交叉注意力模块的头部,以避免在隐藏的头部上执行交叉注意力。掩码值在 [0, 1] 中选择:
    • 1 表示头部未被掩码,
    • 0 表示头部被掩码.
  • 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索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size, sequence_length, num_codebooks), optional) — 用于语言建模的标签。请注意,标签在模型内部被移位,即你可以设置 labels = input_ids 索引在 [-100, 0, ..., config.vocab_size] 中选择。所有设置为 -100 的标签 将被忽略(屏蔽),损失仅针对 [0, ..., config.vocab_size] 中的标签计算

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,取决于配置(MusicgenConfig)和输入。

  • 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) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

  • decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

MusicgenForCausalLM 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

MusicgenForConditionalGeneration

transformers.MusicgenForConditionalGeneration

< >

( config: typing.Optional[transformers.models.musicgen.configuration_musicgen.MusicgenConfig] = None text_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None audio_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None decoder: typing.Optional[transformers.models.musicgen.modeling_musicgen.MusicgenForCausalLM] = None )

参数

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

复合MusicGen模型,包含文本编码器、音频编码器和Musicgen解码器,用于带有文本和/或音频提示的音乐生成任务。

Musicgen模型由Jade Copet、Felix Kreuk、Itai Gat、Tal Remez、David Kant、Gabriel Synnaeve、Yossi Adi和Alexandre Défossez在简单且可控的音乐生成中提出。它是一个在条件音乐生成任务上训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

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

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.BoolTensor] = None input_values: typing.Optional[torch.FloatTensor] = None padding_mask: typing.Optional[torch.BoolTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None encoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = None past_key_values: typing.Tuple[typing.Tuple[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_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 **kwargs ) transformers.modeling_outputs.Seq2SeqLMOutputtuple(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?

  • 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.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size * num_codebooks, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

    可以通过使用音频编码器模型对音频提示进行编码来获取索引,以预测音频代码,例如使用EncodecModel。详情请参见EncodecModel.encode()

    什么是解码器输入ID?

    decoder_input_ids 在前向传递过程中会自动从形状 (batch_size * num_codebooks, target_sequence_length) 转换为 (batch_size, num_codebooks, target_sequence_length)。如果你从音频编码模型(如 EncodecModel)中获取音频代码,请确保帧数等于1,并且在将它们作为 decoder_input_ids 传递之前,将音频代码从 (frames, batch_size, num_codebooks, target_sequence_length) 重塑为 (batch_size * num_codebooks, target_sequence_length)

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • 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索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • labels (torch.LongTensor of shape (batch_size, sequence_length, num_codebooks), optional) — 用于语言建模的标签。请注意,标签在模型内部被移位,即你可以设置 labels = input_ids 索引在 [-100, 0, ..., config.vocab_size] 中选择。所有设置为 -100 的标签 将被忽略(掩码),损失仅针对 [0, ..., config.vocab_size] 中的标签计算
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(MusicgenConfig)和输入。

  • 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) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

  • decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size)可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

MusicgenForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
>>> import torch

>>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
>>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

>>> inputs = processor(
...     text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"],
...     padding=True,
...     return_tensors="pt",
... )

>>> pad_token_id = model.generation_config.pad_token_id
>>> decoder_input_ids = (
...     torch.ones((inputs.input_ids.shape[0] * model.decoder.num_codebooks, 1), dtype=torch.long)
...     * pad_token_id
... )

>>> logits = model(**inputs, decoder_input_ids=decoder_input_ids).logits
>>> logits.shape  # (bsz * num_codebooks, tgt_len, vocab_size)
torch.Size([8, 1, 2048])
< > Update on GitHub