#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。
-->

# EasyAnimate
阿里巴巴 PAI 的 [EasyAnimate](https://github.com/aigc-apps/EasyAnimate)。

其 GitHub 页面的描述：*EasyAnimate 是一个基于 transformer 架构的流水线，旨在生成 AI 图像和视频，并为 Diffusion Transformer 训练基线模型和 Lora 模型。我们支持直接从预训练的 EasyAnimate 模型进行预测，从而生成具有多种分辨率、时长约 6 秒、帧率为 8fps 的视频（EasyAnimateV5.1，1 到 49 帧）。此外，用户还可以针对特定的风格转换训练自己的基线模型和 Lora 模型。*

此流水线由 [bubbliiiing](https://github.com/bubbliiiing) 贡献。原始代码库可在[此处](https://huggingface.co/alibaba-pai)找到。原始权重可在 [hf.co/alibaba-pai](https://huggingface.co/alibaba-pai) 下找到。

EasyAnimate 有两个官方检查点，分别用于文本生成视频和视频生成视频。

| 检查点 | 推荐的推理数据类型 |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh) | torch.float16 |
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-InP`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-InP) | torch.float16 |

目前有一个官方的 EasyAnimate 检查点，可用于图像转视频和视频转视频。

| 检查点 | 推荐的推理数据类型 |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-InP`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-InP) | torch.float16 |

目前有两个官方的 EasyAnimate 检查点可用于控制到视频任务。

| 检查点 | 推荐的推理数据类型 |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-Control`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-Control) | torch.float16 |
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-Control-Camera`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-Control-Camera) | torch.float16 |

对于 EasyAnimateV5.1 系列：
- 文本到视频（T2V）和图像到视频（I2V）支持多种分辨率。宽度和高度可在 256 到 1024 之间变化。
- T2V 和 I2V 模型均支持生成 1~49 帧的视频，且在该帧数范围内效果最佳。建议以 8 FPS 导出视频。

## 量化

量化通过以较低精度的数据类型存储模型权重，有助于降低超大模型的内存需求。不过，量化对视频质量的影响会因视频模型的不同而有所差异。

