# Allegro

RhymesAI의 Yuan Zhou, Qiuyue Wang, Yuxuan Cai, Huan Yang의 [Allegro: Open the Black Box of Commercial-Level Video Generation Model](https://huggingface.co/papers/2410.15458)

해당 논문의 초록은 다음과 같습니다:

*비디오 생성 분야에서 상당한 발전이 이루어졌으며, 오픈소스 커뮤니티는 고품질 모델 훈련을 위한 다수의 연구 논문과 도구를 기여했습니다. 그러나 이러한 노력에도 불구하고, 상업 수준의 성능을 달성하기에는 현재 이용 가능한 정보와 자원이 여전히 부족합니다. 이 보고서에서는 블랙박스를 열어, 품질과 시간적 일관성 모두에서 뛰어난 고급 비디오 생성 모델인 Allegro를 소개합니다. 또한 해당 분야의 현재 한계를 강조하고, 데이터, 모델 아키텍처, 훈련 파이프라인, 평가와 같은 핵심 요소를 다루며 고성능 상업 수준의 비디오 생성 모델을 훈련하기 위한 포괄적인 방법론을 제시합니다. 사용자 연구 결과에 따르면, Allegro는 기존 오픈소스 모델과 대부분의 상업 모델을 능가하며, Hailuo와 Kling에 이어 그 뒤를 잇는 순위를 기록했습니다. 코드: https://github.com/rhymes-ai/Allegro , 모델: https://huggingface.co/rhymes-ai/Allegro , 갤러리: https://rhymes.ai/allegro_gallery .*

> [!TIP]
> Scheduler의 [가이드](../../using-diffusers/schedulers)를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, [파이프라인 간 구성 요소 재사용](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

## 양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 [Quantization](../../quantization/overview) 개요를 참조하세요. 아래 예제는 bitsandbytes를 사용하여 추론을 위해 양자화된 [AllegroPipeline](/docs/diffusers/main/ko/api/pipelines/allegro#diffusers.AllegroPipeline)을 로드하는 방법을 보여줍니다.

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, AllegroTransformer3DModel, AllegroPipeline
from diffusers.utils import export_to_video
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
    "rhymes-ai/Allegro",
    subfolder="text_encoder",
    quantization_config=quant_config,
    dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = AllegroTransformer3DModel.from_pretrained(
    "rhymes-ai/Allegro",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = AllegroPipeline.from_pretrained(
    "rhymes-ai/Allegro",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = (
    "A seaside harbor with bright sunlight and sparkling seawater, with many boats in the water. From an aerial view, "
    "the boats vary in size and color, some moving and some stationary. Fishing boats in the water suggest that this "
    "location might be a popular spot for docking fishing boats."
)
video = pipeline(prompt, guidance_scale=7.5, max_sequence_length=512).frames[0]
export_to_video(video, "harbor.mp4", fps=15)
```

## AllegroPipeline[[diffusers.AllegroPipeline]]

#### diffusers.AllegroPipeline[[diffusers.AllegroPipeline]]

```python
diffusers.AllegroPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, vae: AutoencoderKLAllegro, transformer: AllegroTransformer3DModel, scheduler: KarrasDiffusionSchedulers)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/allegro/pipeline_allegro.py#L144)

**매개변수:**

vae (`AllegroAutoEncoderKL3D`) : 비디오를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (`T5EncoderModel`) : 고정된 텍스트 인코더입니다. PixArt-Alpha는 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) 변형을 사용합니다.

tokenizer (`T5Tokenizer`) : [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer) 클래스의 토크나이저.

transformer ([AllegroTransformer3DModel](/docs/diffusers/main/ko/api/models/allegro_transformer3d#diffusers.AllegroTransformer3DModel)) : 인코딩된 비디오 latents의 노이즈를 제거하기 위한 텍스트 조건부 `AllegroTransformer3DModel`입니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `transformer`와 함께 사용되어 인코딩된 비디오 latents의 노이즈를 제거하는 스케줄러입니다.

Allegro를 사용한 텍스트-비디오 생성을 위한 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

#### __호출__[[diffusers.AllegroPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 100, timesteps: list = None, guidance_scale: float = 7.5, num_frames: int | None = None, height: int | None = None, width: int | None = None, num_videos_per_prompt: int = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], clean_caption: bool = True, max_sequence_length: int = 512)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/allegro/pipeline_allegro.py#L665)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 비디오 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 비디오 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

num_inference_steps (`int`, *선택 사항*, 기본값 100) : 디노이징 단계의 수입니다. 디노이징 단계를 늘리면 일반적으로 더 높은 품질의 비디오를 얻을 수 있지만, 추론 속도가 느려집니다.

timesteps (`list[int]`, *선택 사항*) : 노이즈 제거 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, 균등 간격의 `num_inference_steps` timesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)에서 정의한 가이던스 스케일입니다. `guidance_scale`은 [Imagen Paper](https://huggingface.co/papers/2205.11487)의 2번 식의 `w`로 정의됩니다. `guidance_scale > 1`을 설정하여 가이던스 스케일을 활성화합니다. 가이던스 스케일이 높을수록 텍스트 `prompt`와 밀접하게 연결된 비디오를 생성하도록 장려하지만, 일반적으로 비디오 품질이 낮아지는 대가를 치릅니다.

num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수입니다.

num_frames : (`int`, *선택 사항*, 기본값 88): 생성된 비디오 프레임 수를 제어합니다.

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size) : 생성된 비디오의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size) : 생성된 비디오의 픽셀 단위 너비입니다.

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

generator (`torch.Generator` 또는 `list[torch.Generator]`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.Tensor`, *선택 사항*) : 생성. 서로 다른 프롬프트를 사용하여 동일한 생성을 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 생성된 비디오 텐서 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents 텐서가 생성됩니다.

prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.

negative_prompt_embeds (`torch.Tensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 부정 텍스트 임베딩에 사용할 사전 생성된 어텐션 마스크입니다.

output_type (`str`, *선택 사항*, 기본값 `"pil"`) : generate video의 출력 형식입니다. [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` 또는 `np.array` 중 하나를 선택합니다.

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `~pipelines.stable_diffusion.IFPipelineOutput`를 반환할지 여부.

callback_on_step_end (`Callable`, *선택 사항*) : 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`에는 `callback_on_step_end_tensor_inputs`로 지정된 모든 텐서 목록이 포함됩니다.

callback_on_step_end_tensor_inputs (`List`, *선택 사항*) : `callback_on_step_end` 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 `callback_kwargs` 인수로 전달됩니다. 파이프라인 클래스의 `._callback_tensor_inputs` 속성에 나열된 변수만 포함할 수 있습니다.

clean_caption (`bool`, *선택 사항*, 기본값 `True`) : 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. `beautifulsoup4`와 `ftfy`가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.

max_sequence_length (`int` 기본값은 `512`) : `prompt`에 사용할 최대 시퀀스 길이.

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

`return_dict`가 `True`인 경우 [AllegroPipelineOutput](/docs/diffusers/main/ko/api/pipelines/allegro#diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput)가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 비디오 목록인 `tuple`이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:
```py
>>> import torch
>>> from diffusers import AutoencoderKLAllegro, AllegroPipeline
>>> from diffusers.utils import export_to_video

>>> vae = AutoencoderKLAllegro.from_pretrained("rhymes-ai/Allegro", subfolder="vae", torch_dtype=torch.float32)
>>> pipe = AllegroPipeline.from_pretrained("rhymes-ai/Allegro", vae=vae, torch_dtype=torch.bfloat16).to("cuda")
>>> pipe.vae.enable_tiling()

>>> prompt = (
...     "A seaside harbor with bright sunlight and sparkling seawater, with many boats in the water. From an aerial view, "
...     "the boats vary in size and color, some moving and some stationary. Fishing boats in the water suggest that this "
...     "location might be a popular spot for docking fishing boats."
... )
>>> video = pipe(prompt, guidance_scale=7.5, max_sequence_length=512).frames[0]
>>> export_to_video(video, "output.mp4", fps=15)
```

#### encode_prompt[[diffusers.AllegroPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_videos_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 512, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/allegro/pipeline_allegro.py#L215)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트

negative_prompt (`str` 또는 `list[str]`, *선택*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됨). PixArt-Alpha의 경우 ""여야 합니다.

do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부

num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 이미지 수

device : (`torch.device`, *선택 사항*): 생성된 임베딩을 배치할 torch device

prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩. PixArt-Alpha의 경우, "" 문자열의 임베딩이어야 합니다.

clean_caption (`bool`, 기본값은 `False`) : `True`인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.

max_sequence_length (`int`, 기본값 512) : 프롬프트에 사용할 최대 시퀀스 길이입니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

## AllegroPipelineOutput[[diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput]]

#### diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput[[diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput]]

```python
diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput(frames: typing.Union[torch.Tensor, numpy.ndarray, list[list[PIL.Image.Image]]])
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/allegro/pipeline_output.py#L11)

**매개변수:**

frames (`torch.Tensor`, `np.ndarray`, 또는 list[list[PIL.Image.Image]]) : 비디오 출력 목록 - `batch_size,` 길이의 중첩 목록일 수 있으며, 각 하위 목록에는 `num_frames.` 길이의 노이즈 제거된 PIL 이미지 시퀀스가 포함됩니다. 또한 `(batch_size, num_frames, channels, height, width)` 형상의 NumPy 배열 또는 Torch 텐서일 수도 있습니다.

Allegro 파이프라인의 출력 클래스입니다.

