Diffusers documentation

Stable Audio 3

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

Stable Audio 3

Stable Audio 3 (SA3) 是 Stability AI 推出的文本生成音频模型,可生成 44.1 kHz 的高质量立体声音频。它使用以两个信号为条件的 rectified-flow DiT:

  • 文本 — 由冻结的 T5Gemma 编码器进行编码,并通过交叉注意力机制注入。
  • Duration — 一个浮点数(单位:秒),由 StableAudio3DurationEmbedder 嵌入,并用作自适应层归一化的全局条件向量。

音频由 SAME(Semantically-Aligned Music Encoder)自编码器 AutoencoderSAME 进行解码。

两个检查点均使用 FlowMatchEulerDiscreteScheduler 并采用对数 SNR 均匀 sigma 调度,仅在 stochastic_sampling 和默认步数上有所不同:

检查点diffusion_objectivestochastic_samplingnum_inference_steps
stable-audio-3-medium-baserectified_flowFalse(确定性欧拉法)100(未蒸馏)
stable-audio-3-medium(蒸馏版)rf_denoiserTrue(乒乓式重新加噪)8(蒸馏 8 步)

正确的调度器配置已内置于每个转换后的检查点中,因此当 num_inference_steps 未设置时,其默认值即为正确值。仅在需要覆盖该值时才传入此参数。

原始代码库:Stability-AI/stable-audio-3。

转换原始检查点

Stability AI 的检查点并非以 diffusers 格式发布,因此需要在本地进行转换。该脚本会下载检查点的 model_config.json,并根据其中的 diffusion_objective 选择调度器:

python scripts/convert_stable_audio_3_to_diffusers.py \
  --checkpoint_path stabilityai/stable-audio-3-medium-base \
  --text_encoder_repo google/t5gemma-b-b-ul2 \
  --output_dir /tmp/sa3-diffusers-euler \
  --dtype float32

stable-audio-3-medium-base 是一个受控访问仓库。在转换之前,请使用具有访问权限的账户运行 hf auth login,否则下载将因 401 错误而失败。

使用示例

从其本地输出目录加载转换后的检查点(使用 pip install soundfile 安装 soundfile):

import torch
import soundfile as sf
from diffusers import StableAudio3Pipeline

pipe = StableAudio3Pipeline.from_pretrained("/tmp/sa3-diffusers-euler", torch_dtype=torch.float32)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

generator = torch.Generator("cuda").manual_seed(0)
audio = pipe(
    "A gentle piano melody with soft strings in a concert hall",
    duration=10.0,  # seconds; latent length is computed automatically
    generator=generator,
).audios

sf.write("sa3_output.wav", audio[0].T.cpu().float().numpy(), samplerate=44100)

该 pipeline 还注册在 AutoPipelineForText2Audio 中,它会自动将 checkpoint 解析为 StableAudio3Pipeline:

from diffusers import AutoPipelineForText2Audio

pipe = AutoPipelineForText2Audio.from_pretrained("/tmp/sa3-diffusers-euler", torch_dtype=torch.float32)

示例使用本地路径,因为 stabilityai/stable-audio-3-medium 和 stable-audio-3-medium-base 尚未以 diffusers 格式发布(通过 repo id 加载会返回 404)。一旦发布,即可使用 repo id 替代本地路径。

提示

  • 在 CPU 或 MPS(Apple Silicon)上使用 torch.float32 —— 在 MPS 上使用 torch.float16 会产生噪声。
  • 蒸馏模型(stable-audio-3-medium)经过对抗蒸馏——引导已融入权重。 请保持 guidance_scale=1.0(默认值),并且不要为该检查点传入 negative_prompt;这两项仅对非蒸馏的 stable-audio-3-medium-base 检查点有效。
  • silence_padding_duration(默认值为 0.0)会在潜在序列的末尾添加一段静音余量。除非模型经过专门训练以屏蔽该填充,否则请保持为 0.0,否则额外的帧会消耗输出能量,导致结果音量变低。
  • 将 num_waveforms_per_prompt > 1 设置为大于 1 的值,可为每个提示词生成多个片段。