请参阅 [量化](../../quantization/overview) 概述，以了解支持的量化后端以及如何选择支持您使用场景的量化后端。以下示例演示了如何使用 bitsandbytes 加载量化的 [EasyAnimatePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/easyanimate#diffusers.EasyAnimatePipeline) 进行推理。

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, EasyAnimateTransformer3DModel, EasyAnimatePipeline
from diffusers.utils import export_to_video

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = EasyAnimateTransformer3DModel.from_pretrained(
    "alibaba-pai/EasyAnimateV5.1-12b-zh",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = EasyAnimatePipeline.from_pretrained(
    "alibaba-pai/EasyAnimateV5.1-12b-zh",
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = "A cat walks on the grass, realistic style."
negative_prompt = "bad detailed"
video = pipeline(prompt=prompt, negative_prompt=negative_prompt, num_frames=49, num_inference_steps=30).frames[0]
export_to_video(video, "cat.mp4", fps=8)
```

## EasyAnimatePipeline[[diffusers.EasyAnimatePipeline]]

#### diffusers.EasyAnimatePipeline[[diffusers.EasyAnimatePipeline]]

```python
diffusers.EasyAnimatePipeline(vae: AutoencoderKLMagvit, text_encoder: transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLForConditionalGeneration | transformers.models.bert.modeling_bert.BertModel, tokenizer: transformers.models.qwen2.tokenization_qwen2.Qwen2Tokenizer | transformers.models.bert.tokenization_bert.BertTokenizer, transformer: EasyAnimateTransformer3DModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L186)

**参数：**

vae ([AutoencoderKLMagvit](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_magvit#diffusers.AutoencoderKLMagvit))：一种变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

text_encoder (`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel` | None) : EasyAnimate 在 V5.1 中使用 [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct)。

tokenizer (`~transformers.Qwen2Tokenizer`、`~transformers.BertTokenizer` | None)：用于对文本进行分词的 `Qwen2Tokenizer` 或 `BertTokenizer`。

transformer ([EasyAnimateTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/easyanimate_transformer3d#diffusers.EasyAnimateTransformer3DModel))：由 EasyAnimate Team 设计的 EasyAnimate 模型。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 EasyAnimate 配合，对编码后的图像潜变量进行去噪的调度器。

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

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

EasyAnimate 在 V5.1 中使用了一个文本编码器 [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct)。

#### __调用__[[diffusers.EasyAnimatePipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, num_frames: int | None = 49, height: int | None = 512, width: int | None = 512, num_inference_steps: int | None = 50, guidance_scale: float | None = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 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, timesteps: list[int] | None = 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, 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'], guidance_rescale: float = 0.0)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L524)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像或视频生成的文本提示。如果未提供，则改用 `prompt_embeds`。

num_frames (`int`, *可选*) : 生成视频的长度（以帧为单位）。

height (`int`，*可选*)：生成图像的高度（以像素为单位）。

width (`int`, *可选*) : 生成图像的宽度（以像素为单位）。

num_inference_steps (`int`, *可选*，默认为 50)：生成过程中的去噪步数。步数越多，生成的图像质量通常越高，但推理速度会变慢。

guidance_scale (`float`，*可选*，默认值为 5.0)：鼓励模型使输出与提示词保持一致。较高的值可能会降低图像质量。

negative_prompt (`str` 或 `list[str]`，*可选*)：指示在生成过程中需要排除的内容的提示。如果未指定，则使用 `negative_prompt_embeds`。

num_images_per_prompt (`int`，*可选*，默认为 1)：为每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：适用于 DDIM 调度。由相关文献中的 eta 参数控制。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于确保图像生成可复现性的生成器。

latents (`torch.Tensor`, *可选*) : 用于条件生成的预定义潜在张量。

prompt_embeds (`torch.Tensor`, *可选*) : 提示词的文本嵌入。用于替代提示词字符串输入，以提供更强的灵活性。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 负向提示词的嵌入。如果已定义，将覆盖字符串输入。

prompt_attention_mask (`torch.Tensor`, *可选*) : 主提示嵌入的注意力掩码。

negative_prompt_attention_mask (`torch.Tensor`, *可选*) : 用于负提示嵌入的注意力掩码。

output_type (`str`，*可选*，默认为 "latent")：生成输出的格式，可以是 PIL 图像，也可以是 NumPy 数组。

return_dict (`bool`，*可选*，默认为 `True`)：如果为 `True`，则返回结构化输出。否则返回一个简单的元组。

callback_on_step_end (`Callable`，*可选*)：在每个去噪步骤结束时调用的函数。

callback_on_step_end_tensor_inputs (`list[str]`，*可选*)：要包含在回调函数调用中的张量名称。

guidance_rescale (`float`，*可选*，默认值为 0.0)：根据 guidance scale 调整噪声水平。

timesteps (`list[int]`，*可选*) : 用于去噪过程的自定义时间步。如果未定义，则使用调度器针对 `num_inference_steps` 的默认调度。

**返回：** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

根据提供的提示词，使用 EasyAnimate 流水线生成图像或视频。

示例：
```python
>>> import torch
>>> from diffusers import EasyAnimatePipeline
>>> from diffusers.utils import export_to_video

>>> # Models: "alibaba-pai/EasyAnimateV5.1-12b-zh"
>>> pipe = EasyAnimatePipeline.from_pretrained(
...     "alibaba-pai/EasyAnimateV5.1-7b-zh-diffusers", torch_dtype=torch.float16
... ).to("cuda")
>>> prompt = (
...     "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
...     "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
...     "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
...     "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
...     "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
...     "atmosphere of this unique musical performance."
... )
>>> sample_size = (512, 512)
>>> video = pipe(
...     prompt=prompt,
...     guidance_scale=6,
...     negative_prompt="bad detailed",
...     height=sample_size[0],
...     width=sample_size[1],
...     num_inference_steps=50,
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=8)
```

#### encode_prompt[[diffusers.EasyAnimatePipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = 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, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None, max_sequence_length: int = 256)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L241)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

device : (`torch.device`): torch 设备

dtype (`torch.dtype`)：torch 数据类型

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

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

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

prompt_attention_mask (`torch.Tensor`, *可选*) : 提示词的注意力掩码。当直接传入 `prompt_embeds` 时，此项为必填。

negative_prompt_attention_mask (`torch.Tensor`，*可选*)：用于负面提示词的注意力掩码。当直接传入 `negative_prompt_embeds` 时，此参数为必填项。

max_sequence_length (`int`, *可选*) : 用于提示词的最大序列长度。

将提示词编码为文本编码器的隐藏状态。

## EasyAnimatePipelineOutput[[diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput]]

#### diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput[[diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput]]

```python
diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput(frames: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_output.py#L9)

**参数：**

frames (`torch.Tensor`、`np.ndarray` 或 list[list[PIL.Image.Image]]) : 视频输出列表 - 它可以是一个长度为 `batch_size,` 的嵌套列表，其中每个子列表包含长度为 `num_frames.` 的去噪 PIL 图像序列。它也可以是一个形状为 `(batch_size, num_frames, channels, height, width)` 的 NumPy 数组或 Torch 张量。

EasyAnimate 管线的输出类。

