# LongCat-AudioDiT

LongCat-AudioDiT は、Meituan LongCat によるテキストからオーディオを生成する拡散モデルです。diffusers への統合により、テキスト条件付きのオーディオ生成に対して標準的な [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) インターフェースが提供されます。

このパイプラインは、LongCat-AudioDiTの参照実装から適応されました: https://github.com/meituan-longcat/LongCat-AudioDiT

このパイプラインは、diffusers 形式（`text_encoder/`、`transformer/`、`vae/`、`tokenizer/`、`scheduler/` サブフォルダを含む）のローカルディレクトリまたは Hugging Face Hub リポジトリからの読み込みをサポートしています。

## 使用方法

```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/main/src/diffusers/pipelines/longcat_audio_dit/pipeline_longcat_audio_dit.py#L99)

#### __call__[[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/main/src/diffusers/pipelines/longcat_audio_dit/pipeline_longcat_audio_dit.py#L219)

**パラメータ:**

prompt (`str` または `list[str]`) : 音声生成をガイドするプロンプトまたはプロンプトのリスト。

negative_prompt (`str` または `list[str]`、*省略可*) : classifier-free guidance 用のネガティブプロンプト。

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`、*任意*) : `callback_on_step_end_tensor_inputs` で指定された pipeline、ステップインデックス、タイムステップ、テンソル入力を引数として、各デノイジングステップの終了時に呼び出される関数。

callback_on_step_end_tensor_inputs (`list`、デフォルトは `["latents"]`) : `callback_on_step_end` に渡される Tensor 入力。

**戻り値:** [AudioPipelineOutput](/docs/diffusers/main/ja/api/pipelines/audioldm2#diffusers.AudioPipelineOutput) または `tuple`

`return_dict` が True の場合は [AudioPipelineOutput](/docs/diffusers/main/ja/api/pipelines/audioldm2#diffusers.AudioPipelineOutput)、それ以外の場合は `tuple` を返します。タプルを返す場合、最初の要素は生成されたオーディオ波形です。

生成用のパイプラインを呼び出したときに実行される関数。

例:
```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/main/src/diffusers/pipelines/pipeline_utils.py#L638)

**パラメータ:**

pretrained_model_name_or_path (`str` または `os.PathLike`、*任意*) : 以下のいずれかです。 - Hub にホストされている事前学習済みパイプラインの *repo id*（例: `CompVis/ldm-text2im-large-256`）を表す文字列。 - [save_pretrained()](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline.save_pretrained) を使用して保存されたパイプラインの重みを格納した *ディレクトリ*（例: `./my_pipeline_directory/`）へのパス。

dtype (`torch.dtype` または `dict[str, Union[str, torch.dtype]]`、*省略可*) : デフォルトの `torch.dtype` を上書きし、別の dtype でモデルを読み込みます。異なる dtype でサブモデルを読み込む場合は、`dict` を渡します（例: `{'transformer': torch.bfloat16, 'vae': torch.float16}`）。指定されていないコンポーネントのデフォルト dtype は `default` で設定します（例: `{'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.py` ではなく `clip_guided_stable_diffusion`）。コミュニティパイプラインは、常に 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`, *optional*, デフォルトは `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`, *任意*) : 使用する特定のモデルバージョンです。Hubからカスタムパイプラインを読み込む場合の`revision`と同様に、ブランチ名、タグ名、またはコミットIDを指定できます。デフォルトでは、最新の安定版の🤗 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 RAM がデフォルトとして使用されます。

offload_folder (`str` または `os.PathLike`、*省略可能*) : `"disk"` が device_map に含まれる場合の、重みのオフロード先パス。

offload_state_dict (`bool`, *任意*) : `True`の場合、CPU state dictの重みとチェックポイントの最大のシャードの合計がCPU RAMに収まらない場合に、CPU RAMの枯渇を避けるため、CPU state dictを一時的にハードドライブにオフロードします。ディスクオフロードが存在する場合、デフォルトは`True`です。

low_cpu_mem_usage (`bool`、*任意*、torch のバージョンが 1.9.0 以上ならデフォルトは `True`、それ未満なら `False`) : 重みの初期化を行わず、事前学習済み重みのみを読み込むことでモデルの読み込みを高速化します。また、モデルの読み込み時に CPU メモリ（ピークメモリを含む）をモデルサイズの 1 倍以下に抑えるよう試みます。PyTorch 1.9.0 以上でのみサポートされています。PyTorch の古いバージョンを使用している場合、この引数を `True` に設定するとエラーが発生します。

use_safetensors (`bool`, *optional*, defaults to `None`) : If set to `None`, the safetensors weights are downloaded if they're available **and** if the safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors weights. If set to `False`, safetensors weights are not loaded.

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', *optional*, デフォルトは 'False') : Safetensors モデルの読み込み時に mmap を無効にするかどうかを指定します。モデルがネットワークマウントやハードドライブ上にあり、mmap のランダムアクセス（seek）を適切に処理できない可能性がある場合、このオプションを有効にするとパフォーマンスが向上することがあります。

事前学習済みのパイプライン重みから、PyTorchの拡散パイプラインをインスタンス化します。

パイプラインはデフォルトで評価モード(`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] > プライベートモデルや[gated](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
```

