Diffusers documentation

AudioLDM 2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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),以投影后的 CLAP 和 Flan-T5 嵌入为条件,自回归地预测八个新的嵌入向量。生成的嵌入向量和 Flan-T5 文本嵌入被用作 LDM 中的交叉注意力条件。AudioLDM 2 的 UNet 具有独特之处,因为它接收两个交叉注意力嵌入,而大多数其他 LDM 仅使用一个交叉注意力条件。

该论文的摘要如下:

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

此流水线由 sanchit-gandhi 和 Nguyễn Công Tú Anh 贡献。原始代码库可在 haoheliu/audioldm2 中找到。

提示

选择检查点

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

所有检查点中,文本编码器和 VAE 的模型大小均相同。它们的区别在于 UNet 的大小和深度。 有关这三个检查点的详细信息,请参阅下表:

检查点任务UNet 模型大小模型总大小训练数据 / h
audioldm2文本到音频350M1.1B1150k
audioldm2-large文本到音频750M1.5B1150k
audioldm2-music文本生成音乐350M1.1B665k
audioldm2-gigaspeech文本转语音350M1.1B10k
audioldm2-ljspeech文本转语音350M1.1B

构建提示

  • 描述性提示词输入效果最佳:使用形容词来描述声音(例如“高质量”或“清晰”),并使提示词具有具体的上下文(例如使用“森林中的溪流”而不是“溪流”)。
  • 最好使用“猫”或“狗”这类通用词汇,而不是模型可能不熟悉的具体名称或抽象对象。
  • 使用负面提示词可以显著提升生成波形的质量,通过引导生成过程避开对应低质量音频的词汇。请尝试使用“Low quality.”作为负面提示词。

控制推理

  • 预测音频样本的质量可通过num_inference_steps参数进行控制;步数越高,音频质量越好,但推理速度会相应降低。
  • 可以通过调整 audio_length_in_s 参数来控制预测音频样本的 length。

评估生成的波形:

  • 生成波形的质量会因随机种子不同而有显著差异。请尝试使用不同的种子进行生成,直到获得满意的结果。
  • 可以一次性生成多条波形:将 num_waveforms_per_prompt 设置为大于 1 的值。系统会在生成的波形与提示文本之间进行自动评分,并据此将音频从最佳到最差进行排序。

以下示例展示了如何利用上述技巧构建优质的音乐和语音生成:示例。

请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

AudioLDM2Pipeline

类 diffusers.AudioLDM2Pipeline

< >

( vae: AutoencoderKLtext_encoder: ClapModeltext_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.vits.modeling_vits.VitsModelprojection_model: AudioLDM2ProjectionModellanguage_model: GPT2LMHeadModeltokenizer: RobertaTokenizertokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | transformers.models.vits.tokenization_vits.VitsTokenizerfeature_extractor: ClapFeatureExtractorunet: AudioLDM2UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvocoder: 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。
  • tokenizer_2 ([~transformers.T5Tokenizer, ~transformers.VitsTokenizer]) — 用于对第二个冻结文本编码器输入文本进行分词的 Tokenizer。
  • feature_extractor (ClapFeatureExtractor) — 用于将生成的音频波形预处理为对数梅尔频谱图,以便进行自动评分的特征提取器。
  • unet (UNet2DConditionModel) — 一个用于对编码后的音频潜变量进行去噪的 UNet2DConditionModel。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的音频潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
  • vocoder(SpeechT5HifiGan)— SpeechT5HifiGan 类的声码器,用于将梅尔频谱潜变量转换为最终的音频波形。

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

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str] = Nonetranscription: str | list[str] = Noneaudio_length_in_s: float | None = Nonenum_inference_steps: int = 200guidance_scale: float = 3.5negative_prompt: str | list[str] | None = Nonenum_waveforms_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonegenerated_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_generated_prompt_embeds: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonenegative_attention_mask: typing.Optional[torch.LongTensor] = Nonemax_new_tokens: int | None = Nonereturn_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int | None = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneoutput_type: str | None = 'np' ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导音频生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • transcription (str 或 list[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(str 或 list[str],可选)— 用于指导音频生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • num_waveforms_per_prompt (int,可选,默认为 1) — 每个提示词生成的波形数量。如果 num_waveforms_per_prompt > 1,则会在生成的输出与文本提示词之间执行自动评分。该评分根据生成的波形与文本输入在联合文本-音频嵌入空间中的余弦相似度,对生成的波形进行排序。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作频谱图生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则通过采样使用提供的随机generator生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor,可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • generated_prompt_embeds (torch.Tensor, 可选) — 由 GPT2 语言模型预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,则会根据 prompt 输入参数生成文本嵌入。
  • negative_generated_prompt_embeds (torch.Tensor, 可选) — 由 GPT2 语言模型预生成的负向文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数计算得出。
  • attention_mask (torch.LongTensor, 可选) — 预先计算好的注意力掩码,将应用于 prompt_embeds。如果未提供,则会根据 prompt 输入参数计算注意力掩码。
  • negative_attention_mask (torch.LongTensor, 可选) — 预先计算好的注意力掩码,将应用于 negative_prompt_embeds。如果未提供,则会根据 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)的输出。

返回值

StableDiffusionPipelineOutput 或 tuple

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

用于生成的 pipeline 的调用函数。

示例:

>>> 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])

