Diffusers documentation
AnyFlow
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
요약: 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에서, 프로젝트 페이지는 nvlabs.github.io/AnyFlow에서, 사전 학습된 모델은 Hugging Face의 nvidia/anyflow 컬렉션에서 확인할 수 있습니다.
사용 가능한 모델:
| 체크포인트 | Backbone | 설명 |
|---|---|---|
nvidia/AnyFlow-Wan2.1-T2V-1.3B-Diffusers | Wan2.1 1.3B | 양방향 T2V |
nvidia/AnyFlow-Wan2.1-T2V-14B-Diffusers | Wan2.1 14B | 양방향 T2V |
nvidia/AnyFlow-FAR-Wan2.1-1.3B-Diffusers | FAR + Wan2.1 1.3B | Causal T2V / I2V / V2V |
nvidia/AnyFlow-FAR-Wan2.1-14B-Diffusers | FAR + Wan2.1 14B | Causal T2V / I2V / V2V |
AnyFlowPipeline는 텍스트-비디오(T2V) 생성을 위한 양방향 확산 모델에 설계되었습니다.AnyFlowFARPipeline은 텍스트-비디오(T2V) 생성, 이미지-비디오(I2V) 생성, 비디오 연속(V2V)을 지원하는 청크 단위 인과 확산 모델입니다.
AnyFlow(양방향 T2V)를 사용한 생성
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는 상호 배타적입니다.
공개된 체크포인트는
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를 발생시킵니다.
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)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)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(양방향)을 사용합니다.AnyFlowFARPipeline은 압축 프레임 패치 임베딩과 FAR 인과 블록 마스크를 추가한AnyFlowFARTransformer3DModel을 사용합니다.- LoRA 로딩은
WanLoraLoaderMixin을 통해 지원되며, 이는 업스트림 Wan 파이프라인에서 사용하는 것과 동일한 믹스인입니다. - 학습 레시피(포워드 플로우맵 학습 및 온-폴리시 증류)에 대해서는
NVlabs/AnyFlow의 원본 AnyFlow 학습 프레임워크를 참고하세요. 학습은 diffusers의 범위에 포함되지 않습니다.
AnyFlowPipeline
클래스 diffusers.AnyFlowPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModeltransformer: AnyFlowTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMapEulerDiscreteScheduler )
매개변수
- tokenizer ([AutoTokenizer]) — google/umt5-xxl의 토크나이저.
- text_encoder ([UMT5EncoderModel]) — google/umt5-xxl 텍스트 인코더.
- transformer ([AnyFlowTransformer3DModel]) — 양방향 flow-map 3D Transformer.
- vae ([AutoencoderKLWan]) — latent 표현으로 비디오를 인코딩/디코딩하는 VAE입니다.
- scheduler ([FlowMapEulerDiscreteScheduler]) —
Flow-map 샘플러입니다. 파이프라인은 추론 단계마다
scheduler.step(..., timestep, sample, r_timestep)를 호출합니다.
AnyFlow에서 소개된 AnyFlow flow-map-distilled 체크포인트용 양방향 텍스트-비디오 생성 파이프라인입니다.
AnyFlow는 고정된 매핑이 아닌 임의의 구간 전이를 학습합니다 consistency 모델의
. 따라서 단일 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에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = Nonevideo: typing.Optional[torch.Tensor] = Nonevideo_latents: typing.Optional[torch.Tensor] = Nonenegative_prompt: typing.Union[str, typing.List[str]] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50sigmas: typing.Optional[typing.List[float]] = Nonetimesteps: typing.Optional[typing.List[float]] = Noneguidance_scale: float = 1.0num_videos_per_prompt: typing.Optional[int] = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: typing.Optional[str] = 'np'return_dict: bool = Trueattention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']max_sequence_length: int = 512use_mean_velocity: bool = True ) → ~AnyFlowPipelineOutput or tuple
매개변수
- 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 latents입니다. 파이프라인 측의 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 샘플링을 위한 사용자 정의 스케줄입니다. 길이는 유효한num_inference_steps를 결정하며, 스케줄러는 종단0값을 추가합니다. - timesteps (
List[float], 선택 사항) — 모든 단계 샘플링을 위한 사용자 지정 timestep 스케줄입니다.self.scheduler.timesteps와 동일한 단위(즉,num_train_timesteps로 스케일된 값)를 사용합니다.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. - 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의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - callback_on_step_end (
Callable, 선택 사항) — 각 추론 단계의 끝에서 호출되는 함수 또는PipelineCallback입니다. 자세한 내용은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의 호출 함수.
예:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
매개변수
- 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 device - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - device — (
torch.device, 선택 사항): torch device - dtype — (
torch.dtype, 선택 사항): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
픽셀 공간의 비디오를 AnyFlow의 잠재 레이아웃으로 인코딩합니다.
다른 diffusers 파이프라인의 단일 헬퍼 컨벤션을 따릅니다(예: WanImageToVideoPipeline.encode_image). 전처리, VAE 인코딩, 잠재 변수 정규화를 하나의 호출로 묶습니다. 출력 레이아웃은 (B, T_latent, C, H, W)이며, 이는 AnyFlow 트랜스포머가 조건 프레임에 기대하는 형식입니다.
AnyFlowFARPipeline
클래스 diffusers.AnyFlowFARPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModeltransformer: AnyFlowFARTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMapEulerDiscreteScheduler )
매개변수
- tokenizer ([AutoTokenizer]) — google/umt5-xxl의 토크나이저.
- text_encoder ([UMT5EncoderModel]) — google/umt5-xxl 텍스트 인코더.
- transformer ([AnyFlowFARTransformer3DModel]) — FAR causal flow-map 3D Transformer입니다.
- vae ([AutoencoderKLWan]) — latent 표현으로 비디오를 인코딩/디코딩하는 VAE입니다.
- scheduler ([FlowMapEulerDiscreteScheduler]) — Flow-map 샘플러.
AnyFlow에서 소개된 AnyFlow 체크포인트용 인과(FAR 기반) 텍스트-투-비디오 / 이미지-투-비디오 / 비디오-투-비디오 파이프라인
는 청크 단위 오토레거시 샘플링 루프를 구동합니다. 각 청크는 블록 스파스 인과적 어텐션을 통해 이전 청크에만 주의를 기울이며 flow-map 단계로 노이즈를 제거하고, 중간 KV 캐시는 청크 간에 재사용됩니다.
태스크 모드(T2V / I2V / V2V)는 __call__에 어떤 conditioning 인자가 전달되는지에 따라 선택됩니다:
video=None과video_latents=None모두 — 순수 텍스트-투-비디오.video=<tensor of shape (B, T, C, H, W) in [0, 1] with T = 4n + 1>— VAE 인코딩 전 조건 프레임입니다. 파이프라인이 VAE 인코딩을 수행합니다. I2V의 경우 단일 프레임 비디오를, V2V의 경우 다중 프레임 클립을 전달하세요.video_latents=<latent tensor of shape (B, T_latent, C, H_latent, W_latent)>— FAR 레이아웃으로 이미 인코딩된 latents (VAE 인코딩 단계 생략).
FAR 백본은 FAR에서 도입한 causal Wan2.1 변형입니다. 추론은 재노이즈링 없이 청크별로 평균 속도 형태의 일반 Euler를 사용합니다. 단일 증류 모델로 T2V / I2V / V2V의 결합을 지원합니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = Nonevideo: typing.Optional[torch.Tensor] = Nonevideo_latents: typing.Optional[torch.Tensor] = Nonenegative_prompt: typing.Union[str, typing.List[str]] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50sigmas: typing.Optional[typing.List[float]] = Nonetimesteps: typing.Optional[typing.List[float]] = Noneguidance_scale: float = 1.0num_videos_per_prompt: typing.Optional[int] = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: typing.Optional[str] = 'np'return_dict: bool = Trueattention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']max_sequence_length: int = 512use_mean_velocity: bool = Trueuse_kv_cache: bool = Truechunk_partition: typing.Optional[typing.List[int]] = None ) → ~AnyFlowPipelineOutput or tuple
매개변수
- prompt (
str또는List[str], 선택 사항) — 비디오 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 대신prompt_embeds를 전달하세요. - video (
torch.Tensor, 선택 사항) —[0, 1]범위의(B, T, C, H, W)형식(T = 4n + 1)의 Pre-VAE conditioning frames입니다. 이 값이 제공되면 파이프라인은 VAE 인코딩을 수행하고 샘플링 동안 해당 latent prefix를 고정 상태로 유지합니다.video_latents와 상호 배타적입니다. - video_latents (
torch.Tensor, 선택 사항) — FAR 레이아웃(B, T_latent, C, H_latent, W_latent)의 사전 인코딩된 VAE latents입니다. 파이프라인 측의 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 checkpoints는 any-step sampling(1, 2, 4, 8, …)을 지원합니다.sigmas또는timesteps가 제공된 경우 무시됩니다. - sigmas (
List[float], 선택 사항) —[0, 1]범위에서 노이즈 있는 상태에서 깨끗한 상태로 정렬된, any-step 샘플링을 위한 사용자 정의 스케줄입니다. 길이는 유효한num_inference_steps를 결정하며, 스케줄러는 종단0값을 추가합니다. - timesteps (
List[float], 선택 사항) — 모든 단계 샘플링을 위한 사용자 지정 timestep 스케줄입니다.self.scheduler.timesteps와 동일한 단위(즉,num_train_timesteps로 스케일된 값)를 사용합니다.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의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - callback_on_step_end (
Callable, 선택 사항) — 각 추론 단계의 끝에서 호출되는 함수 또는PipelineCallback입니다. - 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 스테핑을 그대로 따르려면 비활성화하세요. - use_kv_cache (
bool, 기본값True) — causal chunk 간에 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의 호출 함수.
예:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
매개변수
- 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 device - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - device — (
torch.device, 선택 사항): torch device - dtype — (
torch.dtype, 선택 사항): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
픽셀 공간의 비디오를 AnyFlow의 잠재 레이아웃으로 인코딩합니다.
다른 diffusers 파이프라인의 단일 헬퍼 컨벤션을 따릅니다(예: WanImageToVideoPipeline.encode_image). 전처리, VAE 인코딩, 잠재 변수 정규화를 하나의 호출로 묶습니다. 출력 레이아웃은 (B, T_latent, C, H, W)이며, 이는 AnyFlow 트랜스포머가 조건 프레임에 기대하는 형식입니다.
AnyFlowPipelineOutput
클래스 diffusers.pipelines.anyflow.pipeline_output.AnyFlowPipelineOutput
< source >( frames: Tensor )
AnyFlow 파이프라인의 출력 클래스입니다.