Diffusers 文档

AudioLDM 2

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

AudioLDM 2

AudioLDM 2 是 Haohe Liu 等人在 AudioLDM 2: Learning Holistic Audio Generation with Self-supervised Pretraining 中提出的。AudioLDM 2 以文本提示作为输入,并预测相应的音频。它可以生成文本条件的声音效果、人类语音和音乐。

Stable Diffusion 的启发,AudioLDM 2 是一种文本到音频的潜在扩散模型 (LDM),它从文本嵌入中学习连续音频表示。两个文本编码器模型用于从提示输入计算文本嵌入:CLAP 的文本分支和 Flan-T5 的编码器。这些文本嵌入随后通过 AudioLDM2ProjectionModel 投影到共享嵌入空间。GPT2 语言模型 (LM) 用于自回归地预测八个新的嵌入向量,以 projected CLAP 和 Flan-T5 嵌入为条件。生成的嵌入向量和 Flan-T5 文本嵌入用作 LDM 中的交叉注意力条件。UNet 的 AudioLDM 2 是独一无二的,因为它接受两个交叉注意力嵌入,而不是像大多数其他 LDM 中那样的单个交叉注意力条件。

该论文的摘要如下

虽然音频生成在不同类型的音频(如语音、音乐和音效)之间存在共性,但为每种类型设计模型都需要仔细考虑特定的目标和偏差,这些目标和偏差可能与其他类型显著不同。为了使我们更接近音频生成的统一视角,本文提出了一个框架,该框架对语音、音乐和音效生成采用相同的学习方法。我们的框架引入了一种通用的音频表示形式,称为“音频语言”(LOA)。任何音频都可以基于 AudioMAE(一种自监督预训练表示学习模型)转换为 LOA。在生成过程中,我们使用 GPT-2 模型将任何模态转换为 LOA,并使用以 LOA 为条件的潜在扩散模型执行自监督音频生成学习。所提出的框架自然而然地带来了诸如上下文学习能力以及可重用的自监督预训练 AudioMAE 和潜在扩散模型等优势。在文本到音频、文本到音乐和文本到语音的主要基准测试上的实验表明,相对于以前的方法,我们的方法达到了最先进水平或具有竞争力的性能。我们的代码、预训练模型和演示可在 this https URL 获取。

此流程由 sanchit-gandhiNguyễn Công Tú Anh 贡献。原始代码库可在 haoheliu/audioldm2 找到。

提示

选择检查点

AudioLDM2 提供三种变体。其中两个检查点适用于通用的文本到音频生成任务。第三个检查点专门针对文本到音乐生成进行训练。

所有检查点在文本编码器和 VAE 上共享相同的模型大小。它们在 UNet 的大小和深度上有所不同。有关这三个检查点的详细信息,请参见下表

检查点 任务 UNet 模型大小 总模型大小 训练数据 / 小时
audioldm2 文本到音频 350M 1.1B 1150k
audioldm2-large 文本到音频 750M 1.5B 1150k
audioldm2-music 文本到音乐 350M 1.1B 665k
audioldm2-gigaspeech 文本到语音 350M 1.1B 10k
audioldm2-ljspeech 文本到语音 350M 1.1B

构建提示词

  • 描述性提示词输入效果最佳:使用形容词来描述声音(例如“高质量”或“清晰”),并使提示词上下文具体化(例如“森林中的水流”而不是“水流”)。
  • 最好使用“猫”或“狗”等通用术语,而不是模型可能不熟悉的特定名称或抽象对象。
  • 使用负面提示词可以显著提高生成的波形的质量,通过引导生成远离与低质量音频相关的术语。尝试使用“低质量”的负面提示词。

控制推理

  • 预测音频样本的质量可以通过 num_inference_steps 参数控制;更高的步数会带来更高质量的音频,但会以较慢的推理速度为代价。
  • 预测音频样本的长度可以通过更改 audio_length_in_s 参数来控制。