StableAudio3Pipeline

class diffusers.StableAudio3Pipeline

< >

( vae: AutoencoderSAMEtext_encoder: T5GemmaEncoderModeltokenizer: GemmaTokenizerduration_embedder: StableAudio3DurationEmbeddertransformer: StableAudio3DiTModelscheduler: FlowMatchEulerDiscreteScheduler )

参数

  • vae ([AutoencoderSAME]) — 用于编码和解码音频潜变量的 SAME 自编码器。
  • text_encoder ([~transformers.T5GemmaEncoderModel]) — 冻结的 T5Gemma 文本编码器(google/t5gemma-b-b-ul2)。
  • tokenizer ([~transformers.GemmaTokenizerFast]) — 文本编码器的分词器。
  • duration_embedder ([StableAudio3DurationEmbedder]) — 将秒为单位的 duration 映射为每个 DiT 块中 AdaLN 的全局条件向量。
  • transformer ([StableAudio3DiTModel]) — 用于 rectified-flow 速度预测的 DiT。
  • scheduler([FlowMatchEulerDiscreteScheduler])— 用于迭代去噪循环的调度器。生产环境(蒸馏)SA3 Medium 检查点使用 stochastic_sampling=True 执行恰好 8 步 ping-pong 步骤;非蒸馏的基础检查点使用 stochastic_sampling=False 执行约 100 步确定性 Euler 步骤。

使用 Stable Audio 3 进行文本到音频生成的 Pipeline。

SA3 使用经过蒸馏的 rectified-flow DiT,并采用 ping-pong 采样。对于蒸馏后的检查点,无需使用无分类器引导(guidance_scale / negative_prompt)(保持默认的 guidance_scale=1.0 即可),但对于未蒸馏的 stable-audio-3-medium-base 检查点,无分类器引导则具有实际意义。

该模型继承自 [DiffusionPipeline]。有关为所有流水线实现的通用方法,请参阅父类文档。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = Noneduration: float = 10.0num_inference_steps: typing.Optional[int] = Nonelogsnr_min: float = -6.2logsnr_max: float = 2.0silence_padding_duration: float = 0.0guidance_scale: float = 1.0negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonenum_waveforms_per_prompt: int = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_encoder_attention_mask: typing.Optional[torch.LongTensor] = Nonereturn_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']output_type: str = 'pt' ) → [~pipelines.AudioPipelineOutput] or tuple

