# 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]
> スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、[ガイド](../../using-diffusers/schedulers)を必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、[パイプライン間でコンポーネントを再利用する](../../using-diffusers/loading#reusing-models-in-multiple-pipelines)セクションを参照してください。

## 量子化

Quantizationは、モデルの重みを低精度のデータ型で保存することで、非常に大規模なモデルのメモリ要件を軽減するのに役立ちます。ただし、動画モデルによって、Quantizationが動画の品質に与える影響は異なります。

サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択について詳しくは、[Quantization](../../quantization/overview)の概要を参照してください。以下の例では、bitsandbytesを使用して量子化された[AllegroPipeline](/docs/diffusers/main/ja/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`) : 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（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) の Tokenizer。

transformer ([AllegroTransformer3DModel](/docs/diffusers/main/ja/api/models/allegro_transformer3d#diffusers.AllegroTransformer3DModel)) : テキスト条件付きの`AllegroTransformer3DModel`で、エンコードされた動画の潜在変数からノイズを除去します。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `transformer` と組み合わせて、エンコードされた動画の潜在変数（latents）のノイズ除去に使用するスケジューラ。

Allegro を使用したテキストから動画への生成を行う Pipeline です。

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。ライブラリがすべてのパイプラインに対して実装している汎用的なメソッド（ダウンロードや保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 100, timesteps: list[int] = 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[str] = ['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]`、*任意*) : デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、等間隔の`num_inference_steps`個のタイムステップが使用されます。降順で指定する必要があります。

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`、*optional*、デフォルトは 1) : プロンプトごとに生成する動画の数を指定します。

num_frames : (`int`、*optional*、デフォルトは 88): 生成される動画のフレーム数を制御します。

height (`int`、*optional*、デフォルトは self.unet.config.sample_size) : 生成される動画のピクセル単位の縦幅。

width (`int`、*任意*、デフォルトは self.unet.config.sample_size) : 生成される動画のピクセル単位の幅。

eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。

latents (`torch.Tensor`, *optional*) : 生成。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムな`generator`を使用してサンプリングを行い、動画テンソルの入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数テンソルが生成されます。

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

prompt_attention_mask (`torch.Tensor`, *任意*) : テキスト埋め込み用の事前生成されたアテンションマスク。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブテキスト埋め込み。PixArt-Sigma の場合、このネガティブプロンプトは "" である必要があります。指定されない場合、`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/ja/api/pipelines/allegro#diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput) または `tuple`

`return_dict` が `True` の場合、[AllegroPipelineOutput](/docs/diffusers/main/ja/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`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数

device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス

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 パイプライン用の出力クラスです。