评估生成的波形:

  • 生成的波形的质量可能因种子而异。尝试使用不同的种子进行生成,直到找到令人满意的生成结果。
  • 可以一次生成多个波形:将 num_waveforms_per_prompt 设置为大于 1 的值。将对生成的波形和提示文本之间执行自动评分,并相应地对音频进行最佳到最差的排序。

以下示例演示了如何使用上述技巧构建良好的音乐和语音生成:示例

请务必查看调度器 指南,了解如何探索调度器速度和质量之间的权衡,并查看 跨管道重用组件 部分,了解如何有效地将相同的组件加载到多个管道中。

AudioLDM2Pipeline

class diffusers.AudioLDM2Pipeline

< >

( vae: AutoencoderKL text_encoder: ClapModel text_encoder_2: typing.Union[transformers.models.t5.modeling_t5.T5EncoderModel, transformers.models.vits.modeling_vits.VitsModel] projection_model: AudioLDM2ProjectionModel language_model: GPT2Model tokenizer: typing.Union[transformers.models.roberta.tokenization_roberta.RobertaTokenizer, transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast] tokenizer_2: typing.Union[transformers.models.t5.tokenization_t5.T5Tokenizer, transformers.models.t5.tokenization_t5_fast.T5TokenizerFast, transformers.models.vits.tokenization_vits.VitsTokenizer] feature_extractor: ClapFeatureExtractor unet: AudioLDM2UNet2DConditionModel scheduler: KarrasDiffusionSchedulers vocoder: SpeechT5HifiGan )

参数

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
  • text_encoder (ClapModel) — 第一个冻结的文本编码器。AudioLDM2 使用联合音频-文本嵌入模型 CLAP,特别是 laion/clap-htsat-unfused 变体。文本分支用于将文本提示词编码为提示词嵌入。完整的音频-文本模型用于通过计算相似度得分来对生成的波形与文本提示词进行排名。
  • text_encoder_2 ([~transformers.T5EncoderModel, ~transformers.VitsModel]) — 第二个冻结的文本编码器。AudioLDM2 使用 T5 的编码器,特别是 google/flan-t5-large 变体。第二个冻结的文本编码器用于 TTS。AudioLDM2 使用 Vits 的编码器。
  • projection_model (AudioLDM2ProjectionModel) — 一个训练好的模型,用于线性投影来自第一个和第二个文本编码器模型的隐藏状态,并插入学习到的 SOS 和 EOS 令牌嵌入。来自两个文本编码器的投影隐藏状态被连接起来,作为语言模型的输入。Vits 隐藏状态的学习位置嵌入
  • language_model (GPT2Model) — 一种自回归语言模型,用于生成以来自两个文本编码器的投影输出为条件的隐藏状态序列。
  • tokenizer (RobertaTokenizer) — 用于为第一个冻结的文本编码器标记化文本的分词器。
  • tokenizer_2 ([~transformers.T5Tokenizer, ~transformers.VitsTokenizer]) — 用于为第二个冻结的文本编码器标记化文本的分词器。
  • feature_extractor (ClapFeatureExtractor) — 特征提取器,用于预处理生成的音频波形为对数梅尔频谱图,以进行自动评分。
  • unet (UNet2DConditionModel) — 一个 UNet2DConditionModel,用于对编码的音频潜在表示进行去噪。
  • scheduler (SchedulerMixin) — 一个调度器,与 unet 结合使用,以对编码的音频潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • vocoder (SpeechT5HifiGan) — SpeechT5HifiGan 类的声码器,用于将梅尔频谱图潜在表示转换为最终音频波形。

使用 AudioLDM2 进行文本到音频生成的管道。

