Buckets:

mishig's picture
|
download
raw
35.5 kB
# AnyFlow
NVIDIA, 싱가포르 국립대학교, 매사추세츠 공과대학교의 Yuchao Gu, Guian Fang, Yuxin Jiang, Weijia Mao, Song Han, Han Cai, Mike Zheng Shou가 발표한 [AnyFlow: Any-Step Video Diffusion Model with On-Policy Flow Map Distillation](https://huggingface.co/papers/2605.13724)
> **요약:** AnyFlow는 flow map을 기반으로 구축된 최초의 any-step 비디오 diffusion 프레임워크로, 단일 모델(양방향 또는 인과적)이 임의의 추론 예산에 적응할 수 있도록 합니다.
*일부 단계 비디오 생성은 일관성 모델(consistency models)에 의해 크게 발전했습니다. 그러나 고정점(fixed-point) 공식화 때문에 어떤 단계(any-step) 비디오 확산 모델에서 성능이 종종 저하됩니다. 이 한계를 해결하기 위해, 우리는 플로우 맵(flow maps)을 기반으로 구축된 최초의 어떤 단계(any-step) 비디오 확산 증류 프레임워크인 AnyFlow를 제시합니다. AnyFlow는 z_t → z_0 매핑만 학습하는 것이 아니라, 임의의 시간 구간에 걸쳐 z_t → z_r 전이를 학습하여 단일 모델이 다양한 추론 예산에 적응할 수 있도록 합니다. 사전 학습된 비디오 확산 모델을 플로우 맵 모델로 미세 조정하는 개선된 포워드 플로우 맵 학습 레시피를 설계하고, 플로우 맵 모델의 온-폴리시(on-policy) 증류를 가능하게 하는 플로우 맵 역방향 시뮬레이션(Flow Map Backward Simulation)을 도입했습니다. 양방향 및 인과(causal) 아키텍처, 1.3B에서 14B에 이르는 규모, 텍스트-투-비디오 및 이미지-투-비디오 작업을 대상으로 한 광범위한 실험을 통해, AnyFlow가 다양한 단계 예산 하에서 높은 충실도와 유연한 샘플링을 유지하면서 일관성 기반 베이스라인보다 우수한 성능을 보임이 입증되었습니다.*
AnyFlow 파이프라인은 AnyFlow 팀이 기여했습니다. 원본 코드는 [GitHub](https://github.com/NVlabs/AnyFlow)에서, 프로젝트 페이지는 [nvlabs.github.io/AnyFlow](https://nvlabs.github.io/AnyFlow)에서, 사전 학습된 모델은 Hugging Face의 [nvidia/anyflow](https://huggingface.co/collections/nvidia/anyflow) 컬렉션에서 확인할 수 있습니다.
사용 가능한 모델:
| 체크포인트 | Backbone | 설명 |
|---|---|---|
| [`nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers) | Wan2.1 1.3B | 양방향 T2V |
| [`nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers) | Wan2.1 14B | 양방향 T2V |
| [`nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers) | FAR + Wan2.1 1.3B | Causal T2V / I2V / V2V |
| [`nvidia/AnyFlow-FAR-Wan2.1-14B-Diffusers`](https://huggingface.co/nvidia/AnyFlow-FAR-Wan2.1-14B-Diffusers) | FAR + Wan2.1 14B | Causal T2V / I2V / V2V |
> [!TIP]
> `AnyFlowPipeline`는 텍스트-비디오(T2V) 생성을 위한 양방향 확산 모델에 설계되었습니다. `AnyFlowFARPipeline`은 텍스트-비디오(T2V) 생성, 이미지-비디오(I2V) 생성, 비디오 연속(V2V)을 지원하는 청크 단위 인과 확산 모델입니다.
### AnyFlow(양방향 T2V)를 사용한 생성
```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)
```
### AnyFlow (FAR Causal)로 생성
Causal 파이프라인은 ``video``(또는 ``video_latents``) 인수를 통해 T2V / I2V / V2V를 선택합니다. 순수 텍스트-투-비디오를 사용하려면 두 인수를 모두 생략하고, 기존 프레임에 조건을 걸려면 ``[0, 1]`` 범위의 ``(B, T, C, H, W)`` 형식이고 ``T = 4n + 1``을 만족하는 ``video=<tensor>``를 전달하세요. I2V에는 단일 조건 프레임, V2V 연속 생성에는 더 긴 클립을 사용하세요. 모델 레이아웃에 맞게 사전 인코딩된 latents가 이미 있다면 VAE 인코딩을 건너뛰기 위해 ``video_latents=<tensor>``로 전달하세요. ``video``와 ``video_latents``는 상호 배타적입니다.
> [!IMPORTANT]
> 공개된 체크포인트는 `chunk_partition=[1, 3, 3, 3, 3, 3, 3, 2]`(합계 21)을 transformer 설정에 고정하여, 표준 81개의 원시 프레임(VAE의 시간 스트라이드 4에 해당하는 21개의 잠재 프레임)과 일치하도록 구성됩니다. `num_frames`을 변경할 경우, 합계가 `(num_frames - 1) // 4 + 1`이 되도록 일치하는 `chunk_partition`을 전달해야 하며, 그렇지 않으면 파이프라인이 `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)
```
## The input is a single word "Notes".
참고
- Classifier-free guidance가 공개된 체크포인트에 통합되어 있어 추론 시 두 번째 guided forward pass가 실행되지 않습니다. 자체 체크포인트에서 다른 설정이 요구되지 않는 한 기본값 `guidance_scale=1.0`을 유지하세요.
- `FlowMapEulerDiscreteScheduler`은 범용적입니다. `from_pretrained(..., scheduler=FlowMapEulerDiscreteScheduler.from_config(...))`를 통해 모든 flow-map-distilled 체크포인트에 연결할 수 있습니다.
- `AnyFlowPipeline`은 [`AnyFlowTransformer3DModel`](../models/anyflow_transformer3d)(양방향)을 사용합니다. `AnyFlowFARPipeline`은 압축 프레임 패치 임베딩과 FAR 인과 블록 마스크를 추가한 [`AnyFlowFARTransformer3DModel`](../models/anyflow_far_transformer3d)을 사용합니다.
- LoRA 로딩은 `WanLoraLoaderMixin`을 통해 지원되며, 이는 업스트림 Wan 파이프라인에서 사용하는 것과 동일한 믹스인입니다.
- 학습 레시피(포워드 플로우맵 학습 및 온-폴리시 증류)에 대해서는 [`NVlabs/AnyFlow`](https://github.com/NVlabs/AnyFlow)의 원본 AnyFlow 학습 프레임워크를 참고하세요. 학습은 diffusers의 범위에 포함되지 않습니다.
## AnyFlowPipeline[[diffusers.AnyFlowPipeline]]
#### diffusers.AnyFlowPipeline[[diffusers.AnyFlowPipeline]]
```python
diffusers.AnyFlowPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: AnyFlowTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMapEulerDiscreteScheduler)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L80)
**매개변수:**
tokenizer ([*AutoTokenizer*]) : [google/umt5-xxl](https://huggingface.co/google/umt5-xxl)의 Tokenizer.
text_encoder ([*UMT5EncoderModel*]) : [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 텍스트 인코더.
transformer ([*AnyFlowTransformer3DModel*]) : 양방향(flow-map) 3D Transformer.
vae ([*AutoencoderKLWan*]) : 비디오를 잠재 표현으로 인코딩/디코딩하는 VAE입니다.
scheduler ([*FlowMapEulerDiscreteScheduler*]) : Flow-map 샘플러입니다. 파이프라인은 추론 단계마다 `scheduler.step(..., timestep, sample, r_timestep)`을 구동합니다.
[AnyFlow](https://huggingface.co/papers/2605.13724)에서 소개된 AnyFlow flow-map-distilled 체크포인트용 양방향 텍스트-비디오 생성 파이프라인입니다.
AnyFlow은 consistency 모델의 고정된 \\(z_t \to z_0\\) 매핑이 아닌 임의의 간격 전이 \\(z_t \to z_r\\)를 학습하므로, 재학습 없이 단일 distilled checkpoint를 1, 2, 4, 8, 16... NFE에서 평가할 수 있습니다. 이 파이프라인은 전체 video tensor를 하나의 bidirectional pass로 처리하며, chunk-wise autoregressive (causal) 생성에는 `AnyFlowFARPipeline`을 사용하십시오.
Sampling은 재노이즈링 없이 평균 속도 형태의 단순 Euler입니다(`z_r = z_t - (t - r) * u`). 공개된 NVIDIA 체크포인트는 classifier-free guidance를 모델 가중치에 반영하므로, 기본값인 `guidance_scale=1.0`이 권장 설정입니다.
이 모델은 *DiffusionPipeline*에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[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)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L380)
**매개변수:**
prompt (`str` 또는 `List[str]`, *선택 사항*) : 비디오 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 대신 `prompt_embeds`를 전달하세요.
video (`torch.Tensor`, *선택 사항*) : `[0, 1]` 범위의 `(B, T, C, H, W)` 형식의 Pre-VAE conditioning frames입니다. 제공되면 파이프라인은 이를 VAE-encode하고 샘플링 동안 해당 latent prefix를 고정 상태로 유지합니다. `video_latents`와 상호 배타적입니다.
video_latents (`torch.Tensor`, *선택 사항*) : AnyFlow 레이아웃 `(B, T_latent, C, H_latent, W_latent)`의 사전 인코딩된 VAE 잠재 변수입니다. 파이프라인 측의 VAE 인코딩을 건너뜁니다. `video`와 상호 배타적입니다.
negative_prompt (`str` 또는 `List[str]`, *선택*) : 비디오 생성 과정에서 피해야 할 프롬프트입니다. guidance를 사용하지 않을 때(`guidance_scale < 1`) 무시됩니다.
height (`int`, 기본값 `480`) : 생성된 비디오의 픽셀 단위 높이입니다.
width (`int`, 기본값 `832`) : 생성된 비디오의 픽셀 단위 너비입니다.
num_frames (`int`, 기본값 `81`) : 생성된 비디오의 프레임 수입니다. `(num_frames - 1) % vae_scale_factor_temporal == 0` 조건을 만족해야 합니다.
num_inference_steps (`int`, 기본값 `50`) : 디노이징 단계 수입니다. Distilled AnyFlow 체크포인트는 any-step 샘플링을 지원하므로 `1`, `2`, `4`, `8`과 같이 낮은 값이 일반적입니다. `sigmas` 또는 `timesteps`이 제공된 경우 무시됩니다.
sigmas (`List[float]`, *선택 사항*) : `[0, 1]` 범위 내에서 노이즈가 많은 상태에서 깨끗한 상태로 정렬된, any-step 샘플링을 위한 사용자 정의 sigma 스케줄입니다. 길이는 유효한 `num_inference_steps`를 결정하며, 스케줄러는 종단 `0` sig마를 추가합니다.
timesteps (`List[float]`, *선택 사항*) : `self.scheduler.timesteps`와 동일한 단위(즉, `num_train_timesteps`로 스케일된 값)로, any-step 샘플링을 위한 사용자 지정 timestep 스케줄입니다. `sigmas`와 상호 배타적입니다.
guidance_scale (`float`, 기본값 `1.0`) : Classifier-free guidance scale입니다. 공개된 AnyFlow 체크포인트는 학습 중에 CFG를 가중치에 융합하므로, 해당 체크포인트가 다른 값을 기대하는 경우를 제외하고는 `1.0`로 유지하세요.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 `1`) : 프롬프트당 생성할 비디오의 수입니다.
generator (`torch.Generator` 또는 `List[torch.Generator]`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)입니다.
latents (`torch.Tensor`, *선택 사항*) : 입력으로 사용할 사전 생성된 노이즈된 latents입니다. 제공되지 않으면, 제공된 `generator`에서 latents가 샘플링됩니다.
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 조정하는 데 사용할 수 있습니다(예: 프롬프트 가중치). 제공되지 않으면 `prompt`에서 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 출력 형식. `"pil"`, `"np"`, `"pt"`, `"latent"` 중 하나입니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `AnyFlowPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
callback_on_step_end (`Callable`, *선택 사항*) : 각 추론 단계의 끝에서 호출되는 함수 또는 `PipelineCallback`입니다. 자세한 내용은 [`callbacks`](../callbacks)를 참조하세요.
callback_on_step_end_tensor_inputs (`List[str]`, *선택 사항*, 기본값 `["latents"]`) : 콜백으로 전달되는 텐서 입력입니다. `self._callback_tensor_inputs`의 부분 집합이어야 합니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 더 긴 프롬프트는 잘립니다.
use_mean_velocity (`bool`, 기본값 `True`) : `True`인 경우, flow-map 모델은 학습 시 동작과 일치하도록 평균 속도를 예측하기 위해 소스 타임스텝 `t`와 대상 타임스텝 `r` 모두에 조건을 부여합니다. 원시 Euler 스테핑(`r = t`)을 반영하려면 비활성화합니다.
**반환값:** `~AnyFlowPipelineOutput` 또는 `tuple`
`return_dict`가 `True`이면 `AnyFlowPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 비디오인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```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)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L180)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
#### encode_video[[diffusers.AnyFlowPipeline.encode_video]]
```python
encode_video(video: Tensor, height: int, width: int)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow.py#L360)
픽셀 공간의 비디오를 AnyFlow의 잠재 레이아웃으로 인코딩합니다.
다른 diffusers 파이프라인의 단일 헬퍼 컨벤션을 따릅니다(예: `WanImageToVideoPipeline.encode_image`). 전처리, VAE 인코딩, 잠재 변수 정규화를 하나의 호출로 묶습니다. 출력 레이아웃은 `(B, T_latent, C, H, W)`이며, 이는 AnyFlow 트랜스포머가 조건 프레임에 기대하는 형식입니다.
## AnyFlowFARPipeline[[diffusers.AnyFlowFARPipeline]]
#### diffusers.AnyFlowFARPipeline[[diffusers.AnyFlowFARPipeline]]
```python
diffusers.AnyFlowFARPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: AnyFlowFARTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMapEulerDiscreteScheduler)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L92)
**매개변수:**
tokenizer ([*AutoTokenizer*]) : [google/umt5-xxl](https://huggingface.co/google/umt5-xxl)의 Tokenizer.
text_encoder ([*UMT5EncoderModel*]) : [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 텍스트 인코더.
transformer ([*AnyFlowFARTransformer3DModel*]) : FAR causal flow-map 3D Transformer입니다.
vae ([*AutoencoderKLWan*]) : 비디오를 잠재 표현으로 인코딩/디코딩하는 VAE입니다.
scheduler ([*FlowMapEulerDiscreteScheduler*]) : Flow-map 샘플러.
Causal [AnyFlow](https://huggingface.co/papers/2605.13724)에서 소개된 AnyFlow 체크포인트용 (FAR 기반) 텍스트-투-비디오 / 이미지-투-비디오 / 비디오-투-비디오 파이프라인
pipeline은 청크 단위 오토레거시 샘플링 루프를 구동합니다. 각 청크는 블록 스파스 인과적 어텐션을 통해 이전 청크에만 주의를 기울이며 플로우맵 단계로 디노이즈되고, 중간 KV 캐시는 청크 간에 재사용됩니다.
태스크 모드(T2V / I2V / V2V)는 `__call__`에 어떤 conditioning 인자가 전달되는지에 따라 선택됩니다:
- `video=None`과 `video_latents=None` 모두 — 순수 텍스트-투-비디오.
- `video=&amp;lt;tensor of shape (B, T, C, H, W) in [0, 1] with T = 4n + 1>` — VAE 인코딩 전 조건 프레임입니다. 파이프라인이 이를 VAE 인코딩합니다. I2V의 경우 단일 프레임 비디오를, V2V의 경우 다중 프레임 클립을 전달하세요.
- `video_latents=&amp;lt;latent tensor of shape (B, T_latent, C, H_latent, W_latent)>` — FAR 레이아웃으로 이미 인코딩된 latents (VAE 인코딩 단계 생략).
FAR 백본은 [FAR](https://huggingface.co/papers/2503.19325)에서 도입한 causal Wan2.1 변형입니다. 추론은 재노이즈링 없이 청크별로 평균 속도 형태의 일반 Euler를 사용합니다. 단일 증류 모델로 T2V / I2V / V2V의 결합을 지원합니다.
이 모델은 *DiffusionPipeline*에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[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)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L448)
**매개변수:**
prompt (`str` 또는 `List[str]`, *선택 사항*) : 비디오 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 대신 `prompt_embeds`를 전달하세요.
video (`torch.Tensor`, *선택 사항*) : `[0, 1]` 범위의 `(B, T, C, H, W)` 형식(`T = 4n + 1`)의 Pre-VAE conditioning frames입니다. 제공되면 파이프라인은 이를 VAE-encode하고 샘플링 동안 해당 latent prefix를 고정 상태로 유지합니다. `video_latents`와 상호 배타적입니다.
video_latents (`torch.Tensor`, *선택 사항*) : FAR 레이아웃 `(B, T_latent, C, H_latent, W_latent)`의 사전 인코딩된 VAE 잠재 변수입니다. 파이프라인 측의 VAE 인코딩을 건너뜁니다. `video`와 상호 배타적입니다.
negative_prompt (`str` 또는 `List[str]`, *선택*) : 비디오 생성 과정에서 피해야 할 프롬프트입니다. guidance를 사용하지 않을 때(`guidance_scale < 1`) 무시됩니다.
height (`int`, 기본값 `480`) : 생성된 비디오의 픽셀 단위 높이입니다.
width (`int`, 기본값 `832`) : 생성된 비디오의 픽셀 단위 너비입니다.
num_frames (`int`, 기본값 `81`) : 생성된 비디오의 프레임 수입니다. `(num_frames - 1) % vae_scale_factor_temporal == 0` 조건을 만족해야 합니다.
num_inference_steps (`int`, 기본값 `50`) : 각 chunk당 denoising 단계 수입니다. Distilled AnyFlow-FAR 체크포인트는 any-step 샘플링(1, 2, 4, 8, ...)을 지원합니다. `sigmas` 또는 `timesteps`가 제공되면 무시됩니다.
sigmas (`List[float]`, *선택 사항*) : `[0, 1]` 범위 내에서 노이즈가 많은 상태에서 깨끗한 상태로 정렬된, any-step 샘플링을 위한 사용자 정의 sigma 스케줄입니다. 길이는 유효한 `num_inference_steps`를 결정하며, 스케줄러는 종단 `0` sig마를 추가합니다.
timesteps (`List[float]`, *선택 사항*) : `self.scheduler.timesteps`와 동일한 단위(즉, `num_train_timesteps`로 스케일된 값)로, any-step 샘플링을 위한 사용자 지정 timestep 스케줄입니다. `sigmas`와 상호 배타적입니다.
guidance_scale (`float`, 기본값 `1.0`) : Classifier-free guidance scale. 공개된 AnyFlow 체크포인트는 학습 중에 CFG를 가중치에 융합합니다. 체크포인트가 별도로 요구하지 않는 한 `1.0`으로 유지하세요.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 `1`) : 프롬프트당 생성할 비디오의 수입니다.
generator (`torch.Generator` 또는 `List[torch.Generator]`, *선택 사항*) : 샘플링 시드를 설정하는 데 사용되는 Generator입니다.
latents (`torch.Tensor`, *선택 사항*) : 미리 생성된 노이즈가 포함된 latents입니다. 제공되지 않으면, 제공된 `generator`에서 latents가 샘플링됩니다.
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 제공되지 않으면 `prompt`에서 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 출력 형식. `"pil"`, `"np"`, `"pt"`, `"latent"` 중 하나입니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `AnyFlowPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
callback_on_step_end (`Callable`, *선택 사항*) : 각 추론 단계의 끝에서 호출되는 함수 또는 `PipelineCallback`입니다.
callback_on_step_end_tensor_inputs (`List[str]`, *선택 사항*, 기본값 `["latents"]`) : 콜백으로 전달되는 Tensor 입력. `self._callback_tensor_inputs`의 부분 집합이어야 합니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다.
use_mean_velocity (`bool`, 기본값 `True`) : `True`인 경우, 평균 속도를 예측하기 위해 소스 타임스텝 `t`와 대상 타임스텝 `r` 모두로 flow-map 모델을 조건화합니다. 원시 Euler 스테핑을 그대로 따르려면 비활성화하세요.
use_kv_cache (`bool`, 기본값은 `True`) : 인과적 청크 간에 FAR attention KV 캐시를 재사용합니다. 디버깅 목적으로만 비활성화하세요.
chunk_partition (`List[int]`, *선택 사항*) : 청크별 프레임 수입니다. 기본값은 `self.transformer.config.chunk_partition`입니다(발행된 81프레임 체크포인트에 맞춰져 있음). `num_frames`를 변경할 경우, `(num_frames - 1) // vae_scale_factor_temporal + 1`의 합이 되는 `chunk_partition`을 제공해야 합니다.
**반환값:** `~AnyFlowPipelineOutput` 또는 `tuple`
`return_dict`가 `True`이면 `AnyFlowPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 비디오인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```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)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L197)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
#### encode_video[[diffusers.AnyFlowFARPipeline.encode_video]]
```python
encode_video(video: Tensor, height: int, width: int)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_anyflow_far.py#L380)
픽셀 공간의 비디오를 AnyFlow의 잠재 레이아웃으로 인코딩합니다.
다른 diffusers 파이프라인의 단일 헬퍼 컨벤션을 따릅니다(예: `WanImageToVideoPipeline.encode_image`). 전처리, VAE 인코딩, 잠재 변수 정규화를 하나의 호출로 묶습니다. 출력 레이아웃은 `(B, T_latent, C, H, W)`이며, 이는 AnyFlow 트랜스포머가 조건 프레임에 기대하는 형식입니다.
## 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)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/anyflow/pipeline_output.py#L23)
**매개변수:**
frames (`torch.Tensor`, `np.ndarray`, 또는 list[list[PIL.Image.Image]]) : 비디오 출력 목록 - `batch_size,` 길이의 중첩 목록일 수 있으며, 각 하위 목록에는 `num_frames.` 길이의 노이즈 제거된 PIL 이미지 시퀀스가 포함됩니다. 또한 `(batch_size, num_frames, channels, height, width)` 형상의 NumPy 배열 또는 Torch 텐서일 수도 있습니다.
AnyFlow 파이프라인의 출력 클래스입니다.

Xet Storage Details

Size:
35.5 kB
·
Xet hash:
0d3c6b5f61bb3486fecb267ad6d16b48bc120f44923e8b0b82e7dcfd03e68e4b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.