参数

  • prompt (str 或 list[str],可选) — 文本提示词。若要跳过分词和编码,请改为传入 prompt_embeds。
  • duration (float,默认为 10.0) — 以秒为单位的请求输出时长。
  • num_inference_steps (int, 可选) — 去噪步数。当为 None(默认值)时,步数由调度器的 stochastic_sampling 配置决定:当 True 时为 8(蒸馏后的 ping-pong 风格检查点),当 False 时为 100 (未蒸馏的基础检查点)。传入显式值可覆盖此默认行为。
  • logsnr_min (float,默认为 -6.2) — 噪声调度的最小 log-SNR 值 — 对应调度中高噪声的起始点。
  • logsnr_max (float,默认为 2.0) — 噪声调度的最大 log-SNR 值 — 对应调度的低噪声端。
  • silence_padding_duration (float,默认值为 0.0) — 在目标内容之外额外生成的潜在上下文秒数,为模型在边界处提供余量;输出会被裁剪回 duration。默认值为 0.0(禁用)。仅当模型经过训练或蒸馏以屏蔽此填充时才增加该值——否则,额外的帧会消耗输出能量。
  • guidance_scale (float,默认值为 1.0) — 无分类器引导(Classifier-free guidance)的缩放系数。1.0 表示禁用引导(这是默认值,也是蒸馏版 SA3 Medium 检查点唯一合理的取值,因为其 CFG 已固化在权重中)。对于非蒸馏的 stable-audio-3-medium-base 检查点,> 1.0 的取值才有意义;数值越高,生成结果越严格地遵循提示词,但多样性会降低。
  • negative_prompt (str 或 list[str],可选) — 当 guidance_scale > 1.0 时,描述需要避免生成的内容的提示词。当 guidance_scale > 1.0 且未提供此参数或 negative_prompt_embeds 时,默认为空字符串(无条件)。当 guidance_scale <= 1.0 时,此参数将被忽略。
  • num_waveforms_per_prompt (int,默认为 1) — 每个提示词生成的波形数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于在乒乓循环中实现确定性生成和可复现的重新加噪。
  • latents (torch.Tensor, 可选) — 预生成的起始潜变量。如果为 None,则会采样一个新的 Gaussian 张量。
  • prompt_embeds (torch.Tensor,可选) — 预计算文本嵌入 (batch, seq_len, 768)。
  • encoder_attention_mask (torch.LongTensor, 可选) — 用于预计算嵌入的布尔掩码。
  • negative_prompt_embeds (torch.Tensor,可选) — 预计算的负向文本嵌入,作为 negative_prompt 的替代方案。
  • negative_encoder_attention_mask (torch.LongTensor,可选) — 用于预计算负样本嵌入的布尔掩码。
  • return_dict (bool,默认为 True) — 返回 AudioPipelineOutput 或普通元组。
  • callback_on_step_end (Callable,可选) — 在每个去噪步骤结束时调用,参数为 (self, step_idx, timestep, callback_kwargs),其中 callback_kwargs 包含 callback_on_step_end_tensor_inputs 中列出的张量。必须返回一个 字典,其中包含用于循环剩余部分的(可选修改后的)张量。
  • callback_on_step_end_tensor_inputs (list[str],默认为 [“latents”]) — 传递给 callback_on_step_end 的张量。必须是 self._callback_tensor_inputs 的子集。
  • output_type (str,默认为 "pt") — "pt" 表示 PyTorch 张量,"np" 表示 NumPy 数组,或 "latent" 表示跳过解码并返回原始潜在表示。

返回值

[~pipelines.AudioPipelineOutput] 或 tuple

.audios 是一个形状为 (batch * num_waveforms_per_prompt, audio_channels, samples) 的张量 / 数组。

根据文本提示生成音频。

示例:

>>> import torch
>>> import soundfile as sf
>>> from diffusers import StableAudio3Pipeline

>>> pipe = StableAudio3Pipeline.from_pretrained("stabilityai/stable-audio-3-medium", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)

encode_duration

< >

( duration: floatdevice: devicenum_waveforms_per_prompt: intbatch_size: int )

参数

  • duration — 以秒为单位的时长,应用于批次中的每个样本。
  • device — 目标设备。
  • num_waveforms_per_prompt — 平铺因子。
  • batch_size — 提示词的数量。

将时长值嵌入到全局条件向量中。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str], NoneType]device: devicenum_waveforms_per_prompt: intprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = None )

参数

  • prompt — 文本提示词或提示词列表。当提供 prompt_embeds 时将被忽略。
  • device — 目标设备。
  • num_waveforms_per_prompt — 每个提示词要生成的输出波形数量;条件张量会相应地进行平铺。
  • prompt_embeds — 预计算文本嵌入 (batch, seq_len, hidden_size)。
  • encoder_attention_mask — 用于预计算嵌入的布尔掩码,形状为 (batch, seq_len);1 表示真实 token,0 表示填充。

将文本提示编码为交叉注意力条件张量。

prepare_cross_attention

< >

( prompt_embeds: Tensorencoder_attention_mask: Tensorglobal_hidden_states: Tensor )

通过追加时长嵌入作为额外标记,构建交叉注意力上下文。

SA3 将 seconds_total 条件器路由到 两者:全局(AdaLN)输入和交叉注意力上下文(cross_attention_cond_ids = ["prompt", "seconds_total"])。时长嵌入拼接在文本 token 之后,注意力掩码也会扩展一个有效条目。