此模型继承自 DiffusionPipeline。查看超类文档,了解为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None transcription: typing.Union[str, typing.List[str]] = None audio_length_in_s: typing.Optional[float] = None num_inference_steps: int = 200 guidance_scale: float = 3.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_waveforms_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None generated_prompt_embeds: typing.Optional[torch.Tensor] = None negative_generated_prompt_embeds: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.LongTensor] = None negative_attention_mask: typing.Optional[torch.LongTensor] = None max_new_tokens: typing.Optional[int] = None return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: typing.Optional[int] = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None output_type: typing.Optional[str] = 'np' ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导音频生成的提示词。如果未定义,则需要传递 prompt_embeds
  • transcription (strList[str], 可选) —\ 用于文本到语音的文本记录。
  • audio_length_in_s (int, 可选, 默认为 10.24) — 生成音频样本的长度,单位为秒。
  • num_inference_steps (int, 可选, 默认为 200) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的音频,但会牺牲更慢的推理速度。
  • guidance_scale (float, 可选, 默认为 3.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的音频,但会以降低音质为代价。 当 guidance_scale > 1 时,guidance scale 被启用。
  • negative_prompt (strList[str], 可选) — 用于指导音频生成中不应包含的内容的 prompt 或 prompts。 如果未定义,则需要传递 negative_prompt_embeds。 当不使用 guidance 时(guidance_scale < 1),此参数将被忽略。
  • num_waveforms_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的波形数量。 如果 num_waveforms_per_prompt > 1,则在生成的输出和文本 prompt 之间执行自动评分。 此评分根据生成的波形与联合文本-音频嵌入空间中文本输入的余弦相似度对波形进行排名。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。 仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的、从高斯分布中采样的噪声 latents,用作频谱图生成的输入。 可用于使用不同的 prompts 调整相同的生成。 如果未提供,则会通过使用提供的随机 generator 进行采样来生成 latents 张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可用于轻松调整文本输入(prompt 加权)。 如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。 可用于轻松调整文本输入(prompt 加权)。 如果未提供,则 negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • generated_prompt_embeds (torch.Tensor, 可选) — 来自 GPT2 语言模型的预生成文本嵌入。 可用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • negative_generated_prompt_embeds (torch.Tensor, 可选) — 来自 GPT2 语言模型的预生成负文本嵌入。 可用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则 negative_prompt_embeds 将从 negative_prompt 输入参数计算得出。
  • attention_mask (torch.LongTensor, 可选) — 预先计算的 attention mask,将应用于 prompt_embeds。 如果未提供,则 attention mask 将从 prompt 输入参数计算得出。
  • negative_attention_mask (torch.LongTensor, 可选) — 预先计算的 attention mask,将应用于 negative_prompt_embeds。 如果未提供,则 attention mask 将从 negative_prompt 输入参数计算得出。
  • max_new_tokens (int, 可选, 默认为 None) — 使用 GPT2 语言模型生成的新 token 数量。 如果未提供,则 token 数量将从模型的配置中获取。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元组。
  • callback (Callable, 可选) — 在推理期间每 callback_steps 步调用一次的函数。 该函数使用以下参数调用: callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。 如果未指定,则在每个步骤都调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • output_type (str, 可选, 默认为 "np") — 生成音频的输出格式。 在 "np" (返回 NumPy np.ndarray)或 "pt" (返回 PyTorch torch.Tensor 对象)之间选择。 设置为 "latent" 以返回潜在扩散模型 (LDM) 输出。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回 tuple,其中第一个元素是包含生成的音频的列表。

调用管道进行生成的功能。

示例

>>> import scipy
>>> import torch
>>> from diffusers import AudioLDM2Pipeline

>>> repo_id = "cvssp/audioldm2"
>>> pipe = AudioLDM2Pipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")

>>> # define the prompts
>>> prompt = "The sound of a hammer hitting a wooden surface."
>>> negative_prompt = "Low quality."

>>> # set the seed for generator
>>> generator = torch.Generator("cuda").manual_seed(0)

>>> # run the generation
>>> audio = pipe(
...     prompt,
...     negative_prompt=negative_prompt,
...     num_inference_steps=200,
...     audio_length_in_s=10.0,
...     num_waveforms_per_prompt=3,
...     generator=generator,
... ).audios

>>> # save the best audio sample (index 0) as a .wav file
>>> scipy.io.wavfile.write("techno.wav", rate=16000, data=audio[0])
#Using AudioLDM2 for Text To Speech
>>> import scipy
>>> import torch
>>> from diffusers import AudioLDM2Pipeline

>>> repo_id = "anhnct/audioldm2_gigaspeech"
>>> pipe = AudioLDM2Pipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")

>>> # define the prompts
>>> prompt = "A female reporter is speaking"
>>> transcript = "wish you have a good day"

>>> # set the seed for generator
>>> generator = torch.Generator("cuda").manual_seed(0)

>>> # run the generation
>>> audio = pipe(
...     prompt,
...     transcription=transcript,
...     num_inference_steps=200,
...     audio_length_in_s=10.0,
...     num_waveforms_per_prompt=2,
...     generator=generator,
...     max_new_tokens=512,          #Must set max_new_tokens equa to 512 for TTS
... ).audios

>>> # save the best audio sample (index 0) as a .wav file
>>> scipy.io.wavfile.write("tts.wav", rate=16000, data=audio[0])

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。 如果先前启用了 enable_vae_slicing,则此方法将返回到一步计算解码。

enable_model_cpu_offload

< >

( gpu_id = 0 )

使用 accelerate 将所有模型卸载到 CPU,从而减少内存使用量,且对性能的影响较小。 与 enable_sequential_cpu_offload 相比,此方法在调用模型的 forward 方法时,一次将一个完整的模型移动到 GPU,并且该模型将保留在 GPU 中,直到下一个模型运行。 内存节省低于 enable_sequential_cpu_offload,但由于 unet 的迭代执行,性能要好得多。

enable_vae_slicing

< >

( )

启用切片 VAE 解码。 启用此选项后,VAE 将输入张量拆分为切片,以分步计算解码。 这有助于节省一些内存并允许更大的批量大小。

encode_prompt

< >

( prompt device num_waveforms_per_prompt do_classifier_free_guidance transcription = None negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None generated_prompt_embeds: typing.Optional[torch.Tensor] = None negative_generated_prompt_embeds: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.LongTensor] = None negative_attention_mask: typing.Optional[torch.LongTensor] = None max_new_tokens: typing.Optional[int] = None ) prompt_embeds (torch.Tensor)

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • transcription (strList[str]) — 文本转语音的转录
  • device (torch.device) — torch 设备
  • num_waveforms_per_prompt (int) — 每个提示词应生成的波形数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不用于引导音频生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • prompt_embeds (torch.Tensor, 可选) — 来自 Flan T5 模型的预计算文本嵌入。 可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数计算文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 来自 Flan T5 模型的预计算负文本嵌入。 可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 negative_prompt 输入参数计算 negative_prompt_embeds。
  • generated_prompt_embeds (torch.Tensor, 可选) — 来自 GPT2 语言模型的预生成文本嵌入。 可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_generated_prompt_embeds (torch.Tensor, 可选) — 来自 GPT2 语言模型的预生成负文本嵌入。 可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 negative_prompt 输入参数计算 negative_prompt_embeds。
  • attention_mask (torch.LongTensor, 可选) — 要应用于 prompt_embeds 的预计算注意力掩码。如果未提供,将从 prompt 输入参数计算注意力掩码。
  • negative_attention_mask (torch.LongTensor, 可选) — 要应用于 negative_prompt_embeds 的预计算注意力掩码。如果未提供,将从 negative_prompt 输入参数计算注意力掩码。
  • max_new_tokens (int, 可选, 默认为 None) — 使用 GPT2 语言模型生成的新 token 数量。

