# 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は、フローマップを基盤とする最初の任意ステップ対応の動画拡散フレームワークであり、単一のモデル（双方向または因果）が任意の推論予算に適応できるようにします。

*少数ステップの動画生成は、consistency modelによって大きく進展しました。しかし、固定点の定式化により、any-step video diffusion modelでは性能が低下する傾向があります。この制約に対処するため、私たちはフローマップを基盤とする最初のany-step video diffusion蒸留フレームワークであるAnyFlowを提案します。AnyFlowは、z_t → z_0へのマッピングのみを学習するのではなく、任意の時間区間における遷移 z_t → z_r を学習することで、単一のモデルが異なる推論予算に適応できるようにします。事前学習済みのvideo diffusion modelをフローマップモデルにファインチューニングするための改良版のforward flow map学習レシピを設計し、フローマップモデルのon-policy蒸留を可能にするFlow Map Backward Simulationを導入しました。双方向アーキテクチャと因果アーキテクチャの両方において、1.3Bから14Bまでの規模で、text-to-videoおよびimage-to-videoタスクに対する広範な実験により、AnyFlowはconsistencyベースのベースラインを上回り、異なるステップ予算下でも高い忠実性と柔軟なサンプリングを維持することが示されました。*

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) コレクションで確認できます。

利用可能なモデル:

| チェックポイント | バックボーン | 説明 |
|---|---|---|
| [`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 のいずれかを選択します。通常のテキストから動画への生成を行う場合は両方を省略し、既存のフレームを条件として利用する場合は、``T = 4n + 1`` を満たす形状 ``(B, T, C, H, W)`` の ``video=<tensor>`` を ``[0, 1]`` の範囲で渡します。I2V には単一の条件付けフレームを、V2V の継続にはより長いクリップを使用します。モデルレイアウトに事前エンコード済みの潜在変数が既に用意されている場合は、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)
```

## 注記

- Classifier-free guidance はリリースされたチェックポイントに融合されているため、推論時に2回目のガイド付きフォワードパスは実行されません。独自のチェックポイントで別の設定が必要な場合を除き、デフォルトの `guidance_scale=1.0` を維持してください。
- `FlowMapEulerDiscreteScheduler` は汎用的です。`from_pretrained(..., scheduler=FlowMapEulerDiscreteScheduler.from_config(...))` を使用して、任意の flow-map-distilled チェックポイントにアタッチできます。
- `AnyFlowPipeline` は [`AnyFlowTransformer3DModel`](../models/anyflow_transformer3d)（双方向）を使用します。`AnyFlowFARPipeline` は [`AnyFlowFARTransformer3DModel`](../models/anyflow_far_transformer3d) を使用し、これには圧縮フレームの patch embedding と FAR の因果ブロックマスクが追加されています。
- LoRAの読み込みは、`WanLoraLoaderMixin`を通じてサポートされています。これは、アップストリームのWanパイプラインでも使用されている同じミックスインです。
- トレーニングレシピ（フォワードフローマップ学習およびオンポリシー蒸留）については、元のAnyFlowトレーニングフレームワークの[`NVlabs/AnyFlow`](https://github.com/NVlabs/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*]) : 双方向フローマップ3D Transformer。

vae ([*AutoencoderKLWan*]) : 動画を潜在表現にエンコード/デコードするVAEです。

scheduler ([*FlowMapEulerDiscreteScheduler*]) : Flow-map サンプラー。パイプラインは、推論の各ステップごとに `scheduler.step(..., timestep, sample, r_timestep)` を呼び出します。

[AnyFlow](https://huggingface.co/papers/2605.13724)で紹介された、AnyFlowのフローマップ蒸留チェックポイント向けの双方向テキストから動画生成パイプライン。

AnyFlow learns arbitrary-interval transitions \\(z_t \to z_r\\) rather than the fixed \\(z_t \to z_0\\) mapping of consistency models, so a single distilled checkpoint can be evaluated at 1, 2, 4, 8, 16... NFE without retraining. This pipeline operates over the full video tensor in one bidirectional pass; for chunk-wise autoregressive (causal) generation use `AnyFlowFARPipeline`.

サンプリングは、平均速度形式のプレーンなオイラー法（`z_r = z_t - (t - r) * u`）であり、リノイジングは行いません。公開されている NVIDIA のチェックポイントは、classifier-free guidance をモデルの重みに折り込み済みであるため、デフォルトの `guidance_scale=1.0` が推奨される設定です。

このモデルは [*DiffusionPipeline*] を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

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

[ソース](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 でエンコードし、サンプリング中に対応する 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 のチェックポイントは任意ステップサンプリングに対応しているため、`1`、`2`、`4`、`8` といった低い値が一般的です。`sigmas` または `timesteps` が指定されている場合は無視されます。

sigmas (`List[float]`、*任意*) : 任意ステップサンプリング用のカスタム sigma スケジュールです。`[0, 1]` の範囲で、ノイズの多い状態からクリーンな状態の順に並べます。長さによって実効的な `num_inference_steps` が決まり、スケジューラは末尾に `0` の sigma を追加します。

timesteps (`List[float]`、*任意*) : ステップ数に依存しないサンプリング用のカスタムタイムステップスケジュール。`self.scheduler.timesteps` と同じ単位（つまり `num_train_timesteps` でスケーリングされた値）で指定します。`sigmas` とは排他的です。

guidance_scale (`float`、デフォルトは `1.0`) : Classifier-free guidance のスケールです。公開されている 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`, *任意*) : 入力として使用する、事前生成されたノイズ付き潜在変数。指定されない場合、`generator` から潜在変数がサンプリングされます。

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` の場合、フローマップモデルはソースタイムステップ `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`、*optional*、デフォルトは 1) : 各プロンプトに対して生成すべき動画の数。結果の埋め込みを配置する torch デバイス

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

device : (`torch.device`, *任意*): torch デバイス

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 エンコーディング、潜在変数の正規化を 1 つの呼び出しにまとめます。出力のレイアウトは `(B, T_latent, C, H, W)` であり、これは AnyFlow transformer が条件付けフレームに期待する形式です。

## 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*]) : フローマップサンプラー。

Causal [AnyFlow](https://huggingface.co/papers/2605.13724) で紹介された、AnyFlow チェックポイント向けの (FAR ベース) テキストから動画 / 画像から動画 / 動画から動画のパイプライン。

パイプラインはチャンク単位の自己回帰サンプリングループを駆動します。各チャンクは、ブロックスパース因果注意機構によって過去のチャンクのみを参照しながら、フローマップステップでデノイズされます。また、中間KVキャッシュはチャンク間で再利用されます。

タスクモード（T2V / I2V / V2V）は、`__call__`にどの条件付け引数が渡されるかによって選択されます：

- `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 レイアウトで既にエンコード済みの潜変数（VAE のエンコード手順をスキップします）。

FARバックボーンは、[FAR](https://huggingface.co/papers/2503.19325)で導入された因果的なWan2.1バリアントです。推論は、チャンクごとに平均速度形式のプレーンEuler法を用い、再ノイズ化は行いません。単一の蒸留モデルにより、T2V / I2V / V2Vの統合がサポートされています。

このモデルは [*DiffusionPipeline*] を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

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

[ソース](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 条件付けフレームです。指定された場合、パイプラインはこれらを VAE でエンコードし、サンプリング中に対応する潜在変数プレフィックスを固定します。`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`) : チャンクあたりのデノイジングステップ数です。Distilled AnyFlow-FAR チェックポイントは、任意のステップ数でのサンプリング（1、2、4、8、...）をサポートします。`sigmas` または `timesteps` が指定されている場合は無視されます。

sigmas (`List[float]`、*任意*) : 任意ステップサンプリング用のカスタム sigma スケジュールです。`[0, 1]` の範囲で、ノイズの多い状態からクリーンな状態の順に並べます。長さによって実効的な `num_inference_steps` が決まり、スケジューラは末尾に `0` の sigma を追加します。

timesteps (`List[float]`、*任意*) : ステップ数に依存しないサンプリング用のカスタムタイムステップスケジュール。`self.scheduler.timesteps` と同じ単位（つまり `num_train_timesteps` でスケーリングされた値）で指定します。`sigmas` とは排他的です。

guidance_scale (`float`、デフォルトは`1.0`) : Classifier-free guidance のスケールです。公開されている AnyFlow のチェックポイントは、学習中に CFG を重みに融合しています。チェックポイントに別の指定がない限り、`1.0`のままにしてください。

num_videos_per_prompt (`int`、*任意*、デフォルトは`1`) : プロンプトごとに生成する動画の数を指定します。

generator (`torch.Generator` または `List[torch.Generator]`、*任意*) : サンプリングのシードに使用するジェネレーター。

latents (`torch.Tensor`, *任意*) : 事前生成されたノイジーな潜在変数。指定されない場合、指定された`generator`から潜在変数がサンプリングされます。

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"]`) : コールバックに転送されるテンソル入力。`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`) : causal チャンク間で FAR attention の KV キャッシュを再利用します。デバッグ目的での無効化のみを推奨します。

chunk_partition (`List[int]`、*optional*) : チャンクごとのフレーム数。デフォルトは `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`、*optional*、デフォルトは 1) : 各プロンプトに対して生成すべき動画の数。結果の埋め込みを配置する torch デバイス

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

device : (`torch.device`, *任意*): torch デバイス

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 エンコーディング、潜在変数の正規化を 1 つの呼び出しにまとめます。出力のレイアウトは `(B, T_latent, C, H, W)` であり、これは AnyFlow transformer が条件付けフレームに期待する形式です。

## 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 パイプライン用の出力クラスです。