enable_model_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = 'cuda' )

使用 accelerate 将所有模型卸载到 CPU,在性能影响较小的情况下降低内存占用。与 enable_sequential_cpu_offload 相比,此方法在调用某个模型的 forward 方法时,会将整个模型一次性移至 GPU,并且该模型会一直保留在 GPU 上,直到下一个模型开始运行。与 enable_sequential_cpu_offload 相比,此方法的内存节省幅度较小,但由于 unet 的迭代执行,其性能要好得多。

encode_prompt

< >

( promptdevicenum_waveforms_per_promptdo_classifier_free_guidancetranscription = Nonenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonegenerated_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_generated_prompt_embeds: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonenegative_attention_mask: typing.Optional[torch.LongTensor] = Nonemax_new_tokens: int | None = None ) → prompt_embeds (torch.Tensor)

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • transcription (str 或 list[str]) — 要转换为语音的文本
  • device (torch.device) — torch 设备
  • num_waveforms_per_prompt (int) — 每个提示词应生成的波形数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str],可选) — 用于不引导音频生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时(即 guidance_scale 小于 1 时)将被忽略。
  • prompt_embeds (torch.Tensor, 可选) — 来自 Flan T5 模型的预计算文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,则将根据 prompt 输入参数计算文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 由 Flan T5 模型预计算的负向文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数计算得出。
  • generated_prompt_embeds (torch.Tensor, 可选) — 由 GPT2 语言模型预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,则会根据 prompt 输入参数生成文本嵌入。
  • negative_generated_prompt_embeds (torch.Tensor, 可选) — 由 GPT2 语言模型预生成的负向文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数计算得出。
  • 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 = Nonemax_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 函数的额外模型特定参数的字典。

返回值

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

生成的隐藏状态序列。

根据嵌入输入,从语言模型生成隐藏状态序列。

AudioLDM2ProjectionModel

类 diffusers.AudioLDM2ProjectionModel

< >

( text_encoder_dimtext_encoder_1_dimlangauge_model_dimuse_learned_position_embedding = Nonemax_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] = Nonehidden_states_1: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneattention_mask_1: typing.Optional[torch.LongTensor] = None ) → AudioLDM2ProjectionModelOutput