返回

prompt_embeds (torch.Tensor)

来自 Flan T5 模型的文本嵌入。 attention_mask (torch.LongTensor): 要应用于 prompt_embeds 的注意力掩码。 generated_prompt_embeds (torch.Tensor): 从 GPT2 语言模型生成的文本嵌入。

将提示词编码为文本编码器隐藏状态。

示例

>>> import scipy
>>> import torch
>>> from diffusers import AudioLDM2Pipeline

>>> repo_id = "cvssp/audioldm2"
>>> pipe = AudioLDM2Pipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")

>>> # Get text embedding vectors
>>> prompt_embeds, attention_mask, generated_prompt_embeds = pipe.encode_prompt(
...     prompt="Techno music with a strong, upbeat tempo and high melodic riffs",
...     device="cuda",
...     do_classifier_free_guidance=True,
... )

>>> # Pass text embeddings to pipeline for text-conditional audio generation
>>> audio = pipe(
...     prompt_embeds=prompt_embeds,
...     attention_mask=attention_mask,
...     generated_prompt_embeds=generated_prompt_embeds,
...     num_inference_steps=200,
...     audio_length_in_s=10.0,
... ).audios[0]

>>> # save generated audio sample
>>> scipy.io.wavfile.write("techno.wav", rate=16000, data=audio)

