Diffusers documentation
LongCat-AudioDiT
LongCat-AudioDiT
LongCat-AudioDiT 是美团 LongCat 推出的文本生成音频扩散模型。diffusers 集成提供了标准的 DiffusionPipeline 接口,用于基于文本条件的音频生成。
此流水线改编自 LongCat-AudioDiT 参考实现:https://github.com/meituan-longcat/LongCat-AudioDiT
此流水线支持从本地目录或 Hugging Face Hub 仓库加载 diffusers 格式(包含 text_encoder/、transformer/、vae/、tokenizer/ 和 scheduler/ 子文件夹)的模型。
用法
import soundfile as sf
import torch
from diffusers import LongCatAudioDiTPipeline
pipeline = LongCatAudioDiTPipeline.from_pretrained(
"ruixiangma/LongCat-AudioDiT-1B-Diffusers",
dtype=torch.float16,
)
pipeline = pipeline.to("cuda") # or "mps", "xpu", "cpu"
prompt = "A calm ocean wave ambience with soft wind in the background."
audio = pipeline(
prompt,
audio_duration_s=5.0,
num_inference_steps=16,
guidance_scale=4.0,
generator=torch.Generator("cuda").manual_seed(42),
).audios[0, 0]
sf.write("longcat.wav", audio, pipeline.sample_rate)提示
audio_duration_s是控制输出时长的最直接方式。- 使用
generator=torch.Generator("cuda").manual_seed(42)可使生成过程可复现。 - 输出形状为
(batch, channels, samples)- 使用.audios[0, 0]可获取单个音频样本。 - Pipeline 输出单声道音频(1 个通道)。如果需要立体声,可以复制该通道:
audio.unsqueeze(0).repeat(1, 2, 1)。
LongCatAudioDiTPipeline
class diffusers.LongCatAudioDiTPipeline
< source >( vae: LongCatAudioDiTVaetext_encoder: UMT5EncoderModeltokenizer: PreTrainedTokenizerBasetransformer: LongCatAudioDiTTransformerscheduler: diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler | None = None )
__call__
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Noneaudio_duration_s: float | None = Nonelatents: typing.Optional[torch.Tensor] = Nonenum_inference_steps: int = 16guidance_scale: float = 4.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str = 'np'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → AudioPipelineOutput or tuple
参数
- prompt (
str或list[str]) — 用于引导音频生成的提示词或提示词列表。 - negative_prompt (
str或list[str],可选) — 用于无分类器引导的负面提示词。 - audio_duration_s (
float, 可选) — 目标音频时长(以秒为单位)。当提供latents时,此参数将被忽略。 - latents (
torch.Tensor, 可选) — 预生成的噪声潜变量,形状为(batch_size, duration, latent_dim)。 - num_inference_steps (
int,默认为 16) — 去噪步数。 - guidance_scale (
float,默认为 4.0) — 无分类器引导(classifier-free guidance)的引导尺度。 - generator(
torch.Generator或list[torch.Generator],可选)— 随机数生成器。 - output_type(
str,默认为"np")— 输出格式:"np"、"pt"或"latent"。 - return_dict (
bool,默认为True) — 是否返回AudioPipelineOutput。 - callback_on_step_end (
Callable, 可选) — 在每个去噪步骤结束时调用的函数,其参数包括 pipeline、步骤索引、timestep,以及由callback_on_step_end_tensor_inputs指定的张量输入。 - callback_on_step_end_tensor_inputs(
list,默认为["latents"])— 传递给callback_on_step_end的张量输入。
返回值
AudioPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 AudioPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是生成的音频波形。
调用生成 pipeline 时调用的函数。
示例:
>>> import soundfile as sf
>>> import torch
>>> from diffusers import LongCatAudioDiTPipeline
>>> pipe = LongCatAudioDiTPipeline.from_pretrained("ruixiangma/LongCat-AudioDiT-1B-Diffusers")
>>> pipe.to("cuda")
>>> prompt = "A calm ocean wave ambience with soft wind in the background."
>>> audio = pipe(
... prompt,
... audio_duration_s=5.0,
... num_inference_steps=20,
... guidance_scale=4.0,
... generator=torch.Generator("cuda").manual_seed(42),
... ).audios[0, 0]
>>> sf.write("output.wav", audio, pipe.sample_rate)from_pretrained
< source >( pretrained_model_name_or_path: str | os.PathLike**kwargs )
参数
- pretrained_model_name_or_path (
str或os.PathLike, 可选) — 可以是以下之一: Hub 上托管的预训练管道的仓库 ID(例如 CompVis/ldm-text2im-large-256)。 一个目录的路径(例如 ./my_pipeline_directory/),其中包含使用 save_pretrained() 保存的管道权重。- 一个字符串,即托管在 Hub 上的预训练流水线的 repo id(例如
CompVis/ldm-text2im-large-256)。 - 指向一个 目录(例如
./my_pipeline_directory/)的路径,该目录包含使用 save_pretrained() 保存的流水线权重。
- 一个字符串,即托管在 Hub 上的预训练流水线的 repo id(例如
- dtype (
torch.dtype或dict[str, Union[str, torch.dtype]],可选) — 覆盖默认的torch.dtype,并使用其他 dtype 加载模型。若要为不同的子模型加载不同的 dtype,请传入一个dict(例如{'transformer': torch.bfloat16, 'vae': torch.float16})。使用default为未指定的组件设置默认 dtype(例如{'transformer': torch.bfloat16, 'default': torch.float16})。如果某个组件未指定且未设置默认值,则使用torch.float32。 - custom_pipeline (
str, 可选) —> 🧪 这是一个实验性功能,未来可能会发生变化。
可以是以下之一:
- 一个字符串,即托管在 Hub 上的自定义流水线的 repo id(例如
hf-internal-testing/diffusers-dummy-pipeline)。该仓库必须包含一个名为 pipeline.py 的文件,用于定义该自定义流水线。 - 一个字符串,表示托管在 GitHub 上 Community 下的社区流水线的文件名。有效的文件名必须与文件名匹配,而不是流水线脚本(应为
clip_guided_stable_diffusion,而非clip_guided_stable_diffusion.py)。社区流水线始终从 GitHub 的当前 main 分支加载。 - 指向包含自定义 pipeline 的目录的路径(
./my_pipeline_directory/)。该目录必须包含一个名为pipeline.py的文件,用于定义该自定义 pipeline。
有关如何加载和创建自定义管道的更多信息,请参阅加载和添加自定义管道
- 一个字符串,即托管在 Hub 上的自定义流水线的 repo id(例如
- force_download (
bool,可选,默认为False) — 是否强制(重新)下载模型权重和配置文件,如果存在缓存版本则覆盖它们。 - cache_dir (
Union[str, os.PathLike], 可选) — 如果未使用标准缓存,则用于缓存已下载的预训练模型配置的目录路径。 - proxies (
Dict[str, str],可选) — 按协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。每次请求都会使用这些代理。 - output_loading_info(
bool, 可选,默认为False) — 是否同时返回一个包含缺失键、意外键和错误消息的字典。 - local_files_only (
bool,可选,默认为False) — 是否仅加载本地的模型权重和配置文件。如果设置为True,则不会从 Hub 下载模型。 - token (
str或 bool,可选) — 用于远程文件的 HTTP bearer 授权令牌。如果为True,则使用由diffusers-cli login生成的令牌(存储在~/.huggingface中)。 - revision (
str, 可选, 默认为"main") — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 id,或 Git 允许的任何标识符。 - custom_revision (
str, 可选) — 要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID,类似于从 Hub 加载自定义流水线时的revision。默认使用最新的稳定版 🤗 Diffusers 版本。 - mirror (
str, 可选) — 镜像源,用于解决在中国下载模型时可能遇到的访问问题。我们不保证该源的时效性或安全性,详情请参阅镜像站点。 - device_map (
str, 可选) — 指定流水线各组件应如何放置在可用设备上的策略。目前仅支持“balanced”device_map。有关更多信息,请参阅 此处。 - max_memory (
Dict, 可选) — 用于指定最大内存的设备标识符字典。如果未设置,则默认为每个 GPU 的最大可用内存以及可用的 CPU 内存。 - offload_folder (
str或os.PathLike,可选) — 如果 device_map 包含值"disk",则用于卸载权重的路径。 - offload_state_dict (
bool, 可选) — 如果为True,则临时将 CPU 状态字典卸载到硬盘,以避免在 CPU 状态字典的权重加上检查点中最大的分片无法容纳时耗尽 CPU 内存。当存在磁盘卸载时,默认值为True。 - low_cpu_mem_usage (
bool,可选,如果 torch 版本 >= 1.9.0 则默认为True,否则为False) — 通过仅加载预训练权重而不初始化权重来加速模型加载。在加载模型时,这也试图将 CPU 内存(包括峰值内存)的使用量控制在不超过 1 倍模型大小。仅支持 PyTorch >= 1.9.0。如果您使用的是旧版本的 PyTorch,将此参数设置为True将引发错误。 - use_safetensors (
bool,可选,默认为None) — 如果设置为None,则在 safetensors 权重可用且已安装 safetensors 库的情况下,会下载 safetensors 权重。如果设置为True,则强制从 safetensors 权重加载模型。如果设置为False,则不加载 safetensors 权重。 - use_onnx (
bool,可选,默认为None) — 如果设置为True,只要存在 ONNX 权重,就始终会下载它们。如果设置为False,则永远不会下载 ONNX 权重。默认情况下,use_onnx的默认值为_is_onnx类属性,对于非 ONNX 流水线,该属性为False;对于 ONNX 流水线,该属性为True。ONNX 权重包括以.onnx和.pb结尾的两种文件。 - kwargs(其余关键字参数字典,可选) —
可用于覆盖加载和可保存变量(特定流水线类的流水线组件)。被覆盖的组件会直接传递给流水线的
__init__方法。更多信息请参见下方示例。 - variant (
str, 可选) — 从指定的变体文件名(例如"fp16"或"ema")加载权重。 - disable_mmap('bool',可选,默认为 'False')— 是否在加载 Safetensors 模型时禁用 mmap。当模型位于网络挂载或硬盘上时,此选项可能表现更佳,因为这些存储设备可能无法很好地处理 mmap 的频繁寻址操作。
从预训练流水线权重实例化一个 PyTorch 扩散流水线。
默认情况下,pipeline 会设置为评估模式(model.eval())。
如果出现以下错误消息,您需要针对下游任务微调权重:
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.> 若要使用私有或 受限 模型,请使用
hf > auth login登录。
示例:
>>> from diffusers import DiffusionPipeline
>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")
>>> # Download pipeline that requires an authorization token
>>> # For more information on access tokens, please refer to this section
>>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
>>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> # Use a different scheduler
>>> from diffusers import LMSDiscreteScheduler
>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.scheduler = scheduler