StableAudio3InpaintPipeline

class diffusers.StableAudio3InpaintPipeline

< >

( vae: AutoencoderSAMEtext_encoder: T5GemmaEncoderModeltokenizer: GemmaTokenizerduration_embedder: StableAudio3DurationEmbeddertransformer: StableAudio3DiTModelscheduler: FlowMatchEulerDiscreteScheduler )

参数

  • vae ([AutoencoderSAME]) — 用于编码和解码音频潜变量的 SAME 自编码器。
  • text_encoder ([~transformers.T5GemmaEncoderModel]) — 冻结的 T5Gemma 文本编码器(google/t5gemma-b-b-ul2)。
  • tokenizer ([~transformers.GemmaTokenizerFast]) — 文本编码器的分词器。
  • duration_embedder ([StableAudio3DurationEmbedder]) — 将秒为单位的 duration 映射为每个 DiT 块中 AdaLN 的全局条件向量。
  • transformer ([StableAudio3DiTModel]) — 用于 rectified-flow 速度预测的 DiT。
  • scheduler([FlowMatchEulerDiscreteScheduler])— 用于迭代去噪循环的调度器。生产环境(蒸馏)SA3 Medium 检查点使用 stochastic_sampling=True 执行恰好 8 步 ping-pong 步骤;非蒸馏的基础检查点使用 stochastic_sampling=False 执行约 100 步确定性 Euler 步骤。

Stable Audio 3 的音频修复(inpainting)流水线。

与 [StableAudio3Pipeline] 共享其文本到音频的逻辑(通过 # Copied from 保持同步)。当提供 audio 和 mask 时,使用冻结的 SAME 编码器对参考音频进行编码,并通过 transformer 的 local_add_cond 路径(to_local_embed)将 masked_latent ∥ mask 作为局部加性条件注入到每个 DiT 块中。

调用签名扩展(参见 __call__): audio (torch.Tensor,形状为 (batch, channels, samples)): 参考音频波形,采样率为 vae.config.sampling_rate Hz。 mask (torch.Tensor,形状为 (batch, 1, latent_length)): 潜在空间中的逐帧二值掩码。1 = 保留原始音频;0 = 需要修复的区域。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = Noneduration: float = 10.0audio: typing.Optional[torch.Tensor] = Nonemask: typing.Optional[torch.Tensor] = Nonemask_start_seconds: typing.Union[float, typing.List[float], NoneType] = Nonemask_end_seconds: typing.Union[float, typing.List[float], NoneType] = Nonenum_inference_steps: typing.Optional[int] = Nonelogsnr_min: float = -6.2logsnr_max: float = 2.0silence_padding_duration: float = 0.0num_waveforms_per_prompt: int = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = Nonereturn_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']output_type: str = 'pt' )

参数

  • prompt (str 或 list[str],可选) — 文本提示。
  • duration (float,默认为 10.0) — 以秒为单位的输出时长。应与参考音频的时长一致。
  • audio (torch.Tensor, optional) — 参考波形 (batch, channels, samples),采样率为 vae.config.sampling_rate Hz。执行 inpainting 时必填。
  • mask (torch.Tensor, optional) — 逐帧潜在空间掩码 (batch, 1, L),其中 0 表示重绘区域,1 表示保留区域。必须提供 mask 或 mask_start_seconds / mask_end_seconds。
  • mask_start_seconds (float 或 list[float],可选) — 以秒为单位的修复区域起始时间。
  • mask_end_seconds (float 或 list[float],可选) — 修复区域的结束时间(必须与 mask_start_seconds 配对使用)。
  • num_inference_steps (int, 可选) — 去噪步数。当为 None(默认值)时,步数将从调度器的 stochastic_sampling 配置中选取,与 [StableAudio3Pipeline] 保持一致。
  • logsnr_min (float,默认为 -6.2) — 噪声调度的最小 log-SNR 值 — 对应调度中高噪声的起始点。
  • logsnr_max (float,默认为 2.0) — 噪声调度的最大 log-SNR 值 — 对应调度的低噪声端。
  • silence_padding_duration (float,默认为 0.0) — 目标内容之后的额外潜在余量。
  • num_waveforms_per_prompt (int,默认为 1) — 每个提示词生成的波形数量。
  • generator — 用于可复现性的随机数生成器。
  • latents — 预生成的起始噪声(None → 重新采样)。
  • prompt_embeds — 预计算文本嵌入。
  • encoder_attention_mask — 预计算嵌入的掩码。
  • return_dict (bool,默认为 True) — 返回 AudioPipelineOutput 或元组。
  • callback_on_step_end (Callable,可选) — 在每个去噪步骤结束时调用,参数为 (self, step_idx, timestep, callback_kwargs)。必须返回一个字典,其中包含用于循环剩余部分的(可选修改后的)张量。
  • callback_on_step_end_tensor_inputs (list[str],默认为 [“latents”]) — 传递给 callback_on_step_end 的张量。必须是 self._callback_tensor_inputs 的子集。
  • output_type(str,默认为 "pt")— "pt" / "np" / "latent"。

根据文本提示和参考音频生成修复后的音频。

示例:

>>> import torch
>>> import soundfile as sf
>>> import torchaudio
>>> from diffusers import StableAudio3InpaintPipeline

>>> pipe = StableAudio3InpaintPipeline.from_pretrained(
...     "stabilityai/stable-audio-3-medium", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> audio, sr = torchaudio.load("reference.wav")
>>> audio = torchaudio.functional.resample(audio, sr, pipe.vae.config.sampling_rate).unsqueeze(0).to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     audio=audio,
...     mask_start_seconds=4.0,
...     mask_end_seconds=6.0,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)

encode_duration

< >

( duration: floatdevice: devicenum_waveforms_per_prompt: intbatch_size: int )

参数

  • duration — 以秒为单位的时长,应用于批次中的每个样本。
  • device — 目标设备。
  • num_waveforms_per_prompt — 平铺因子。
  • batch_size — 提示词的数量。

将时长值嵌入到全局条件向量中。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str], NoneType]device: devicenum_waveforms_per_prompt: intprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = None )