generate_language_model

< >

( inputs_embeds: Tensor = None max_new_tokens: int = 8 **model_kwargs ) inputs_embeds (torch.Tensorof shape(batch_size, sequence_length, hidden_size)`)

参数

  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.Tensor) — 用作生成的提示的序列。
  • max_new_tokens (int) — 要生成的新 token 数量。
  • model_kwargs (Dict[str, Any], 可选) — 将转发到模型的 forward 函数的其他模型特定 kwargs 的临时参数化。

返回

inputs_embeds (torch.Tensorof shape(batch_size, sequence_length, hidden_size)`)

生成的隐藏状态序列。

从语言模型生成隐藏状态序列,以嵌入输入为条件。

AudioLDM2ProjectionModel

class diffusers.AudioLDM2ProjectionModel

< >

( text_encoder_dim text_encoder_1_dim langauge_model_dim use_learned_position_embedding = None max_seq_length = None )

参数

  • text_encoder_dim (int) — 来自第一个文本编码器 (CLAP) 的文本嵌入的维度。
  • text_encoder_1_dim (int) — 来自第二个文本编码器(T5 或 VITS)的文本嵌入的维度。
  • langauge_model_dim (int) — 来自语言模型 (GPT2) 的文本嵌入的维度。

一个简单的线性投影模型,用于将两个文本嵌入映射到一个共享的潜在空间。它还在每个文本嵌入序列的开始和结束处分别插入学习到的嵌入向量。每个附加 _1 的变量都指代第二个文本编码器对应的变量。否则,它来自第一个。

forward

< >

( hidden_states: typing.Optional[torch.Tensor] = None hidden_states_1: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.LongTensor] = None attention_mask_1: typing.Optional[torch.LongTensor] = None )

AudioLDM2UNet2DConditionModel

diffusers.AudioLDM2UNet2DConditionModel

< >

