# AnyFlow

[AnyFlow: Mô hình khuếch tán video bất kỳ bước nào với chưng cất bản đồ luồng theo chính sách](https://huggingface.co/papers/2605.13724) từ NVIDIA, Đại học Quốc gia Singapore và Viện Công nghệ Massachusetts, bởi Yuchao Gu, Guian Fang, Yuxin Jiang, Weijia Mao, Song Han, Han Cai, Mike Zheng Shou.

> **Tóm tắt:** AnyFlow là khung khuếch tán video theo bước tùy ý đầu tiên được xây dựng dựa trên bản đồ dòng chảy, cho phép một mô hình duy nhất (hai chiều hoặc nhân quả) thích ứng với các ngân sách suy luận tùy ý.

*Sinh video ít bước đã được thúc đẩy đáng kể bởi các mô hình nhất quán. Tuy nhiên, hiệu suất của chúng thường suy giảm trong các mô hình khuếch tán video bất kỳ bước nào do công thức điểm cố định. Để giải quyết hạn chế này, chúng tôi giới thiệu AnyFlow, khung trích xuất mô hình khuếch tán video bất kỳ bước nào đầu tiên được xây dựng dựa trên các bản đồ dòng chảy. Thay vì chỉ học ánh xạ z_t → z_0, AnyFlow học các chuyển tiếp z_t → z_r trên các khoảng thời gian tùy ý, cho phép một mô hình duy nhất thích ứng với các ngân sách suy luận khác nhau. Chúng tôi thiết kế một công thức huấn luyện bản đồ dòng chảy tiến bộ được cải thiện để tinh chỉnh các mô hình khuếch tán video được huấn luyện trước thành các mô hình bản đồ dòng chảy, và giới thiệu Mô phỏng ngược Bản đồ dòng chảy để cho phép trích xuất theo chính sách cho các mô hình bản đồ dòng chảy. Các thí nghiệm rộng rãi trên cả kiến trúc hai chiều và nhân quả, ở quy mô từ 1.3B đến 14B, trên các tác vụ từ văn bản sang video và từ hình ảnh sang video cho thấy AnyFlow vượt trội hơn so với các đường cơ sở dựa trên tính nhất quán trong khi vẫn duy trì độ trung thực cao và lấy mẫu linh hoạt dưới các ngân sách bước khác nhau.*

Các pipeline AnyFlow được đóng góp bởi nhóm AnyFlow. Mã nguồn gốc có sẵn trên [GitHub](https://github.com/NVlabs/AnyFlow), trang dự án nằm tại [nvlabs.github.io/AnyFlow](https://nvlabs.github.io/AnyFlow), và các mô hình được huấn luyện trước có thể tìm thấy trong bộ sưu tập [nvidia/anyflow](https://huggingface.co/collections/nvidia/anyflow) trên Hugging Face.

Các Mô hình Có sẵn:

| Checkpoint | Backbone | Mô tả |
|---|---|---|
| [`nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers) | Wan2.1 1.3B | T2V hai chiều |
| [`nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers) | Wan2.1 14B | T2V hai chiều |
| [`nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers) | FAR + Wan2.1 1.3B | T2V / I2V / V2V nhân quả |
| [`nvidia/AnyFlow-FAR-Wan2.1-14B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-FAR-Wan2.1-14B-Diffusers) | FAR + Wan2.1 14B | T2V / I2V / V2V nhân quả |

> [!TIP]
> `AnyFlowPipeline` được thiết kế cho các mô hình khuếch tán hai chiều trong việc tạo video từ văn bản (T2V). `AnyFlowFARPipeline` là mô hình khuếch tán nhân quả theo từng khối, hỗ trợ tạo video từ văn bản (T2V), tạo video từ hình ảnh (I2V) và tiếp nối video (V2V).

### Tạo nội dung với AnyFlow (T2V hai chiều)

```py
import torch
from diffusers import AnyFlowPipeline
from diffusers.utils import export_to_video

pipe = AnyFlowPipeline.from_pretrained(
    "nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers", dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = (
    "An astronaut runs smoothly and appears almost weightless on the lunar surface, "
    "as seen from a low-angle shot that highlights the vast, desolate background of the moon. "
    "The moon's craters and rocky terrain are clearly visible, creating a stark contrast against "
    "the running astronaut who moves with graceful, fluid motions."
)
video = pipe(prompt, num_inference_steps=4, num_frames=81).frames[0]
export_to_video(video, "anyflow_t2v.mp4", fps=16)
```

### Sinh nội dung với AnyFlow (FAR Causal)

Pipeline nhân quả chọn giữa T2V / I2V / V2V thông qua đối số ``video`` (hoặc ``video_latents``): bỏ trống cả hai để tạo video từ văn bản thuần túy, hoặc truyền ``video=<tensor>`` có hình dạng ``(B, T, C, H, W)`` trong khoảng ``[0, 1]`` với ``T = 4n + 1`` để điều kiện dựa trên các khung hình hiện có. Sử dụng một khung hình điều kiện duy nhất cho I2V và một đoạn clip dài hơn cho việc tiếp nối V2V. Nếu bạn đã có các latent được mã hóa trước theo bố cục của mô hình, hãy truyền chúng qua ``video_latents=<tensor>`` để bỏ qua bước mã hóa VAE. ``video`` và ``video_latents`` là hai đối số loại trừ lẫn nhau.

> [!IMPORTANT]
> Các checkpoint đã phát hành tích hợp sẵn `chunk_partition=[1, 3, 3, 3, 3, 3, 3, 2]` (tổng 21) vào cấu hình transformer, tương ứng với 81 khung hình thô chuẩn (21 khung hình latent tại bước thời gian 4 của VAE). Khi bạn thay đổi `num_frames`, hãy truyền một `chunk_partition` có tổng bằng `(num_frames - 1) // 4 + 1`, nếu không pipeline sẽ ném ra `ValueError`.

```py
import torch
from diffusers import AnyFlowFARPipeline
from diffusers.utils import export_to_video

pipe = AnyFlowFARPipeline.from_pretrained(
    "nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers", dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = (
    "An astronaut runs smoothly and appears almost weightless on the lunar surface, "
    "as seen from a low-angle shot that highlights the vast, desolate background of the moon."
)
video = pipe(prompt, num_inference_steps=4, num_frames=81).frames[0]
export_to_video(video, "anyflow_far_t2v.mp4", fps=16)
```

```py
import numpy as np
import torch
from diffusers import AnyFlowFARPipeline
from diffusers.utils import export_to_video, load_image

pipe = AnyFlowFARPipeline.from_pretrained(
    "nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers", dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

# Example conditioning image from the AnyFlow repo.
first_frame = load_image(
    "https://raw.githubusercontent.com/NVlabs/AnyFlow/main/assets/evaluation/example/images/1.jpg"
).resize((832, 480))
arr = np.asarray(first_frame).astype("float32") / 255.0  # (480, 832, 3)
context_tensor = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).unsqueeze(1).to("cuda")  # (1, 1, 3, 480, 832)

prompt = (
    "A towering, battle-scarred humanoid robot, reminiscent of a Transformer with powerful, segmented armor "
    "and glowing red optics, walking through the skeletal remains of a city ruin. Twisted metal and shattered "
    "concrete crunch under its heavy steps, as the robot scans the desolate, dust-choked skyline under an dark sky."
)
video = pipe(
    prompt=prompt,
    video=context_tensor,
    num_inference_steps=4,
    num_frames=81,
).frames[0]
export_to_video(video, "anyflow_far_i2v.mp4", fps=16)
```

```py
import numpy as np
import torch
from diffusers import AnyFlowFARPipeline
from diffusers.utils import export_to_video, load_video

pipe = AnyFlowFARPipeline.from_pretrained(
    "nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers", dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

# Example conditioning clip from the AnyFlow repo — take the first 9 frames (3 latent frames at VAE temporal stride 4).
context_frames = load_video(
    "https://raw.githubusercontent.com/NVlabs/AnyFlow/main/assets/evaluation/example/videos/2.mp4"
)[:9]
arr = np.stack([np.asarray(f.resize((832, 480))) for f in context_frames]).astype("float32") / 255.0
context_tensor = torch.from_numpy(arr).permute(0, 3, 1, 2).unsqueeze(0).to("cuda")  # (1, 9, 3, 480, 832)

prompt = (
    "A focused trail runner's powerful strides through a dense, sun-dappled forest. "
    "The camera tracks alongside, highlighting muscular exertion, sweat, and determined facial expression."
)
video = pipe(
    prompt=prompt,
    video=context_tensor,
    num_inference_steps=4,
    num_frames=81,
    # Override chunk_partition so the first chunk covers exactly the 3 latent context frames.
    chunk_partition=[3, 3, 3, 3, 3, 3, 3],
).frames[0]
export_to_video(video, "anyflow_far_v2v.mp4", fps=16)
```

## Ghi chú

- Classifier-free guidance đã được tích hợp vào các checkpoint được phát hành, do đó quá trình suy luận không thực hiện thêm một bước truyền dẫn có hướng dẫn thứ hai. Giữ nguyên giá trị mặc định `guidance_scale=1.0` trừ khi checkpoint của bạn yêu cầu khác.
- `FlowMapEulerDiscreteScheduler` có tính đa dụng. Bạn có thể gắn nó vào bất kỳ checkpoint nào đã được chưng cất bằng flow-map thông qua `from_pretrained(..., scheduler=FlowMapEulerDiscreteScheduler.from_config(...))`.
- `AnyFlowPipeline` sử dụng [`AnyFlowTransformer3DModel`](../models/anyflow_transformer3d) (hai chiều). `AnyFlowFARPipeline` sử dụng [`AnyFlowFARTransformer3DModel`](../models/anyflow_far_transformer3d), trong đó bổ sung patch embedding cho khung nén và khối mask nhân quả FAR.
- Việc nạp LoRA được hỗ trợ thông qua `WanLoraLoaderMixin`, cùng một mixin được sử dụng bởi các pipeline Wan upstream.
- Đối với các công thức huấn luyện (huấn luyện forward flow-map và chưng cất on-policy), hãy tham khảo khung huấn luyện AnyFlow gốc tại [`NVlabs/AnyFlow`](https://github.com/NVlabs/AnyFlow); việc huấn luyện nằm ngoài phạm vi của diffusers.

## AnyFlowPipeline[[diffusers.AnyFlowPipeline]]

#### diffusers.AnyFlowPipeline[[diffusers.AnyFlowPipeline]]

```python
diffusers.AnyFlowPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: AnyFlowTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMapEulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L80)

**Tham số:**

tokenizer ([*AutoTokenizer*]) : Tokenizer từ [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

text_encoder ([*UMT5EncoderModel*]) : bộ mã hóa văn bản [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

transformer ([*AnyFlowTransformer3DModel*]) : Transformer 3D flow-map hai chiều.

vae ([*AutoencoderKLWan*]) : VAE mã hóa/giải mã video từ và sang các biểu diễn ẩn.

scheduler ([*FlowMapEulerDiscreteScheduler*]) : Bộ lấy mẫu flow-map. Pipeline điều khiển `scheduler.step(..., timestep, sample, r_timestep)` cho mỗi bước suy luận.

Pipeline tạo video từ văn bản hai chiều cho các checkpoint được chưng cất flow-map của AnyFlow, được giới thiệu trong [AnyFlow](https://huggingface.co/papers/2605.13724).

AnyFlow học các chuyển tiếp có khoảng tùy ý \\(z_t \to z_r\\) thay vì ánh xạ cố định \\(z_t \to z_0\\) của các mô hình consistency, do đó một checkpoint đã được chưng cất duy nhất có thể được đánh giá ở 1, 2, 4, 8, 16... NFE mà không cần huấn luyện lại. Pipeline này hoạt động trên toàn bộ tensor video trong một lượt hai chiều; để tạo tự hồi quy theo từng khối (nhân quả), hãy dùng `AnyFlowFARPipeline`.

Sampling là Euler thuần túy ở dạng vận tốc trung bình (`z_r = z_t - (t - r) * u`) mà không có re-noising. Các checkpoint NVIDIA được phát hành đã tích hợp classifier-free guidance vào trọng số mô hình, do đó cài đặt mặc định `guidance_scale=1.0` là thiết lập được khuyến nghị.

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

#### __call__[[diffusers.AnyFlowPipeline.__call__]]

```python
__call__(prompt: typing.Union[str, typing.List[str]] = None, video: typing.Optional[torch.Tensor] = None, video_latents: typing.Optional[torch.Tensor] = None, negative_prompt: typing.Union[str, typing.List[str]] = None, height: int = 480, width: int = 832, num_frames: int = 81, num_inference_steps: int = 50, sigmas: typing.Optional[typing.List[float]] = None, timesteps: typing.Optional[typing.List[float]] = None, guidance_scale: float = 1.0, num_videos_per_prompt: typing.Optional[int] = 1, generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: typing.Optional[str] = 'np', return_dict: bool = True, attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None, callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], max_sequence_length: int = 512, use_mean_velocity: bool = True)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L380)

**Tham số:**

prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, hãy truyền `prompt_embeds` thay thế.

video (`torch.Tensor`, *tuỳ chọn*) : Các khung điều kiện trước VAE có hình dạng `(B, T, C, H, W)` trong khoảng `[0, 1]`. Khi được cung cấp, pipeline sẽ mã hóa chúng bằng VAE và giữ nguyên phần tiền tố latent tương ứng trong suốt quá trình lấy mẫu. Loại trừ lẫn nhau với `video_latents`.

video_latents (`torch.Tensor`, *tùy chọn*) : VAE latents đã mã hóa trước theo bố cục AnyFlow `(B, T_latent, C, H_latent, W_latent)`. Bỏ qua bước mã hóa VAE ở phía pipeline. Loại trừ lẫn nhau với `video`.

negative_prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt cần tránh trong quá trình tạo video. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

height (`int`, mặc định là `480`) : Chiều cao của video được tạo ra, tính bằng pixel.

width (`int`, mặc định là `832`) : Độ rộng của video được tạo ra, tính bằng pixel.

num_frames (`int`, mặc định là `81`) : Số khung hình trong video được tạo ra. Phải thỏa mãn `(num_frames - 1) % vae_scale_factor_temporal == 0`.

num_inference_steps (`int`, mặc định là `50`) : Số bước khử nhiễu. Các checkpoint AnyFlow đã được chưng cất hỗ trợ lấy mẫu ở bất kỳ bước nào, do đó các giá trị thấp như `1`, `2`, `4` hoặc `8` là phổ biến. Tham số này bị bỏ qua khi `sigmas` hoặc `timesteps` được cung cấp.

sigmas (`List[float]`, *optional*) : Lịch sigma tùy chỉnh cho việc lấy mẫu bất kỳ bước nào, trong khoảng `[0, 1]` và được sắp xếp từ nhiễu đến sạch. Độ dài xác định `num_inference_steps` hiệu dụng; trình lập lịch sẽ thêm sigma `0` cuối cùng.

timesteps (`List[float]`, *optional*) : Lịch trình bước thời gian tùy chỉnh cho việc lấy mẫu bất kỳ bước nào, cùng đơn vị với `self.scheduler.timesteps` (tức là được nhân với `num_train_timesteps`). Loại trừ lẫn nhau với `sigmas`.

guidance_scale (`float`, mặc định là `1.0`) : Thang độ hướng dẫn phân loại không có điều kiện (classifier-free guidance). Các checkpoint AnyFlow đã phát hành tích hợp CFG vào trọng số trong quá trình huấn luyện; giữ nguyên ở `1.0` trừ khi bạn biết chắc checkpoint của mình yêu cầu khác.

num_videos_per_prompt (`int`, *tùy chọn*, mặc định là `1`) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `List[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước để sử dụng làm đầu vào. Nếu không được cung cấp, các latents sẽ được lấy mẫu từ `generator` được cung cấp.

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 để điều chỉnh đầu vào văn bản (ví dụ: trọng số prompt). Nếu không được cung cấp, các vector nhúng sẽ được tạo từ `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.

output_type (`str`, *tùy chọn*, mặc định là `"np"`) : Định dạng đầu ra. Một trong số `"pil"`, `"np"`, `"pt"`, hoặc `"latent"`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `AnyFlowPipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm hoặc `PipelineCallback` được gọi vào cuối mỗi bước suy luận. Xem [`callbacks`](../callbacks) để biết thêm chi tiết.

callback_on_step_end_tensor_inputs (`List[str]`, *tùy chọn*, mặc định là `["latents"]`) : Các đầu vào tensor được chuyển tiếp đến callback. Phải là một tập con của `self._callback_tensor_inputs`.

max_sequence_length (`int`, mặc định là `512`) : Độ dài tối đa của chuỗi text-encoder. Các prompt dài hơn sẽ bị cắt bớt.

use_mean_velocity (`bool`, mặc định là `True`) : Khi `True`, mô hình flow-map được điều kiện hóa bởi cả bước thời gian nguồn `t` và bước thời gian đích `r` để dự đoán vận tốc trung bình, khớp với hành vi khi huấn luyện. Tắt đi để mô phỏng bước Euler thô (`r = t`).

**Trả về:** `~AnyFlowPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `AnyFlowPipelineOutput` sẽ được trả về, ngược lại một `tuple` mà phần tử đầu tiên là video được tạo sẽ được trả về.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```python
>>> import torch
>>> from diffusers import AnyFlowPipeline
>>> from diffusers.utils import export_to_video

>>> pipe = AnyFlowPipeline.from_pretrained(
...     "nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers", torch_dtype=torch.bfloat16
... ).to("cuda")

>>> prompt = "A red panda eating bamboo in a forest, cinematic lighting"
>>> video = pipe(prompt, num_inference_steps=4, num_frames=33).frames[0]
>>> export_to_video(video, "anyflow_t2v.mp4", fps=16)
```

#### encode_prompt[[diffusers.AnyFlowPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L180)

**Tham số:**

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

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

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng classifier free guidance hay không.

num_videos_per_prompt (`int`, *optional*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt. Thiết bị torch để đặt các embeddings kết quả lên

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

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

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

#### encode_video[[diffusers.AnyFlowPipeline.encode_video]]

```python
encode_video(video: Tensor, height: int, width: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L360)

Mã hóa video trong không gian pixel thành bố cục ẩn của AnyFlow.

Tuân theo quy ước helper đơn của các pipeline diffusers khác (xem `WanImageToVideoPipeline.encode_image`): đóng gói tiền xử lý, mã hóa VAE và chuẩn hóa latent thành một lần gọi. Bố cục đầu ra là `(B, T_latent, C, H, W)`, đây là định dạng mà transformer AnyFlow mong đợi cho các khung điều kiện.

## AnyFlowFARPipeline[[diffusers.AnyFlowFARPipeline]]

#### diffusers.AnyFlowFARPipeline[[diffusers.AnyFlowFARPipeline]]

```python
diffusers.AnyFlowFARPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: AnyFlowFARTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMapEulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L92)

**Tham số:**

tokenizer ([*AutoTokenizer*]) : Tokenizer từ [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

text_encoder ([*UMT5EncoderModel*]) : bộ mã hóa văn bản [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

transformer ([*AnyFlowFARTransformer3DModel*]) : Transformer 3D flow-map nhân quả FAR.

vae ([*AutoencoderKLWan*]) : VAE mã hóa/giải mã video từ và sang các biểu diễn ẩn.

scheduler ([*FlowMapEulerDiscreteScheduler*]) : Bộ lấy mẫu flow-map.

Causal Pipeline (dựa trên FAR) text-to-video / image-to-video / video-to-video cho các checkpoint của AnyFlow, được giới thiệu trong [AnyFlow](https://huggingface.co/papers/2605.13724).

Pipeline điều khiển một vòng lặp lấy mẫu tự hồi quy theo từng khối: mỗi khối được khử nhiễu bằng các bước flow-map trong khi chỉ chú ý đến các khối trước đó thông qua chú ý nhân quả thưa theo khối, và bộ nhớ đệm KV trung gian được tái sử dụng giữa các khối.

Chế độ tác vụ (T2V / I2V / V2V) được chọn dựa trên đối số điều kiện nào được truyền vào `__call__`:

- cả `video=None` và `video_latents=None` — thuần văn bản sang video.
- `video=&amp;lt;tensor of shape (B, T, C, H, W) in [0, 1] with T = 4n + 1>` — các khung hình điều kiện trước VAE; pipeline sẽ mã hóa chúng bằng VAE. Truyền một video một khung hình cho I2V hoặc một đoạn clip nhiều khung hình cho V2V.
- `video_latents=&amp;lt;latent tensor of shape (B, T_latent, C, H_latent, W_latent)>` — các latent đã được mã hóa sẵn theo bố cục FAR (bỏ qua bước mã hóa VAE).

Khung xương FAR là biến thể nhân quả Wan2.1 được giới thiệu bởi [FAR](https://huggingface.co/papers/2503.19325). Suy luận là Euler thuần túy ở dạng vận tốc trung bình cho mỗi khối, không có tái nhiễu. Hỗ trợ T2V / I2V / V2V kết hợp bằng một mô hình đã chưng cất duy nhất.

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

#### __call__[[diffusers.AnyFlowFARPipeline.__call__]]

```python
__call__(prompt: typing.Union[str, typing.List[str]] = None, video: typing.Optional[torch.Tensor] = None, video_latents: typing.Optional[torch.Tensor] = None, negative_prompt: typing.Union[str, typing.List[str]] = None, height: int = 480, width: int = 832, num_frames: int = 81, num_inference_steps: int = 50, sigmas: typing.Optional[typing.List[float]] = None, timesteps: typing.Optional[typing.List[float]] = None, guidance_scale: float = 1.0, num_videos_per_prompt: typing.Optional[int] = 1, generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: typing.Optional[str] = 'np', return_dict: bool = True, attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None, callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], max_sequence_length: int = 512, use_mean_velocity: bool = True, use_kv_cache: bool = True, chunk_partition: typing.Optional[typing.List[int]] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L448)

**Tham số:**

prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, hãy truyền `prompt_embeds` thay thế.

video (`torch.Tensor`, *tùy chọn*) : Các khung điều kiện trước VAE có hình dạng `(B, T, C, H, W)` trong khoảng `[0, 1]` (`T = 4n + 1`). Khi được cung cấp, pipeline sẽ mã hóa chúng bằng VAE và giữ nguyên phần tiền tố latent tương ứng trong quá trình lấy mẫu. Loại trừ lẫn nhau với `video_latents`.

video_latents (`torch.Tensor`, *tùy chọn*) : VAE latents đã mã hóa trước trong bố cục FAR `(B, T_latent, C, H_latent, W_latent)`. Bỏ qua bước mã hóa VAE ở phía pipeline. Loại trừ lẫn nhau với `video`.

negative_prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt cần tránh trong quá trình tạo video. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

height (`int`, mặc định là `480`) : Chiều cao của video được tạo ra, tính bằng pixel.

width (`int`, mặc định là `832`) : Độ rộng của video được tạo ra, tính bằng pixel.

num_frames (`int`, mặc định là `81`) : Số khung hình trong video được tạo ra. Phải thỏa mãn `(num_frames - 1) % vae_scale_factor_temporal == 0`.

num_inference_steps (`int`, mặc định là `50`) : Số bước khử nhiễu cho mỗi khối. Các checkpoint AnyFlow-FAR đã được chưng cất hỗ trợ lấy mẫu bất kỳ bước nào (1, 2, 4, 8, ...). Tham số này bị bỏ qua khi `sigmas` hoặc `timesteps` được cung cấp.

sigmas (`List[float]`, *optional*) : Lịch sigma tùy chỉnh cho việc lấy mẫu bất kỳ bước nào, trong khoảng `[0, 1]` và được sắp xếp từ nhiễu đến sạch. Độ dài xác định `num_inference_steps` hiệu dụng; trình lập lịch sẽ thêm sigma `0` cuối cùng.

timesteps (`List[float]`, *optional*) : Lịch trình bước thời gian tùy chỉnh cho việc lấy mẫu bất kỳ bước nào, cùng đơn vị với `self.scheduler.timesteps` (tức là được nhân với `num_train_timesteps`). Loại trừ lẫn nhau với `sigmas`.

guidance_scale (`float`, mặc định là `1.0`) : Thang độ hướng dẫn phân loại không có điều kiện (classifier-free guidance). Các checkpoint AnyFlow đã phát hành tích hợp CFG vào trọng số trong quá trình huấn luyện; giữ nguyên ở mức `1.0` trừ khi checkpoint yêu cầu khác.

num_videos_per_prompt (`int`, *tùy chọn*, mặc định là `1`) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `List[torch.Generator]`, *tùy chọn*) : Generator được sử dụng để đặt seed cho quá trình lấy mẫu.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước. Nếu không được cung cấp, các latents sẽ được lấy mẫu từ `generator` được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Nếu không được cung cấp, các vector nhúng sẽ được tạo từ `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.

output_type (`str`, *tùy chọn*, mặc định là `"np"`) : Định dạng đầu ra. Một trong số `"pil"`, `"np"`, `"pt"`, hoặc `"latent"`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `AnyFlowPipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm hoặc `PipelineCallback` được gọi vào cuối mỗi bước suy luận.

callback_on_step_end_tensor_inputs (`List[str]`, *tùy chọn*, mặc định là `["latents"]`) : Các đầu vào Tensor được chuyển tiếp đến callback. Phải là một tập con của `self._callback_tensor_inputs`.

max_sequence_length (`int`, mặc định là `512`) : Độ dài tối đa của chuỗi text-encoder.

use_mean_velocity (`bool`, mặc định là `True`) : Khi `True`, điều kiện hóa mô hình flow-map dựa trên cả bước thời gian nguồn `t` và bước thời gian đích `r` để dự đoán vận tốc trung bình. Tắt để mô phỏng bước Euler thô.

use_kv_cache (`bool`, mặc định là `True`) : Tái sử dụng bộ nhớ đệm KV của chú ý FAR giữa các khối nhân quả. Chỉ tắt khi gỡ lỗi.

chunk_partition (`List[int]`, *tùy chọn*) : Số lượng khung hình cho từng chunk. Mặc định là `self.transformer.config.chunk_partition` (khớp với các checkpoint 81 khung hình đã phát hành). Khi bạn thay đổi `num_frames`, hãy cung cấp một `chunk_partition` có tổng bằng `(num_frames - 1) // vae_scale_factor_temporal + 1`.

**Trả về:** `~AnyFlowPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, một `AnyFlowPipelineOutput` sẽ được trả về, ngược lại một `tuple` mà phần tử đầu tiên là video được tạo ra sẽ được trả về.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```python
>>> import numpy as np
>>> import torch
>>> from diffusers import AnyFlowFARPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> pipe = AnyFlowFARPipeline.from_pretrained(
...     "nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers", torch_dtype=torch.bfloat16
... ).to("cuda")

>>> # Single-frame I2V: wrap the conditioning image as a (1, 1, 3, H, W) tensor in [0, 1].
>>> first_frame = load_image("path/to/first_frame.png").resize((832, 480))
>>> arr = np.asarray(first_frame).astype("float32") / 255.0
>>> context = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).unsqueeze(1).to("cuda")

>>> video = pipe(
...     prompt="a cat walks across a sunlit lawn",
...     video=context,
...     num_inference_steps=4,
...     num_frames=81,
... ).frames[0]
>>> export_to_video(video, "anyflow_far.mp4", fps=16)
```

#### encode_prompt[[diffusers.AnyFlowFARPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L197)

**Tham số:**

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

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

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng classifier free guidance hay không.

num_videos_per_prompt (`int`, *optional*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt. Thiết bị torch để đặt các embeddings kết quả lên

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

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

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

#### encode_video[[diffusers.AnyFlowFARPipeline.encode_video]]

```python
encode_video(video: Tensor, height: int, width: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L380)

Mã hóa video trong không gian pixel thành bố cục ẩn của AnyFlow.

Tuân theo quy ước helper đơn của các pipeline diffusers khác (xem `WanImageToVideoPipeline.encode_image`): đóng gói tiền xử lý, mã hóa VAE và chuẩn hóa latent thành một lần gọi. Bố cục đầu ra là `(B, T_latent, C, H, W)`, đây là định dạng mà transformer AnyFlow mong đợi cho các khung điều kiện.

## AnyFlowPipelineOutput[[diffusers.pipelines.anyflow.pipeline_output.AnyFlowPipelineOutput]]

#### diffusers.pipelines.anyflow.pipeline_output.AnyFlowPipelineOutput[[diffusers.pipelines.anyflow.pipeline_output.AnyFlowPipelineOutput]]

```python
diffusers.pipelines.anyflow.pipeline_output.AnyFlowPipelineOutput(frames: Tensor)
```

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

**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 AnyFlow.

