# LongCat-AudioDiT

LongCat-AudioDiT 是美团 LongCat 推出的文本生成音频扩散模型。diffusers 集成提供了标准的 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline) 接口，用于基于文本条件的音频生成。

此流水线改编自 LongCat-AudioDiT 参考实现：https://github.com/meituan-longcat/LongCat-AudioDiT

此流水线支持从本地目录或 Hugging Face Hub 仓库加载 diffusers 格式（包含 `text_encoder/`、`transformer/`、`vae/`、`tokenizer/` 和 `scheduler/` 子文件夹）的模型。

## 用法

```py
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[[diffusers.LongCatAudioDiTPipeline]]

#### diffusers.LongCatAudioDiTPipeline[[diffusers.LongCatAudioDiTPipeline]]

```python
diffusers.LongCatAudioDiTPipeline(vae: LongCatAudioDiTVae, text_encoder: UMT5EncoderModel, tokenizer: PreTrainedTokenizerBase, transformer: LongCatAudioDiTTransformer, scheduler: diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/longcat_audio_dit/pipeline_longcat_audio_dit.py#L99)

#### __调用__[[diffusers.LongCatAudioDiTPipeline.__call__]]

```python
__call__(prompt: str | list[str], negative_prompt: str | list[str] | None = None, audio_duration_s: float | None = None, latents: typing.Optional[torch.Tensor] = None, num_inference_steps: int = 16, guidance_scale: float = 4.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str = 'np', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/longcat_audio_dit/pipeline_longcat_audio_dit.py#L219)

**参数：**

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)：用于无分类器引导的引导比例。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：随机数生成器。

output_type (`str`，默认为 `"np"`)：输出格式：`"np"`、`"pt"` 或 `"latent"`。

return_dict (`bool`，默认为 `True`)：是否返回 `AudioPipelineOutput`。

callback_on_step_end (`Callable`，*可选*)：一个在每次去噪步骤结束时调用的函数，其参数包括 pipeline、步骤索引、时间步以及由 `callback_on_step_end_tensor_inputs` 指定的张量输入。

callback_on_step_end_tensor_inputs (`list`，默认为 `["latents"]`)：传递给 `callback_on_step_end` 的 Tensor 输入。

**返回：** [AudioPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/audioldm2#diffusers.AudioPipelineOutput) 或 `tuple`

如果 `return_dict` 为 True，则返回 [AudioPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/audioldm2#diffusers.AudioPipelineOutput)，否则返回 `tuple`。当返回元组时，第一个元素是生成的音频波形。

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

示例：
```py
>>> 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[[diffusers.LongCatAudioDiTPipeline.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L638)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`，*可选*) : 可以是以下之一： - 一个字符串，即托管在 Hub 上的预训练流水线的 *repo id*（例如 `CompVis/ldm-text2im-large-256`）。 - 一个指向 *目录* 的路径（例如 `./my_pipeline_directory/`），其中包含使用 [save_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.save_pretrained) 保存的流水线权重。

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`, *可选*) : > [!WARNING] > 🧪 这是一个实验性功能，未来可能会发生变化。 可以是以下之一： - 一个字符串，即托管在 Hub 上的自定义流水线的 *repo id*（例如 `hf-internal-testing/diffusers-dummy-pipeline`）。该仓库必须包含一个名为 pipeline.py 的文件，用于定义自定义流水线。 - 一个字符串，即托管在 GitHub [Community](https://github.com/huggingface/diffusers/tree/main/examples/community) 下的社区流水线的 *文件名*。有效的文件名必须与文件名匹配，而不是流水线脚本（使用 `clip_guided_stable_diffusion` 而不是 `clip_guided_stable_diffusion.py`）。社区流水线始终从 GitHub 的当前 main 分支加载。 - 指向包含自定义流水线的目录的路径（`./my_pipeline_directory/`）。该目录必须包含一个名为 `pipeline.py` 的文件，用于定义自定义流水线。 有关如何加载和创建自定义流水线的更多信息，请参阅 [加载和添加自定义流水线](https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview)

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 承载者授权令牌。如果为 `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`。有关更多信息，请参阅 [此处](https://huggingface.co/docs/diffusers/main/en/tutorials/inference_with_big_models#device-placement)。

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 （其余关键字参数字典，*可选*）：可用于覆盖加载和可保存的变量（特定 pipeline 类的 pipeline 组件）。被覆盖的组件会直接传递给 pipeline 的 `__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.
```

> [!TIP] > 若要使用私有或 [受限](https://huggingface.co/docs/hub/models-gated#gated-models) 模型，请先登录
使用 `hf > auth login`。

示例：

```py
>>> 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
```