( sample_size: typing.Optional[int] = None in_channels: int = 4 out_channels: int = 4 flip_sin_to_cos: bool = True freq_shift: int = 0 down_block_types: typing.Tuple[str] = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D') mid_block_type: typing.Optional[str] = 'UNetMidBlock2DCrossAttn' up_block_types: typing.Tuple[str] = ('UpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D') only_cross_attention: typing.Union[bool, typing.Tuple[bool]] = False block_out_channels: typing.Tuple[int] = (320, 640, 1280, 1280) layers_per_block: typing.Union[int, typing.Tuple[int]] = 2 downsample_padding: int = 1 mid_block_scale_factor: float = 1 act_fn: str = 'silu' norm_num_groups: typing.Optional[int] = 32 norm_eps: float = 1e-05 cross_attention_dim: typing.Union[int, typing.Tuple[int]] = 1280 transformer_layers_per_block: typing.Union[int, typing.Tuple[int]] = 1 attention_head_dim: typing.Union[int, typing.Tuple[int]] = 8 num_attention_heads: typing.Union[int, typing.Tuple[int], NoneType] = None use_linear_projection: bool = False class_embed_type: typing.Optional[str] = None num_class_embeds: typing.Optional[int] = None upcast_attention: bool = False resnet_time_scale_shift: str = 'default' time_embedding_type: str = 'positional' time_embedding_dim: typing.Optional[int] = None time_embedding_act_fn: typing.Optional[str] = None timestep_post_act: typing.Optional[str] = None time_cond_proj_dim: typing.Optional[int] = None conv_in_kernel: int = 3 conv_out_kernel: int = 3 projection_class_embeddings_input_dim: typing.Optional[int] = None class_embeddings_concat: bool = False )

参数

  • sample_size (intTuple[int, int], 可选, 默认为 None) — 输入/输出样本的高度和宽度。
  • in_channels (int, 可选, 默认为 4) — 输入样本中的通道数。
  • out_channels (int, 可选, 默认为 4) — 输出中的通道数。
  • flip_sin_to_cos (bool, 可选, 默认为 False) — 是否在时间嵌入中将 sin 翻转为 cos。
  • freq_shift (int, 可选, 默认为 0) — 应用于时间嵌入的频率偏移。
  • down_block_types (Tuple[str], 可选, 默认为 ("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")) — 要使用的下采样块的元组。
  • mid_block_type (str, 可选, 默认为 "UNetMidBlock2DCrossAttn") — UNet 中间的块类型,对于 AudioLDM2 只能是 UNetMidBlock2DCrossAttn
  • up_block_types (Tuple[str], 可选, 默认为 ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")) — 要使用的上采样块的元组。
  • only_cross_attention (boolTuple[bool], 可选, 默认为 False) — 是否在基本 Transformer 块中包含自注意力,请参阅 BasicTransformerBlock
  • block_out_channels (Tuple[int], 可选, 默认为 (320, 640, 1280, 1280)) — 每个块的输出通道的元组。
  • layers_per_block (int, 可选, 默认为 2) — 每个块的层数。
  • downsample_padding (int, 可选, 默认为 1) — 用于下采样卷积的填充。
  • mid_block_scale_factor (float, 可选, 默认为 1.0) — 用于中间块的缩放因子。
  • act_fn (str, 可选, 默认为 "silu") — 要使用的激活函数。
  • norm_num_groups (int, 可选, 默认为 32) — 用于归一化的组数。如果为 None,则后处理中会跳过归一化和激活层。
  • norm_eps (float, 可选, 默认为 1e-5) — 用于归一化的 epsilon 值。
  • cross_attention_dim (intTuple[int], 可选, 默认为 1280) — 交叉注意力特征的维度。
  • transformer_layers_per_block (intTuple[int], 可选, 默认为 1) — BasicTransformerBlock 类型的 Transformer 块的数量。仅与 ~models.unet_2d_blocks.CrossAttnDownBlock2D~models.unet_2d_blocks.CrossAttnUpBlock2D~models.unet_2d_blocks.UNetMidBlock2DCrossAttn 相关。
  • attention_head_dim (int, 可选, 默认为 8) — 注意力头的维度。
  • num_attention_heads (int, 可选) — 注意力头的数量。如果未定义,则默认为 attention_head_dim
  • resnet_time_scale_shift (str, 可选, 默认为 "default") — ResNet 模块的时间尺度偏移配置(参见 ResnetBlock2D)。从 defaultscale_shift 中选择。
  • class_embed_type (str, 可选, 默认为 None) — 要使用的类别嵌入类型,它最终与时间嵌入求和。从 None"timestep""identity""projection""simple_projection" 中选择。
  • num_class_embeds (int, 可选, 默认为 None) — 当 class_embed_type 等于 None 时,可学习嵌入矩阵的输入维度,该矩阵将被投影到 time_embed_dim
  • time_embedding_type (str, 可选, 默认为 positional) — 用于时间步的位置嵌入类型。从 positionalfourier 中选择。
  • time_embedding_dim (int, 可选, 默认为 None) — 用于时间步嵌入维度的可选覆盖。
  • time_embedding_act_fn (str, 可选, 默认为 None) — 可选的激活函数,仅在时间嵌入传递到 UNet 的其余部分之前使用一次。从 silumishgeluswish 中选择。
  • timestep_post_act (str, 可选, 默认为 None) — 在时间步嵌入中使用的第二个激活函数。从 silumishgelu 中选择。
  • time_cond_proj_dim (int, 可选, 默认为 None) — 时间步嵌入中 cond_proj 层的维度。
  • conv_in_kernel (int, 可选, 默认为 3) — conv_in 层的内核大小。
  • conv_out_kernel (int, 可选, 默认为 3) — conv_out 层的内核大小。
  • projection_class_embeddings_input_dim (int, 可选) — 当 class_embed_type="projection" 时,class_labels 输入的维度。当 class_embed_type="projection" 时为必需。
  • class_embeddings_concat (bool, 可选, 默认为 False) — 是否将时间嵌入与类别嵌入连接。

一个有条件的 2D UNet 模型,它接受一个噪声样本、条件状态和时间步,并返回一个样本形状的输出。与原始的 UNet2DConditionModel 相比,此变体在每个 Transformer 块中可选地包含一个额外的自注意力层,以及多个交叉注意力层。它还允许最多两个交叉注意力嵌入:encoder_hidden_statesencoder_hidden_states_1

此模型继承自 ModelMixin。查看超类文档以了解为其所有模型实现的通用方法(例如下载或保存)。

forward

< >

( sample: Tensor timestep: typing.Union[torch.Tensor, float, int] encoder_hidden_states: Tensor class_labels: typing.Optional[torch.Tensor] = None timestep_cond: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None return_dict: bool = True encoder_hidden_states_1: typing.Optional[torch.Tensor] = None encoder_attention_mask_1: typing.Optional[torch.Tensor] = None ) UNet2DConditionOutputtuple

参数

  • sample (torch.Tensor) — 噪声输入张量,形状如下 (batch, channel, height, width)
  • timestep (torch.Tensorfloatint) — 用于去噪输入的timestep数量。
  • encoder_hidden_states (torch.Tensor) — 编码器隐藏状态,形状为 (batch, sequence_length, feature_dim)
  • encoder_attention_mask (torch.Tensor) — 应用于 encoder_hidden_states 的形状为 (batch, sequence_length) 的交叉注意力掩码。如果为 True,则保留掩码;如果为 False,则丢弃掩码。掩码将转换为偏置,这会将较大的负值添加到与“丢弃”标记对应的注意力分数中。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 UNet2DConditionOutput 而不是普通的元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 AttnProcessor
  • encoder_hidden_states_1 (torch.Tensor, 可选) — 第二组编码器隐藏状态,形状为 (batch, sequence_length_2, feature_dim_2)。可用于根据与 encoder_hidden_states 不同的一组嵌入来调节模型。
  • encoder_attention_mask_1 (torch.Tensor, 可选) — 应用于 encoder_hidden_states_1 的形状为 (batch, sequence_length_2) 的交叉注意力掩码。如果为 True,则保留掩码;如果为 False,则丢弃掩码。掩码将转换为偏置,这会将较大的负值添加到与“丢弃”标记对应的注意力分数中。

返回

UNet2DConditionOutputtuple

如果 return_dict 为 True,则返回 UNet2DConditionOutput,否则返回 tuple,其中第一个元素是样本张量。

AudioLDM2UNet2DConditionModel 的前向方法。

AudioPipelineOutput

class diffusers.AudioPipelineOutput

< >

( audios: ndarray )

参数

  • audios (np.ndarray) — 降噪音频样本列表,为形状为 (batch_size, num_channels, sample_rate) 的 NumPy 数组。

音频管道的输出类。

< > 在 GitHub 上更新