# LongCat-AudioDiT

LongCat-AudioDiT는 Meituan LongCat의 텍스트-오디오 확산 모델입니다. diffusers 통합은 텍스트 조건부 오디오 생성을 위한 표준 [DiffusionPipeline](/docs/diffusers/main/ko/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)

#### __호출__[[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 = ['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를 위한 negative prompt(s).

audio_duration_s (`float`, *선택 사항*) : 초 단위의 대상 오디오 길이. `latents`가 제공되면 무시됩니다.

latents (`torch.Tensor`, *선택 사항*) : `(batch_size, duration, latent_dim)` 형태의 사전 생성된 노이즈된 latents.

num_inference_steps (`int`, 기본값 16) : 디노이징 단계 수.

guidance_scale (`float`, 기본값 4.0) : classifier-free guidance의 guidance scale입니다.

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, step index, timestep, tensor 입력을 인자로 받아 각 denoising 단계의 끝에서 호출되는 함수입니다.

callback_on_step_end_tensor_inputs (`list`, 기본값은 `["latents"]`) : `callback_on_step_end`에 전달되는 Tensor 입력.

**반환값:** [AudioPipelineOutput](/docs/diffusers/main/ko/api/pipelines/audioldm2#diffusers.AudioPipelineOutput) 또는 `tuple`

`return_dict`가 True인 경우 [AudioPipelineOutput](/docs/diffusers/main/ko/api/pipelines/audioldm2#diffusers.AudioPipelineOutput), 그렇지 않으면 `tuple`입니다. 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/ko/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라는 파일이 포함되어야 합니다. - [Community](https://github.com/huggingface/diffusers/tree/main/examples/community) 아래 GitHub에 호스팅된 커뮤니티 파이프라인의 *파일 이름* 문자열. 유효한 파일 이름은 파이프라인 스크립트(`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`, *선택 사항*, 기본값 `False`) : 누락된 키, 예상치 못한 키 및 오류 메시지가 포함된 사전도 함께 반환할지 여부.

local_files_only (`bool`, *선택 사항*, 기본값 `False`) : 로컬 모델 가중치와 구성 파일만 로드할지 여부를 지정합니다. `True`로 설정하면 Hub에서 모델을 다운로드하지 않습니다.

token (`str` 또는 *bool*, *선택 사항*) : 원격 파일에 대한 HTTP bearer 인증으로 사용할 토큰입니다. `True`인 경우, `diffusers-cli login`에서 생성된 토큰(`~/.huggingface`에 저장됨)이 사용됩니다.

revision (`str`, *선택 사항*, 기본값 `"main"`) : 사용할 특정 모델 버전입니다. Git에서 허용하는 브랜치 이름, 태그 이름, 커밋 ID 또는 기타 식별자일 수 있습니다.

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 상태 사전의 가중치와 체크포인트의 가장 큰 샤드 합이 CPU RAM에 맞지 않을 때 CPU RAM 부족을 방지하기 위해 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 가중치가 사용 가능한 경우 해당 가중치가 다운로드됩니다. `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의 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
```