参数

  • prompt — 文本提示词或提示词列表。当提供 prompt_embeds 时将被忽略。
  • device — 目标设备。
  • num_waveforms_per_prompt — 每个提示词要生成的输出波形数量;条件张量会相应地进行平铺。
  • prompt_embeds — 预计算文本嵌入 (batch, seq_len, hidden_size)。
  • encoder_attention_mask — 用于预计算嵌入的布尔掩码,形状为 (batch, seq_len);1 表示真实 token,0 表示填充。

将文本提示编码为交叉注意力条件张量。

prepare_cross_attention

< >

( prompt_embeds: Tensorencoder_attention_mask: Tensorglobal_hidden_states: Tensor )

通过追加时长嵌入作为额外标记,构建交叉注意力上下文。

SA3 将 seconds_total 条件器路由到 两者:全局(AdaLN)输入和交叉注意力上下文(cross_attention_cond_ids = ["prompt", "seconds_total"])。时长嵌入拼接在文本 token 之后,注意力掩码也会扩展一个有效条目。

StableAudio3AudioToAudioPipeline

生成参考音频片段的变体:整个参考音频被加噪至 init_noise_level,然后从该状态开始去噪;这与 StableAudio3InpaintPipeline 的逐帧局部加性条件不同,后者会精确保留特定帧。

class diffusers.StableAudio3AudioToAudioPipeline

< >

( vae: AutoencoderSAMEtext_encoder: T5GemmaEncoderModeltokenizer: GemmaTokenizerduration_embedder: StableAudio3DurationEmbeddertransformer: StableAudio3DiTModelscheduler: FlowMatchEulerDiscreteScheduler )