参数

  • hidden_states(形状为 (batch_size, sequence_length, text_encoder_dim) 的 torch.Tensor,可选)— 来自第一个文本编码器(CLAP)的文本嵌入。
  • hidden_states_1(形状为 (batch_size, sequence_length_1, text_encoder_1_dim) 的 torch.Tensor,可选) — 来自第二个文本编码器(T5 或 VITS)的文本嵌入。
  • attention_mask (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — hidden_states 的注意力掩码。
  • attention_mask_1(形状为 (batch_size, sequence_length_1) 的 torch.LongTensor,可选)— hidden_states_1 的注意力掩码。

返回值

AudioLDM2ProjectionModelOutput

两个文本编码器投影后的文本嵌入,沿序列维度拼接,以及它们合并后的注意力掩码。

AudioLDM2UNet2DConditionModel

class diffusers.AudioLDM2UNet2DConditionModel

< >

( sample_size: int | None = Nonein_channels: int = 4out_channels: int = 4flip_sin_to_cos: bool = Truefreq_shift: int = 0down_block_types: tuple = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D')mid_block_type: str = 'UNetMidBlock2DCrossAttn'up_block_types: tuple = ('UpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D')only_cross_attention: bool | tuple[bool] = Falseblock_out_channels: tuple = (320, 640, 1280, 1280)layers_per_block: int | tuple[int] = 2downsample_padding: int = 1mid_block_scale_factor: float = 1act_fn: str = 'silu'norm_num_groups: int | None = 32norm_eps: float = 1e-05cross_attention_dim: int | tuple[int] = 1280transformer_layers_per_block: int | tuple[int] = 1attention_head_dim: int | tuple[int] = 8num_attention_heads: int | tuple[int] | None = Noneuse_linear_projection: bool = Falseclass_embed_type: str | None = Nonenum_class_embeds: int | None = Noneupcast_attention: bool = Falseresnet_time_scale_shift: str = 'default'time_embedding_type: str = 'positional'time_embedding_dim: int | None = Nonetime_embedding_act_fn: str | None = Nonetimestep_post_act: str | None = Nonetime_cond_proj_dim: int | None = Noneconv_in_kernel: int = 3conv_out_kernel: int = 3projection_class_embeddings_input_dim: int | None = Noneclass_embeddings_concat: bool = False )

参数

  • sample_size (int 或 tuple[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 (bool 或 tuple[bool],可选,默认为 False) — 是否在基础 Transformer 块中包含自注意力,参见 BasicTransformerBlock。
  • block_out_channels (tuple[int],可选,默认为 (320, 640, 1280, 1280)) — 每个 block 的输出通道数元组。
  • 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 (int 或 tuple[int],可选,默认值为 1280) — 交叉注意力特征的维度。
  • transformer_layers_per_block(int 或 tuple[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)。可选值为 default 或 scale_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) — 用于时间步的位置嵌入类型。可选值为 positional 或 fourier。
  • time_embedding_dim (int,可选,默认为 None) — 用于覆盖投影后时间嵌入维度的可选参数。
  • time_embedding_act_fn (str,可选,默认为 None) — 可选的激活函数,仅在时间嵌入传递到 UNet 其余部分之前使用一次。可从 silu、mish、gelu 和 swish 中选择。
  • timestep_post_act (str,可选,默认为 None) — 用于时间步嵌入的第二个激活函数。可从 silu、mish 和 gelu 中选择。
  • 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_states 和 encoder_hidden_states_1。

该模型继承自 ModelMixin。请查阅其父类文档,了解为所有模型实现的通用方法(例如下载或保存)。

forward

< >

( sample: Tensortimestep: typing.Union[torch.Tensor, float, int]encoder_hidden_states: Tensorclass_labels: typing.Optional[torch.Tensor] = Nonetimestep_cond: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneencoder_attention_mask: typing.Optional[torch.Tensor] = Nonereturn_dict: bool = Trueencoder_hidden_states_1: typing.Optional[torch.Tensor] = Noneencoder_attention_mask_1: typing.Optional[torch.Tensor] = None ) → UNet2DConditionOutput or tuple

参数

  • sample (torch.Tensor) — 形状为 (batch, channel, height, width) 的含噪输入张量。
  • timestep(torch.Tensor 或 float 或 int)— 用于对输入进行去噪的时间步数。
  • 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, 可选) — 形状为 (batch, sequence_length_2) 的交叉注意力掩码,应用于 encoder_hidden_states_1。 如果为 True,则保留该掩码;否则,如果为 False,则将其丢弃。掩码将被转换为偏置, 向对应于“丢弃”标记的注意力分数添加较大的负值。

返回值

UNet2DConditionOutput 或 tuple

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

AudioLDM2UNet2DConditionModel 的前向方法。

AudioPipelineOutput

类 diffusers.AudioPipelineOutput

< >

( audios: ndarray )

参数

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

音频管道的输出类。

Update on GitHub