# Allegro

来自 RhymesAI 的 [Allegro：打开商业级视频生成模型的黑盒](https://huggingface.co/papers/2410.15458)，作者为 Yuan Zhou、Qiuyue Wang、Yuxuan Cai、Huan Yang。

该论文的摘要如下：

*视频生成领域取得了显著进展，开源社区贡献了大量用于训练高质量模型的研究论文和工具。然而，尽管付出了这些努力，现有的信息和资源仍不足以实现商业级性能。在本报告中，我们揭开黑盒，介绍了 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/overview) 概述，以了解支持的量化后端以及如何选择支持您使用场景的量化后端。下面的示例演示了如何使用 bitsandbytes 加载用于推理的量化 [AllegroPipeline](/docs/diffusers/v0.43.0/zh/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/v0.43.0/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) 类的分词器。

transformer ([AllegroTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/allegro_transformer3d#diffusers.AllegroTransformer3DModel))：一个以文本为条件的 `AllegroTransformer3DModel`，用于对编码后的视频潜变量进行去噪。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `transformer` 配合，对编码后的视频潜变量进行去噪的调度器。

使用 Allegro 进行文本到视频生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[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/v0.43.0/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`，*可选*，默认为 1)：每个提示词生成的视频数量。

num_frames : (`int`，*可选*，默认值为 88)：该参数控制生成视频中的帧数。

height (`int`，*可选*，默认为 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/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，对其他调度器将被忽略。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 生成。可用于使用不同的提示词微调相同的生成过程。如果未提供，则将通过使用提供的随机`generator`进行采样，生成一个预生成的噪声潜变量张量（从高斯分布中采样），用作视频张量的输入。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_prompt_attention_mask (`torch.Tensor`, *可选*) : 为负文本嵌入预生成的注意力掩码。

output_type (`str`，*可选*，默认为 `"pil"`)：生成视频的输出格式。可选 [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/v0.43.0/zh/api/pipelines/allegro#diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [AllegroPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/allegro#diffusers.pipelines.allegro.pipeline_output.AllegroPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成视频的列表。

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

示例：
```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/v0.43.0/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`)：是否使用无分类器引导

num_videos_per_prompt (`int`，*可选*，默认为 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/v0.43.0/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 管道的输出类。