参数

  • vae ([AutoencoderSAME]) — 用于编码和解码音频潜变量的 SAME 自编码器。
  • text_encoder ([~transformers.T5GemmaEncoderModel]) — 冻结的 T5Gemma 文本编码器(google/t5gemma-b-b-ul2)。
  • tokenizer ([~transformers.GemmaTokenizerFast]) — 文本编码器的分词器。
  • duration_embedder ([StableAudio3DurationEmbedder]) — 将秒为单位的 duration 映射为每个 DiT 块中 AdaLN 的全局条件向量。
  • transformer ([StableAudio3DiTModel]) — 用于 rectified-flow 速度预测的 DiT。
  • scheduler([FlowMatchEulerDiscreteScheduler])— 用于迭代去噪循环的调度器。生产环境(蒸馏)SA3 Medium 检查点使用 stochastic_sampling=True 执行恰好 8 步 ping-pong 步骤;非蒸馏的基础检查点使用 stochastic_sampling=False 执行约 100 步确定性 Euler 步骤。

Stable Audio 3 的音频到音频变体流水线。

与 [StableAudio3Pipeline] 共享其文本到音频的逻辑(通过 # Copied from 保持同步)。使用冻结的 SAME 编码器对参考音频进行编码,根据 init_noise_level 将其与新的噪声混合,然后从该状态开始去噪——整个信号是全局加噪/去噪的,这与 [StableAudio3InpaintPipeline] 的逐帧局部加性条件不同。

调用签名扩展(参见 __call__): audio (torch.Tensor,形状为 (batch, channels, samples)): 采样率为 vae.config.sampling_rate Hz 的参考音频波形。 init_noise_level (float): 在去噪之前混入参考音频的噪声量。1.0 表示完全噪声(等效于 文本生成音频);较低的数值会保留更多参考音频的内容。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = Noneduration: float = 10.0audio: typing.Optional[torch.Tensor] = Noneinit_noise_level: float = 1.0num_inference_steps: typing.Optional[int] = Nonelogsnr_min: float = -6.2logsnr_max: float = 2.0silence_padding_duration: float = 0.0num_waveforms_per_prompt: int = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = Nonereturn_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']output_type: str = 'pt' )

参数

  • prompt (str 或 list[str],可选) — 文本提示。
  • duration (float,默认为 10.0) — 以秒为单位的输出时长。应与参考音频的时长一致。
  • audio (torch.Tensor, optional) — 参考波形 (batch, channels, samples),采样率为 vae.config.sampling_rate Hz。必填。
  • init_noise_level (float,默认值为 1.0) — 在去噪之前混合到参考信号中的噪声水平(取值范围为 (0, 1]):x_start = (1 - init_noise_level) * reference_latents + init_noise_level * noise。1.0 会完全丢弃参考信号(等效于 [StableAudio3Pipeline]);较低的取值会在执行完整步数的同时,逐步保留更多参考信号的结构。
  • num_inference_steps (int,可选) — 去噪步数。当为 None(默认值)时,步数将从调度器的 stochastic_sampling 配置中选取,与 [StableAudio3Pipeline] 保持一致。
  • logsnr_min (float,默认为 -6.2) — 噪声调度的最小 log-SNR 值 — 对应调度中高噪声的起始点。
  • logsnr_max (float,默认为 2.0) — 噪声调度的最大 log-SNR 值 — 对应调度的低噪声端。
  • silence_padding_duration (float,默认为 0.0) — 目标内容之后的额外潜在余量。
  • num_waveforms_per_prompt (int,默认为 1) — 每个提示词生成的波形数量。
  • generator — 用于可复现性的随机数生成器。
  • latents — 预生成的起始噪声(None → 重新采样)。
  • prompt_embeds — 预计算文本嵌入。
  • encoder_attention_mask — 预计算嵌入的掩码。
  • return_dict (bool,默认为 True) — 返回 AudioPipelineOutput 或元组。
  • callback_on_step_end (Callable,可选) — 在每个去噪步骤结束时调用,参数为 (self, step_idx, timestep, callback_kwargs)。必须返回一个字典,其中包含用于循环剩余部分的(可选修改后的)张量。
  • callback_on_step_end_tensor_inputs (list[str],默认为 [“latents”]) — 传递给 callback_on_step_end 的张量。必须是 self._callback_tensor_inputs 的子集。
  • output_type(str,默认为 "pt")— "pt" / "np" / "latent"。

根据文本提示和参考波形生成音频变体。

示例:

>>> import torch
>>> import soundfile as sf
>>> import torchaudio
>>> from diffusers import StableAudio3AudioToAudioPipeline

>>> pipe = StableAudio3AudioToAudioPipeline.from_pretrained(
...     "stabilityai/stable-audio-3-medium", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> audio, sr = torchaudio.load("reference.wav")
>>> audio = torchaudio.functional.resample(audio, sr, pipe.vae.config.sampling_rate).unsqueeze(0).to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     audio=audio,
...     init_noise_level=0.6,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)

encode_duration

< >

( duration: floatdevice: devicenum_waveforms_per_prompt: intbatch_size: int )

参数

  • duration — 以秒为单位的时长,应用于批次中的每个样本。
  • device — 目标设备。
  • num_waveforms_per_prompt — 平铺因子。
  • batch_size — 提示词的数量。

将时长值嵌入到全局条件向量中。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str], NoneType]device: devicenum_waveforms_per_prompt: intprompt_embeds: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = None )

