#
# Được cấp phép theo Giấy phép Apache, Phiên bản 2.0 (gọi là "Giấy phép");
# bạn có thể không sử dụng tệp này ngoại trừ tuân thủ theo Giấy phép.
# Bạn có thể nhận được một bản sao của Giấy phép tại
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Trừ khi được yêu cầu bởi luật pháp có hiệu lực hoặc được thỏa thuận bằng văn bản, phần mềm
# được phân phối theo Giấy phép được phân phối trên cơ sở
# KHÔNG CÓ BẢO HÀNH HOẶC ĐIỀU KIỆN DƯỚI BẤT KỲ HÌNH THỨC NÀO, dù được nêu rõ hay ngụ ý.
# Xem Giấy phép để biết ngôn ngữ cụ thể điều chỉnh các quyền và
# các hạn chế theo Giấy phép.
-->

# EasyAnimate
[EasyAnimate](https://github.com/aigc-apps/EasyAnimate) của Alibaba PAI.

Mô tả từ trang GitHub của nó: *EasyAnimate là một pipeline dựa trên kiến trúc transformer, được thiết kế để tạo ảnh và video AI, cũng như để huấn luyện các mô hình baseline và mô hình Lora cho Diffusion Transformer. Chúng tôi hỗ trợ dự đoán trực tiếp từ các mô hình EasyAnimate đã được huấn luyện trước, cho phép tạo ra các video với nhiều độ phân giải khác nhau, có độ dài khoảng 6 giây, ở tốc độ 8fps (EasyAnimateV5.1, từ 1 đến 49 khung hình). Ngoài ra, người dùng có thể tự huấn luyện các mô hình baseline và Lora của riêng mình cho các phép biến đổi phong cách cụ thể.*

Pipeline này được đóng góp bởi [bubbliiiing](https://github.com/bubbliiiing). Mã nguồn gốc có thể được tìm thấy [tại đây](https://huggingface.co/alibaba-pai). Trọng số gốc có thể được tìm thấy tại [hf.co/alibaba-pai](https://huggingface.co/alibaba-pai).

Có hai checkpoint EasyAnimate chính thức cho text-to-video và video-to-video.

| checkpoints | dtype suy luận được khuyến nghị |
|:---:|:---:|
| [`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 |

Có một checkpoint EasyAnimate chính thức có sẵn cho image-to-video và video-to-video.

| checkpoints | dtype suy luận được khuyến nghị |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-InP`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-InP) | torch.float16 |

Có hai checkpoint EasyAnimate chính thức có sẵn cho control-to-video.

| checkpoints | dtype suy luận được khuyến nghị |
|:---:|:---:|
| [`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 |

Đối với dòng EasyAnimateV5.1:
- Text-to-video (T2V) và Image-to-video (I2V) hoạt động ở nhiều độ phân giải khác nhau. Chiều rộng và chiều cao có thể dao động từ 256 đến 1024.
- Cả hai mô hình T2V và I2V đều hỗ trợ tạo video với 1~49 khung hình và hoạt động tốt nhất ở giá trị này. Khuyến nghị xuất video ở 8 FPS.

## Lượng tử hóa

Quantization giúp giảm yêu cầu về bộ nhớ của các mô hình rất lớn bằng cách lưu trữ trọng số mô hình trong kiểu dữ liệu có độ chính xác thấp hơn. Tuy nhiên, lượng tử hóa có thể ảnh hưởng khác nhau đến chất lượng video tùy thuộc vào mô hình video.

Tham khảo phần tổng quan [Lượng tử hóa](../../quantization/overview) để tìm hiểu thêm về các backend lượng tử hóa được hỗ trợ và cách chọn một backend lượng tử hóa phù hợp với trường hợp sử dụng của bạn. Ví dụ bên dưới minh họa cách tải một [EasyAnimatePipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/easyanimate#diffusers.EasyAnimatePipeline) đã được lượng tử hóa để suy luận bằng bitsandbytes.

```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L186)

**Tham số:**

vae ([AutoencoderKLMagvit](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl_magvit#diffusers.AutoencoderKLMagvit)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn.

text_encoder (`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel` | None) : EasyAnimate sử dụng [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) trong V5.1.

tokenizer (`~transformers.Qwen2Tokenizer`, `~transformers.BertTokenizer` | None) : Một `Qwen2Tokenizer` hoặc `BertTokenizer` để phân tách văn bản.

transformer ([EasyAnimateTransformer3DModel](/docs/diffusers/v0.43.0/vi/api/models/easyanimate_transformer3d#diffusers.EasyAnimateTransformer3DModel)) : Mô hình EasyAnimate do EasyAnimate Team thiết kế.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với EasyAnimate để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

Pipeline để tạo video từ văn bản sử dụng EasyAnimate.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

EasyAnimate sử dụng một text encoder [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) trong V5.1.

#### __call__[[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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L524)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Các câu lệnh văn bản để hướng dẫn việc tạo ảnh hoặc video. Nếu không được cung cấp, hãy sử dụng `prompt_embeds` thay thế.

num_frames (`int`, *tuỳ chọn*) : Độ dài của video được tạo ra (tính bằng số khung hình).

height (`int`, *tuỳ chọn*) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tuỳ chọn*) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel.

num_inference_steps (`int`, *tuỳ chọn*, mặc định là 50) : Số bước khử nhiễu trong quá trình tạo. Nhiều bước hơn thường cho hình ảnh chất lượng cao hơn nhưng làm chậm suy luận.

guidance_scale (`float`, *optional*, mặc định là 5.0) : Khuyến khích mô hình căn chỉnh đầu ra với các prompt. Giá trị cao hơn có thể làm giảm chất lượng hình ảnh.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Các prompt chỉ định những gì cần loại trừ trong quá trình sinh. Nếu không được chỉ định, hãy sử dụng `negative_prompt_embeds`.

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Áp dụng cho lịch trình DDIM. Được điều khiển bởi tham số eta từ tài liệu liên quan.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Bộ tạo để đảm bảo khả năng tái lập trong quá trình tạo ảnh.

latents (`torch.Tensor`, *tùy chọn*) : Các tensor latent được định nghĩa trước để điều kiện cho quá trình sinh.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng (embeddings) của văn bản cho các prompt. Ghi đè các đầu vào chuỗi prompt để linh hoạt hơn.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Embeddings cho các prompt âm. Ghi đè các đầu vào dạng chuỗi nếu được định nghĩa.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) cho các nhúng (embeddings) của prompt chính.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho các nhúng prompt âm.

output_type (`str`, *tùy chọn*, mặc định là "latent") : Định dạng của đầu ra được tạo, dưới dạng ảnh PIL hoặc mảng NumPy.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Nếu `True`, trả về một kết quả có cấu trúc. Ngược lại, trả về một tuple đơn giản.

callback_on_step_end (`Callable`, *tùy chọn*) : Các hàm được gọi vào cuối mỗi bước khử nhiễu.

callback_on_step_end_tensor_inputs (`list[str]`, *tùy chọn*) : Tên tensor cần được bao gồm trong các cuộc gọi hàm callback.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Điều chỉnh mức độ nhiễu dựa trên thang độ dẫn hướng.

timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, lịch mặc định của scheduler cho `num_inference_steps` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Tạo hình ảnh hoặc video bằng pipeline EasyAnimate dựa trên các prompt được cung cấp.

Ví dụ:
```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L241)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

dtype (`torch.dtype`) : kiểu dữ liệu torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt. Bắt buộc khi `prompt_embeds` được truyền trực tiếp.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt âm. Bắt buộc khi `negative_prompt_embeds` được truyền trực tiếp.

max_sequence_length (`int`, *tuỳ chọn*) : độ dài tối đa của chuỗi để sử dụng cho prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

## 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/easyanimate/pipeline_output.py#L9)

**Tham số:**

frames (`torch.Tensor`, `np.ndarray`, hoặc list[list[PIL.Image.Image]]) : danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dài `batch_size,` trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dài `num_frames.` Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng `(batch_size, num_frames, channels, height, width)`.

Lớp đầu ra cho các pipeline EasyAnimate.