参数

  • prompt — 文本提示词或提示词列表。当提供 prompt_embeds 时将被忽略。
  • device — 目标设备。
  • num_waveforms_per_prompt — 每个提示词要生成的输出波形数量;条件张量会相应地进行平铺。
  • prompt_embeds — 预计算文本嵌入 (batch, seq_len, hidden_size)。
  • encoder_attention_mask — 用于预计算嵌入的布尔掩码,形状为 (batch, seq_len);1 表示真实 token,0 表示填充。

将文本提示编码为交叉注意力条件张量。

prepare_cross_attention

< >

( prompt_embeds: Tensorencoder_attention_mask: Tensorglobal_hidden_states: Tensor )

通过追加时长嵌入作为额外标记,构建交叉注意力上下文。

SA3 将 seconds_total 条件器路由到 两者:全局(AdaLN)输入和交叉注意力上下文(cross_attention_cond_ids = ["prompt", "seconds_total"])。时长嵌入拼接在文本 token 之后,注意力掩码也会扩展一个有效条目。

StableAudio3DurationEmbedder

class diffusers.StableAudio3DurationEmbedder

< >

( output_dim: int = 768fourier_dim: int = 256min_val: float = 0.0max_val: float = 384.0min_freq: float = 0.5max_freq: float = 10000.0 )

参数

  • output_dim (int,默认为 768) — 输出嵌入的维度。必须与 DiT 的 global_cond_dim 相匹配。
  • fourier_dim (int,默认为 256) — 内部傅里叶特征维度(必须为偶数)。
  • min_val (float,默认为 0.0) — 用于归一化截断的最小持续时间值。
  • max_val (float,默认值为 384.0) — 用于归一化截断的最大时长值。超过此值的数值将被截断。384 秒是 seconds_total 条件器在生产环境 SA3 Medium 中的上限。
  • min_freq (float,默认为 0.5) — 指数傅里叶基的最小频率。
  • max_freq (float,默认为 10000.0) — 指数傅里叶基的最大频率。

将时长值(以秒为单位)嵌入到 Stable Audio 3 DiT 的全局条件向量中(用作 global_hidden_states AdaLN 输入)。

复制 SA3 参考实现中的 NumberConditioner(fourier_features_type="expo")。

forward

< >

( seconds: Tensor )

参数

  • seconds(形状为 (batch,) 的 torch.Tensor)— 以秒为单位的时长值。
Update on GitHub