---
slug: inference/examples/basic
title: Basic Video Generation Tutorial
---
**Source:** [examples/inference/basic](https://github.com/hao-ai-lab/FastVideo/blob/main/examples/inference/basic)

<a id="basic-video-generation-tutorial"></a>
The `VideoGenerator` class provides the primary Python interface for doing offline video generation, which is interacting with a diffusion pipeline without using a separate inference api server.

## Requirements {#requirements}
- At least a single NVIDIA GPU with CUDA 12.4.
- Python 3.10-3.12

## Installation {#installation}
If you have not installed FastVideo, please following these [instructions](https://hao-ai-lab.github.io/FastVideo/getting_started/installation) first.

## Usage {#usage}
The first script in this example shows the most basic usage of FastVideo. If you are new to Python and FastVideo, you should start here.

```bash
# if you have not cloned the directory:
git clone https://github.com/hao-ai-lab/FastVideo.git && cd FastVideo

python examples/inference/basic/basic.py
```

### Apple Silicon (FastMetal-QAD) {#apple-silicon-fastmetal-qad}

Use the MLX runtime with FastMetal-QAD. See the
[MLX install guide](https://hao-ai-lab.github.io/FastVideo/getting_started/installation/mlx/).

```bash
hf download FastVideo/FastMetal-1.3B-QAD --local-dir ./FastMetal-1.3B-QAD

python examples/inference/basic/mlx_wan_prompt_to_video.py \
  --model-root ./FastMetal-1.3B-QAD \
  --mlx-checkpoint ./FastMetal-1.3B-QAD \
  --prompt "A bird's-eye view of a misty forest valley at dawn."
```

5B uses
[`mlx_wan22_generate.py`](https://github.com/hao-ai-lab/FastVideo/blob/main/examples/inference/basic/mlx_wan22_generate.py)
with
`FastVideo/FastMetal-5B-QAD`.

`examples/inference/basic/basic_mps.py` is the older PyTorch MPS demo.

FastH3 V1 T2VA also runs through the native MLX runtime. Convert the DiT
to INT8, INT6, or INT4 first, then run:

```bash
python examples/inference/basic/mlx_fasth3.py \
  --model-root ./FastH3-Preview-v0.2 \
  --mlx-checkpoint ./FastH3-MLX/int6 \
  --prompt "(S1) A presenter says <d>[English] Fast H3 is amazing.</d>" \
  --height 480 --width 832 --num-frames 124 \
  --output-path ./outputs/fasth3_int6.mp4
```

FastH3 V2 is a separate checkpoint and script. Convert with
`--include-vsa` and run `mlx_fasth3_8step.py`. Do not reuse a V1 DiT.

Pass `--fast` for temporal RIFE fast mode and `--fast-spatial` for spatial
fast mode (reduced-canvas denoise + pixel-space upsample); the two compose.
V1 VSA is opt-in: convert with `--include-vsa` and pass `--vsa`. V2
turns VSA on by default. See the
[MLX install guide](https://hao-ai-lab.github.io/FastVideo/getting_started/installation/mlx/).
This MLX entrypoint supports T2VA only; FL2VA, Ref2VA, and
two-pass refinement remain follow-up work. INT6/INT8/INT4 are
weight-only; VSA attention activations stay BF16. Dense-only V1
checkpoints keep working for dense inference.

The complete setup and conversion commands are in the
[MLX install guide](https://hao-ai-lab.github.io/FastVideo/getting_started/installation/mlx/).

For an example running DMD+VSA inference:
```
python examples/inference/basic/basic_dmd.py
```

For the typed config/request path added during the inference API refactor:
```
python examples/inference/basic/basic_dmd_new_api.py
```

### FastH3 Preview {#fasth3-preview}

The verified [basic FastH3 example](https://github.com/hao-ai-lab/FastVideo/blob/main/examples/inference/basic/basic_fasth3.py)
runs the few-step (4-forward, DMD2-distilled) MiniMax-H3 preview, generating
synchronized video and audio with its trained block-sparse VSA attention:

```bash
UV_TORCH_BACKEND=cu130 uv pip install -e ".[fasth3]"
```

This installs the pinned FA4 CuTe package and FastVideo kernel release used by
the measured GB200 profile. Then run:

```
python examples/inference/basic/basic_fasth3.py --prompt "your prompt"
```
The default checkpoint, [FastH3 Preview v0.2](https://huggingface.co/FastVideo/FastVideo-Minimax-FastH3-Preview-v0.2), is public on the Hub under the MiniMax H3 Community License. Review its model card and license before use or redistribution.

The default `all` profile is the fastest measured four-GPU Preview recipe on GB200. It selects VSA sparsity 0.9 with 64-token tiles and the ptx_blackwell sparse kernel, enables FA4 for eligible non-VSA paths, regionally compiles and replicates the sparse DiT, compiles and temporally parallelizes the video VAE with the `gather` strategy, and pins CPU-offloaded component memory. It also pins the benchmark protocol: five sigma-grid points (exactly four DiT forwards), one excluded seed-999 warmup, then three timed seed-1000 requests with distinct output paths.

The equivalent explicit command is:

```bash
python examples/inference/basic/basic_fasth3.py \
  --prompt "your prompt" \
  --profile all \
  --num-gpus 4 \
  --steps 5 \
  --vsa-sparsity 0.9 \
  --vsa-tile-size 64 \
  --vsa-kernel ptx_blackwell \
  --compile-vae \
  --parallel-vae \
  --replicated-dit \
  --pin-cpu-memory \
  --fa4 \
  --no-torch-compile \
  --inference-torch-compile \
  --ulysses-a2a off \
  --warmup \
  --repeats 3 \
  --seed 1000 \
  --warmup-seed 999
```

`all` enables the inference-only H3 fusions and regional compile. Both can change floating-point operation order, so this is a report-only performance profile rather than an exact-parity route. Use `--profile strict` to disable the H3 fusions while preserving regional compile, or `--profile strict --no-inference-torch-compile` for the eager strict route. Individual `--no-*` switches are available for portability and attribution; in particular, use `--vsa-kernel triton --no-fa4` if the Blackwell kernels are unavailable. `--h3-sequential-load` / `--no-h3-sequential-load` override the auto split that releases Qwen3-VL before DiT/VAE load (on by default on GB10, off on discrete GPUs). The script preserves the warmup and each measured video under distinct paths, then prints per-request wall time, the worker's peak memory, and a warmup-excluded median. `Peak memory` is the worker's allocator high-water mark: it is never reset between generations, so it includes model load and every prior run, and only rank 0's value is reported. It is populated by the `mp` backend only: the Ray backend leaves `peak_memory_mb` unset, so `--execution-backend ray` prints no `Peak memory` line.

One script covers each validated duration; regional compile is the fastest
measured DiT route for all three:

```bash
# 5 s
python examples/inference/basic/basic_fasth3.py \
  --prompt "your prompt" --output outputs/fasth3_5s
# 10 s
python examples/inference/basic/basic_fasth3.py \
  --prompt "your prompt" --num-frames 243 --output outputs/fasth3_10s
# 15 s
python examples/inference/basic/basic_fasth3.py \
  --prompt "your prompt" --num-frames 345 --output outputs/fasth3_15s
```

Pass `--no-inference-torch-compile` to recover the eager sparse-DiT route.

#### Hopper (H100 80 GB) {#hopper-h100-80-gb}

Hopper has no FA4 and no ptx_blackwell VSA kernel, so the GB200 profile above does
not apply there. The measured Hopper route keeps the same checkpoint, four
forwards and 90% VSA sparsity and changes three things: the 64-token VSA path
runs on the ThunderKittens sm_90a kernel, which fastvideo-kernel picks on sm_90
whenever it is built with
`cd fastvideo-kernel && CMAKE_ARGS='-DFASTVIDEO_KERNEL_BUILD_TK=ON' ./build.sh`
(`--vsa-kernel tk` keeps the ptx_blackwell route off and fails early when that
extension is missing),
the DiT is FSDP-sharded across the GPUs instead of replicated
(`--no-replicated-dit`; a replicated 66 GB BF16 DiT does not fit 80 GB), and
the Qwen3-VL text encoder stays resident as block-scaled FP8 (35.5 GB instead
of 66.7 GB) rather than being offloaded on every request:

```bash
python scripts/checkpoint_conversion/quantize_minimax_h3_text_encoder_fp8.py \
  --source ./FastH3-Preview-v1/text_encoder --output ./FastH3-TextEncoder-FP8

python examples/inference/basic/basic_fasth3.py \
  --prompt "your prompt" \
  --num-gpus 4 --no-replicated-dit \
  --vsa-kernel tk --no-fa4 \
  --text-encoder-weights ./FastH3-TextEncoder-FP8 \
  --no-offload-text-encoder --no-offload-vae \
  --height 544 --width 960 --num-frames 345
```

`examples/inference/basic/basic_fasth3_h100.yaml` is the same profile for
`fastvideo generate --config`. Measured points on this route (345 frames,
24 FPS, stereo audio, warm, loading and compilation excluded):

| GPUs | Resolution | Playback | Generation | Source |
|---|---|---|---|---|
| 8x H100 80 GB | 1344x768 | 14.375 s | 13.506 s (13.503 / 13.506 / 13.554) | [hlander-ai/minimax-h3](https://github.com/hlander-ai/minimax-h3) on FastVideo `b2db0c0` with these patches, Triton VSA |
| 4x H100 80 GB, NVLink | 960x544 | 14.375 s | 12.98-14.02 s over 8 consecutive clips | Windflow streaming worker on FastVideo `b2db0c0` with these patches, TK VSA |

The 4x H100 row was measured through a downstream streaming worker rather than
this script; `basic_fasth3.py` numbers for that shape will follow in a later
PR. The FP8 text encoder is a precision change relative to the stock BF16
encoder; the other two changes are lossless.

### FastH3 Preview LoRAs {#fasth3-preview-loras}

The LoRA release runs on top of `MiniMaxAI/MiniMax-H3` with the same default
compile, fusion, FA4, VSA, and parallel-VAE profile as the full FastH3 example:

```bash
bash examples/inference/basic/run_fasth3_lora_preview_vsa_datafree.sh \
  --prompt "your prompt"
```

The four release launchers are:

- `run_fasth3_lora_preview_vsa_datafree.sh`
- `run_fasth3_lora_preview_vsa_synthetic_step1300.sh`
- `run_fasth3_lora_preview_vsa_synthetic_step1900.sh`
- `run_fasth3_lora_preview_dense_datafree.sh`

Each downloads its exact private adapter file from
`FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA`; authenticate with `hf auth
login` first. Pass `--lora-strength 0.5` to interpolate every adapter payload at
half strength. Strength `1` applies the published rank-64 adapter at its trained
scale and approximates the full student; `0` removes its weight deltas. VSA
launchers still use sparse attention at strength `0` and require FastVideo's
tile-64 VSA kernel; the dense launcher selects FA4. Each launcher writes to its
own variant directory by default so comparison outputs do not collide.

### FastH3 OmniRef PDD (Ref2VA) {#fasth3-omniref-pdd-ref2va}

[basic_fasth3_omniref_pdd.py](https://github.com/hao-ai-lab/FastVideo/blob/main/examples/inference/basic/basic_fasth3_omniref_pdd.py)
runs a Parallel Decoding Distillation Ref2VA student in eight transformer
forwards. The export carries only its `transformer_ref`, scheduler configs,
and `fastvideo_inference.json`; the script links them with the base
MiniMax-H3 components into one local model directory. Its 128-token VSA tiles
need the ptx_blackwell kernel:

```bash
python examples/inference/basic/basic_fasth3_omniref_pdd.py \
  --model-path <local export directory or Hugging Face repo id> \
  --video reference.mp4 --image character.png --prompt "your prompt"
```

See [FastH3 distilled checkpoint schedules](https://github.com/hao-ai-lab/FastVideo/blob/main/docs/inference/fasth3-distilled.md#ref2va-pdd-students)
for the contract and the reference-video sparsity policy. For the consumer NVFP4
stack (RTX 5090, RTX PRO 6000, DGX Spark; FP8 on the RTX 4090) add
`--profile <name>`, and see
[FastH3 OmniRef inference](https://github.com/hao-ai-lab/FastVideo/blob/main/docs/inference/fasth3_omniref.md).

## Basic Walkthrough {#basic-walkthrough}

All you need to generate videos using multi-gpus from state-of-the-art diffusion pipelines is the following few lines!

```python
from fastvideo import VideoGenerator

def main():
    generator = VideoGenerator.from_pretrained(
        "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
        num_gpus=1,
    )

    prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
             "wide with interest. The playful yet serene atmosphere is complemented by soft "
             "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
    video = generator.generate_video(prompt)

if __name__ == "__main__":
    main()
```


## Additional Files {#additional-files}

??? note "basic.py"

    ```py
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            # image_encoder_cpu_offload=False,
        )
    
        # sampling_param = SamplingParam.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
        # sampling_param.num_frames = 45
        # sampling_param.image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
        # Generate videos with the same simple API, regardless of GPU count
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True)
        # video = generator.generate_video(prompt, sampling_param=sampling_param, output_path="wan_t2v_videos/")
    
        # Generate another video with a different prompt, without reloading the
        # model!
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        video2 = generator.generate_video(prompt2, output_path=OUTPUT_PATH, save_video=True)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_compacth3_rtx5090.yaml"

    ```yaml
    #   FASTVIDEO_ATTENTION_BACKEND=ATTN_QAT_INFER FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    #     FLASHINFER_CUDA_ARCH_LIST=12.0a FASTVIDEO_STAGE_LOGGING=1 \
    #     fastvideo generate --config examples/inference/basic/basic_compacth3_rtx5090.yaml
    generator:
      model_path: ./CompactH3
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: true
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: false
      pipeline:
        experimental:
          attention_backend: ATTN_QAT_INFER
          h3_sequential_load: true
          inference_torch_compile: false
          vae_parallel_decode: false
          video_decode_backend: h3-vae
    request:
      prompt: >-
        A wide cinematic shot of an alpine meadow at sunrise, pale pink mountain
        peaks above a blue valley filled with thin morning mist.
      negative_prompt: ""
      sampling:
        seed: 2026
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 5
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/compacth3_rtx5090/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_compacth3_rtx_pro6000.yaml"

    ```yaml
    #   FASTVIDEO_ATTENTION_BACKEND=ATTN_QAT_INFER FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    #     FLASHINFER_CUDA_ARCH_LIST=12.0a FASTVIDEO_STAGE_LOGGING=1 \
    #     fastvideo generate --config examples/inference/basic/basic_compacth3_rtx_pro6000.yaml
    generator:
      model_path: ./CompactH3
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        experimental:
          attention_backend: ATTN_QAT_INFER
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: false
          video_decode_backend: h3-vae
    request:
      prompt: >-
        A wide cinematic shot of an alpine meadow at sunrise, pale pink mountain
        peaks above a blue valley filled with thin morning mist.
      negative_prompt: ""
      sampling:
        seed: 2026
        height: 768
        width: 1344
        num_frames: 124
        fps: 24
        num_inference_steps: 5
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/compacth3_rtx_pro6000/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_cosmos2_5_dfd_i2w.py"

    ```py
    """Run the public four-step Cosmos Predict2.5 DFD Video2World student."""
    
    import argparse
    
    from fastvideo import VideoGenerator
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main() -> None:
        parser = argparse.ArgumentParser()
        parser.add_argument("--model", required=True, help="Converted FastVideo DFD model directory")
        parser.add_argument("--image", required=True, help="Conditioning image")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs_video/cosmos2_5_dfd_i2w.mp4")
        parser.add_argument("--seed", type=int, default=42)
        parser.add_argument(
            "--return-frames",
            action="store_true",
            help="Return decoded frames without writing an MP4",
        )
        args = parser.parse_args()
    
        generator = VideoGenerator.from_pretrained(
            args.model,
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
        sampling = SamplingParam(
            num_inference_steps=4,
            num_frames=81,
            height=704,
            width=1280,
            fps=24,
            seed=args.seed,
            guidance_scale=1.0,
        )
        result = generator.generate_video(
            args.prompt,
            sampling_param=sampling,
            image_path=args.image,
            num_cond_frames=1,
            output_path=args.output,
            save_video=not args.return_frames,
            return_frames=args.return_frames,
        )
        if args.return_frames:
            frames = result.get("frames") if isinstance(result, dict) else None
            if not isinstance(frames, list) or len(frames) != 81:
                raise RuntimeError("DFD frame-return contract failed: expected 81 decoded frames")
            print(f"COSMOS25_DFD_FRAMES: PASS count={len(frames)}")
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_cosmos2_5_distilled_t2w.py"

    ```py
    """Run the released Cosmos Predict2.5 2B distilled Text2World checkpoint."""
    
    import argparse
    
    from fastvideo import VideoGenerator
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main() -> None:
        parser = argparse.ArgumentParser()
        parser.add_argument("--model", required=True, help="Converted FastVideo model directory")
        parser.add_argument("--output", default="outputs_video/cosmos2_5_distilled_t2w.mp4")
        parser.add_argument("--steps", type=int, default=4, choices=range(1, 5))
        parser.add_argument("--frames", type=int, default=77)
        parser.add_argument("--height", type=int, default=704)
        parser.add_argument("--width", type=int, default=1280)
        parser.add_argument("--fps", type=int, default=24)
        parser.add_argument("--seed", type=int, default=42)
        parser.add_argument(
            "--return-frames",
            action="store_true",
            help="Return decoded frames without writing an MP4 (DreamVerse contract smoke)",
        )
        args = parser.parse_args()
    
        generator = VideoGenerator.from_pretrained(
            args.model,
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
        sampling = SamplingParam(
            num_inference_steps=args.steps,
            num_frames=args.frames,
            height=args.height,
            width=args.width,
            fps=args.fps,
            seed=args.seed,
            guidance_scale=1.0,
        )
        prompt = (
            "A robotic arm performs precision welding in an industrial workshop. "
            "Bright blue-white sparks scatter over the metal while smoke rises, "
            "cinematic lighting, steady camera, realistic motion."
        )
        result = generator.generate_video(
            prompt,
            sampling_param=sampling,
            output_path=args.output,
            save_video=not args.return_frames,
            return_frames=args.return_frames,
        )
        if args.return_frames:
            frames = result.get("frames") if isinstance(result, dict) else None
            if not isinstance(frames, list) or not frames:
                raise RuntimeError("DreamVerse contract failed: generation did not return a nonempty frames list")
            first_shape = getattr(frames[0], "shape", None)
            print(f"COSMOS25_DREAMVERSE_FRAMES: PASS count={len(frames)} first_shape={first_shape}")
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_cosmos2_5_i2w.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    from fastvideo import VideoGenerator
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main():
        # Point this to your local diffusers model dir (or replace with a HF model ID).
        model_path = "KyleShao/Cosmos-Predict2.5-2B-Diffusers"
    
        generator = VideoGenerator.from_pretrained(
            model_path,
            num_gpus=1,
            use_fsdp_inference=False,  # set True if GPU is out of memory
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        sampling_param = SamplingParam.from_pretrained(model_path)
    
        # image2world example from official repo
        image_path = "assets/images/bus_terminal.jpg"
    
        prompt = (
            "A nighttime city bus terminal gradually shifts from stillness to subtle movement. "
            "At first, multiple double-decker buses are parked under the glow of overhead lights, "
            "with a central bus labeled '87D' facing forward and stationary. "
            "As the video progresses, the bus in the middle moves ahead slowly, its headlights brightening the surrounding area "
            "and casting reflections onto adjacent vehicles. "
            "The motion creates space in the lineup, signaling activity within the otherwise quiet station. "
            "It then comes to a smooth stop, resuming its position in line. "
            "Overhead signage in Chinese characters remains illuminated, enhancing the vibrant, urban night scene.")
    
        generator.generate_video(
            prompt,
            sampling_param=sampling_param,
            image_path=str(image_path),
            num_cond_frames=1,
            output_path="outputs_video/cosmos2_5_i2w.mp4",
            save_video=True,
        )
    
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_cosmos2_5_t2w.py"

    ```py
    from fastvideo import VideoGenerator
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main():
        # Point this to your local diffusers model dir (or replace with a HF model ID).
        model_path = "KyleShao/Cosmos-Predict2.5-2B-Diffusers"
    
        generator = VideoGenerator.from_pretrained(
            model_path,
            num_gpus=1,
            use_fsdp_inference=False,  # set True if GPU is out of memory
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        # Load default sampling parameters (negative_prompt, resolution, steps, etc.)
        sampling_param = SamplingParam.from_pretrained(model_path)
    
        prompt = (
            "A high-definition video captures the precision of robotic welding in an industrial setting. "
            "The first frame showcases a robotic arm, equipped with a welding torch, positioned over a large metal structure. "
            "The welding process is in full swing, with bright sparks and intense light illuminating the scene, "
            "creating a vivid display of blue and white hues. "
            "A significant amount of smoke billows around the welding area, partially obscuring the view but emphasizing the heat and activity. "
            "The background reveals parts of the workshop environment, including a ventilation system and various pieces of machinery, "
            "indicating a busy and functional industrial workspace. "
            "As the video progresses, the robotic arm maintains its steady position, continuing the welding process and moving to its left. "
            "The welding torch consistently emits sparks and light, and the smoke continues to rise, diffusing slightly as it moves upward. "
            "The metal surface beneath the torch shows ongoing signs of heating and melting. "
            "The scene retains its industrial ambiance, with the welding sparks and smoke dominating the visual field, "
            "underscoring the ongoing nature of the welding operation.")
    
        generator.generate_video(
            prompt,
            sampling_param=sampling_param,
            output_path="outputs_video/cosmos2_5_t2w.mp4",
            save_video=True,
        )
    
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_cosmos2_5_v2w.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    from fastvideo import VideoGenerator
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main():
        # Point this to your local diffusers model dir (or replace with a HF model ID).
        model_path = "KyleShao/Cosmos-Predict2.5-2B-Diffusers"
    
        generator = VideoGenerator.from_pretrained(
            model_path,
            num_gpus=1,
            use_fsdp_inference=False,  # set True if GPU is out of memory
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        sampling_param = SamplingParam.from_pretrained(model_path)
    
        # video2world example from official repo
        video_path = "assets/videos/robot_pouring.mp4"
    
        prompt = (
            "A robotic arm, primarily white with black joints and cables, is shown in a clean, modern indoor setting with a white tabletop. "
            "The arm, equipped with a gripper holding a small, light green pitcher, is positioned above a clear glass containing a reddish-brown liquid and a spoon. "
            "The robotic arm is in the process of pouring a transparent liquid into the glass. "
            "To the left of the pitcher, there is an opened jar with a similar reddish-brown substance visible through its transparent body. "
            "In the background, a vase with white flowers and a brown couch are partially visible, adding to the contemporary ambiance. "
            "The lighting is bright, casting soft shadows on the table. "
            "The robotic arm's movements are smooth and controlled, demonstrating precision in its task. "
            "As the video progresses, the robotic arm completes the pour, leaving the glass half-filled with the reddish-brown liquid. "
            "The jar remains untouched throughout the sequence, and the spoon inside the glass remains stationary. "
            "The other robotic arm on the right side also stays stationary throughout the video. "
            "The final frame captures the robotic arm with the pitcher finishing the pour, with the glass now filled to a higher level, while the pitcher is slightly tilted but still held securely by the gripper."
        )
    
        generator.generate_video(
            prompt,
            sampling_param=sampling_param,
            video_path=str(video_path),
            num_cond_frames=1,
            output_path="outputs_video/cosmos2_5_v2w.mp4",
            save_video=True,
        )
    
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_dmd.py"

    ```py
    import os
    import time
    from fastvideo import VideoGenerator
    
    from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_dmd2"
    
    
    def main():
        os.environ["FASTVIDEO_ATTENTION_BACKEND"] = "VIDEO_SPARSE_ATTN"
    
        load_start_time = time.perf_counter()
        model_name = "FastVideo/FastWan2.1-T2V-1.3B-Diffusers"
        generator = VideoGenerator.from_pretrained(
            model_name,
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            # Adjust these offload parameters if you have < 32GB of VRAM
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            VSA_sparsity=0.8,
        )
        load_end_time = time.perf_counter()
        load_time = load_end_time - load_start_time
    
        sampling_param = SamplingParam.from_pretrained(model_name)
        sampling_param.num_frames = 81
    
        prompt = (
            "A neon-lit alley in futuristic Tokyo during a heavy rainstorm at night. The puddles reflect glowing signs in kanji, advertising ramen, karaoke, and VR arcades. A woman in a translucent raincoat walks briskly with an LED umbrella. Steam rises from a street food cart, and a cat darts across the screen. Raindrops are visible on the camera lens, creating a cinematic bokeh effect."
        )
        start_time = time.perf_counter()
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True, sampling_param=sampling_param)
        end_time = time.perf_counter()
        gen_time = end_time - start_time
    
        # Generate another video with a different prompt, without reloading the
        # model!
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        start_time = time.perf_counter()
        video2 = generator.generate_video(prompt2, output_path=OUTPUT_PATH, save_video=True, num_frames=81)
        end_time = time.perf_counter()
        gen_time2 = end_time - start_time
    
        print(f"Time taken to load model: {load_time} seconds")
        print(f"Time taken to generate video: {gen_time} seconds")
        print(f"Time taken to generate video2: {gen_time2} seconds")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_dmd_new_api.py"

    ```py
    import os
    import time
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        PipelineSelection,
    )
    
    OUTPUT_PATH = "video_samples_dmd2_typed"
    
    
    def main():
        os.environ["FASTVIDEO_ATTENTION_BACKEND"] = "VIDEO_SPARSE_ATTN"
    
        model_name = "FastVideo/FastWan2.1-T2V-1.3B-Diffusers"
        generator_config = GeneratorConfig(
            model_path=model_name,
            engine=EngineConfig(
                num_gpus=1,
                use_fsdp_inference=False,
                offload=OffloadConfig(
                    text_encoder=True,
                    pin_cpu_memory=True,
                    dit=False,
                    vae=False,
                ),
            ),
            # PR 2 still routes a few advanced inference knobs through the
            # compatibility bridge until they get first-class typed fields.
            pipeline=PipelineSelection(experimental={
                "VSA_sparsity": 0.8,
            }, ),
        )
    
        load_start_time = time.perf_counter()
        generator = VideoGenerator.from_config(generator_config)
        load_end_time = time.perf_counter()
        load_time = load_end_time - load_start_time
    
        prompt = ("A neon-lit alley in futuristic Tokyo during a heavy rainstorm at night. "
                  "The puddles reflect glowing signs in kanji, advertising ramen, karaoke, "
                  "and VR arcades. A woman in a translucent raincoat walks briskly with an "
                  "LED umbrella. Steam rises from a street food cart, and a cat darts "
                  "across the screen. Raindrops are visible on the camera lens, creating "
                  "a cinematic bokeh effect.")
        request = GenerationRequest(
            prompt=prompt,
            output=OutputConfig(
                output_path=OUTPUT_PATH,
                save_video=True,
                return_frames=False,
            ),
        )
    
        start_time = time.perf_counter()
        result = generator.generate(request)
        end_time = time.perf_counter()
        gen_time = end_time - start_time
    
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently "
                   "in the breeze, enhancing the lion's commanding presence. The tone is "
                   "vibrant, embodying the raw energy of the wild. Low angle, steady "
                   "tracking shot, cinematic.")
        request2 = GenerationRequest(
            prompt=prompt2,
            output=OutputConfig(
                output_path=OUTPUT_PATH,
                save_video=True,
                return_frames=False,
            ),
        )
    
        start_time = time.perf_counter()
        result2 = generator.generate(request2)
        end_time = time.perf_counter()
        gen_time2 = end_time - start_time
    
        print(f"Time taken to load model: {load_time} seconds")
        print(f"Time taken to generate video: {gen_time} seconds")
        print(f"First output written to: {result.video_path}")
        print(f"Time taken to generate video2: {gen_time2} seconds")
        print(f"Second output written to: {result2.video_path}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Few-step video+audio generation with the DMD2-distilled MiniMax H3 preview.
    
    The default ``all`` profile reproduces the fastest measured FastH3 Preview
    recipe on four GB200 GPUs. It runs the checkpoint's native five-point sigma
    grid (exactly four DiT forwards), trained VSA policy, Blackwell sparse kernel,
    regional fullgraph DiT compile, compiled/parallel video VAE, and inference-only
    H3 fusions. One compile warmup is excluded before three measured requests.
    
    Both regional compile and the default fusions can change floating-point
    operation order, so ``all`` is a report-only performance profile.
    ``--profile strict`` disables the H3 fusions but preserves regional compile;
    combine it with ``--no-inference-torch-compile`` for the eager strict route.
    """
    
    from __future__ import annotations
    
    import argparse
    import importlib.util
    import os
    import statistics
    import time
    import warnings
    from collections.abc import Sequence
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    from fastvideo.configs.models.dits.minimax_h3 import MiniMaxH3ArchConfig
    from fastvideo.configs.pipelines.minimax_h3_token_reduction import MiniMaxH3TokenReductionSchedule
    
    DEFAULT_MODEL = "FastVideo/FastVideo-Minimax-FastH3-Preview-v0.2"
    
    
    def build_parser(description: str | None = None) -> argparse.ArgumentParser:
        """Build the shared FastH3 preview CLI used by full and LoRA checkpoints."""
        parser = argparse.ArgumentParser(description=description or __doc__)
        parser.add_argument("--model-path", default=DEFAULT_MODEL)
        # The HF repo may require authentication while the MiniMax H3 Community
        # License review completes. A local snapshot can be passed here instead.
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs/fasth3")
        parser.add_argument("--lazy-module-load",
                            action=argparse.BooleanOptionalAction,
                            default=None,
                            help="load each heavy component on first use and free it after the last stage that "
                            "needs it, so peak memory is the largest overlapping set instead of the sum of every "
                            "component. Omit for auto (on for unified-memory devices such as GB10; off on discrete "
                            "GPUs). Costs a reload per generation; pass --no-lazy-module-load to keep every "
                            "component resident")
        parser.add_argument("--profile",
                            choices=("all", "strict"),
                            default="all",
                            help="all enables the fastest measured, non-parity H3 fusions; strict disables only them")
        parser.add_argument("--height", type=int, default=768)
        parser.add_argument("--width", type=int, default=1344)
        parser.add_argument("--num-frames", type=int, default=124)
        # num_inference_steps counts sigma-GRID POINTS. The distilled schedule is
        # t=1000,750,500,250 -> 0: five points and exactly four DiT forwards.
        parser.add_argument("--steps",
                            type=int,
                            default=5,
                            help="sigma-grid points; N points run N-1 DiT forwards (the trained default is 5)")
        seeds = parser.add_mutually_exclusive_group()
        seeds.add_argument("--seed", type=int, default=1000, help="seed reused for every measured request")
        seeds.add_argument("--seeds",
                           type=int,
                           nargs="+",
                           help="ordered seed sweep on one pipeline; repeat the list --repeats times")
        parser.add_argument("--warmup-seed", type=int, default=999)
        parser.add_argument("--repeats",
                            type=int,
                            default=3,
                            help="number of passes over the seed or seed list after warmup")
        parser.add_argument("--text-conditioning-cache-max-bytes",
                            type=int,
                            default=0,
                            help="CPU tensor-byte budget for single-rank T2VA text reuse; 0 disables the cache")
        parser.add_argument("--warmup",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="run one excluded request before timing")
        parser.add_argument("--num-gpus", type=int, default=4)
        parser.add_argument(
            "--execution-backend",
            choices=("mp", "uni", "ray"),
            default=None,
            help="mp for one node; ray for a Ray cluster (two DGX Sparks). "
            "Default: ray when RAY_ADDRESS is set, otherwise mp",
        )
        parser.add_argument("--vsa-sparsity",
                            type=float,
                            default=0.9,
                            help="run-level VSA sparsity in [0, 1); 0.9 is the checkpoint's trained policy")
        parser.add_argument("--vsa-tile-size",
                            type=int,
                            choices=(64, 256),
                            default=64,
                            help="VSA-H3 tile size; 64 is the checkpoint's trained and measured geometry")
        parser.add_argument("--vsa-kernel",
                            choices=("triton", "ptx_blackwell", "tk", "sm100a"),
                            default="ptx_blackwell",
                            help="tile-64 sparse kernel; ptx_blackwell requires a compatible fastvideo-kernel build; "
                            "tk keeps the ptx_blackwell route off and requires the ThunderKittens sm_90a extension, "
                            "which fastvideo-kernel already picks on sm_90 whenever it is built")
        parser.add_argument("--fa4",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="use FA4 for eligible non-VSA attention paths")
        parser.add_argument("--text-encoder-weights",
                            default=None,
                            help="separate text-encoder checkpoint, e.g. the block-FP8 encoder written by "
                            "scripts/checkpoint_conversion/quantize_minimax_h3_text_encoder_fp8.py")
        parser.add_argument("--offload-text-encoder",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="offload the text encoder between requests (disable to keep it resident)")
        parser.add_argument("--offload-vae",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="offload the VAE between requests (disable to keep it resident)")
        parser.add_argument("--h3-fusions",
                            action=argparse.BooleanOptionalAction,
                            default=None,
                            help="override the profile's H3 fusion policy (changes model numerics when enabled)")
        parser.add_argument("--compile-vae",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="compile the video VAE decoder independently of the DiT")
        parser.add_argument("--parallel-vae",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="round-robin VAE temporal chunks across sequence-parallel ranks")
        parser.add_argument("--h3-sequential-load",
                            action=argparse.BooleanOptionalAction,
                            default=None,
                            help="encode with Qwen3-VL, release it, then load DiT/VAEs. Default auto: on for "
                            "unified-memory devices (GB10), off on discrete GPUs")
        parser.add_argument("--video-decode-backend",
                            choices=("h3-vae", "taeh3"),
                            default="h3-vae",
                            help="h3-vae is the full MiniMax VAE; taeh3 is the fast approximate preview decoder")
        parser.add_argument("--taeh3-checkpoint", default=None, help="local taeh3.safetensors; unset uses the pinned cache")
        parser.add_argument("--replicated-dit",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="replicate DiT weights instead of FSDP-sharding them")
        parser.add_argument("--pin-cpu-memory",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="pin CPU-offloaded text-encoder and VAE weights")
        parser.add_argument("--torch-compile",
                            action=argparse.BooleanOptionalAction,
                            default=False,
                            help="compile the whole DiT path (off in the fastest FastH3 profile)")
        parser.add_argument("--inference-torch-compile",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="regionally compile DiT blocks (enabled in the fastest FastH3 profile)")
        parser.add_argument("--ulysses-a2a",
                            choices=("off", "auto"),
                            default="off",
                            help="sequence-parallel all-to-all route; off reproduces the fastest FastH3 profile, while "
                            "auto opts into the fused NVLink kernel when the installed kernel package supports it")
        parser.add_argument("--compile-mode",
                            default=None,
                            help='whole-DiT torch.compile mode, e.g. "reduce-overhead"; requires '
                            "--no-inference-torch-compile")
        parser.add_argument("--token-reduction",
                            action="store_true",
                            help="training-free speed mode after antirez/h3.c: pair horizontally adjacent generated-video "
                            "tokens inside the middle DiT blocks; faster, but can change composition")
        parser.add_argument("--token-reduction-blocks",
                            default=None,
                            metavar="BEGIN:END",
                            help="blocks that run reduced (default 4:30)")
        parser.add_argument("--token-reduction-early",
                            default=None,
                            metavar="STEPS:END",
                            help="for the first STEPS forwards, reduce up to block END instead (default 4:40; 0:0 "
                            "disables)")
        parser.add_argument("--token-reduction-scale",
                            type=float,
                            default=None,
                            help="scale of the update each paired token gets from its pair (default 1.0); unpaired "
                            "tokens, such as the last column of an odd-width video, take the full update as in h3.c")
        return parser
    
    
    def token_reduction_options(args: argparse.Namespace) -> dict[str, object] | None:
        """``h3_token_reduction`` options from the command line, or None when it is off."""
        if not getattr(args, "token_reduction", False):
            return None
        options: dict[str, object] = {"enabled": True}
        if args.token_reduction_blocks is not None:
            options["blocks"] = args.token_reduction_blocks
        if args.token_reduction_early is not None:
            options["early"] = args.token_reduction_early
        if args.token_reduction_scale is not None:
            options["update_scale"] = args.token_reduction_scale
        return options
    
    
    def validate_args(parser: argparse.ArgumentParser, args: argparse.Namespace) -> argparse.Namespace:
        if args.repeats < 1:
            parser.error("--repeats must be at least 1")
        tuning = (args.token_reduction_blocks, args.token_reduction_early, args.token_reduction_scale)
        if not args.token_reduction and any(value is not None for value in tuning):
            parser.error("--token-reduction-blocks/-early/-scale need --token-reduction")
        if args.token_reduction:
            # Reject malformed values and intervals past H3's 50 blocks before any download; the
            # transformer loader checks a shallower checkpoint, such as FastH3 Trim, against its own depth.
            try:
                MiniMaxH3TokenReductionSchedule.from_options(token_reduction_options(args) or {},
                                                             num_blocks=MiniMaxH3ArchConfig().num_layers)
            except ValueError as error:
                parser.error(str(error))
        if args.num_gpus < 1:
            parser.error("--num-gpus must be at least 1")
        if args.text_conditioning_cache_max_bytes < 0:
            parser.error("--text-conditioning-cache-max-bytes must be non-negative")
        if args.text_conditioning_cache_max_bytes and args.num_gpus != 1:
            parser.error("--text-conditioning-cache-max-bytes requires --num-gpus 1")
        if not 0.0 <= args.vsa_sparsity < 1.0:
            parser.error("--vsa-sparsity must be in [0, 1)")
        if args.compile_mode is not None and args.inference_torch_compile:
            parser.error("--compile-mode cannot be combined with regional compile; pass --no-inference-torch-compile")
        if args.vsa_kernel == "sm100a":
            warnings.warn("--vsa-kernel sm100a is deprecated; use --vsa-kernel ptx_blackwell", FutureWarning, stacklevel=2)
            args.vsa_kernel = "ptx_blackwell"
        return args
    
    
    def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
        parser = build_parser()
        return validate_args(parser, parser.parse_args(argv))
    
    
    def _uses_vsa(args: argparse.Namespace) -> bool:
        """Full FastH3 checkpoints use VSA; LoRA previews may select dense attention."""
        return bool(getattr(args, "vsa", True))
    
    
    def _h3_fusions_enabled(args: argparse.Namespace) -> bool:
        if args.h3_fusions is not None:
            return bool(args.h3_fusions)
        return args.profile == "all"
    
    
    def profile_environment(args: argparse.Namespace) -> dict[str, str | None]:
        """Return the complete boot-time environment for this profile.
    
        ``None`` means the variable must be removed. Values are explicit even for
        disabled features so a shell's inherited experiment settings cannot
        silently change the advertised profile.
        """
        use_vsa = _uses_vsa(args)
        return {
            "FASTVIDEO_ATTENTION_BACKEND": "VIDEO_SPARSE_ATTN_H3" if use_vsa else "FLASH_ATTN",
            "FASTVIDEO_VSA_PTX_BLACKWELL": "1" if use_vsa and args.vsa_kernel == "ptx_blackwell" else "0",
            "FASTVIDEO_VSA_TK": "1" if use_vsa and args.vsa_kernel == "tk" else "0",
            "FASTVIDEO_VSA_CUTEDSL": "0",
            # A non-empty output path enables the diagnostic probe.
            "FASTVIDEO_H3_VSA_PROBE": None,
            "FASTVIDEO_DISABLE_ATTENTION_COMPILE": "0",
            "FASTVIDEO_FA4": "1" if args.fa4 else "0",
            "FASTVIDEO_NVFP4_FA4": "0",
            "FASTVIDEO_MINIMAX_H3_FA4_PACKED_VARLEN": "0",
            "FASTVIDEO_MINIMAX_H3_FUSIONS": "all" if _h3_fusions_enabled(args) else "0",
            "FASTVIDEO_INFERENCE_TORCH_COMPILE": "1" if args.inference_torch_compile else "0",
            "FASTVIDEO_VAE_PARALLEL_DECODE": "1" if args.parallel_vae else "0",
            "FASTVIDEO_VAE_PARALLEL_ENCODE": "0",
            "FASTVIDEO_VAE_PARALLEL_DECODE_STRATEGY": "gather",
            "FASTVIDEO_ULYSSES_A2A": args.ulysses_a2a,
            "FASTVIDEO_STAGE_LOGGING": "1",
        }
    
    
    def configure_environment(args: argparse.Namespace) -> dict[str, str | None]:
        environment = profile_environment(args)
        for name, value in environment.items():
            if value is None:
                os.environ.pop(name, None)
            else:
                os.environ[name] = value
        return environment
    
    
    def _fa4_is_installed() -> bool:
        try:
            return importlib.util.find_spec("flash_attn.cute") is not None
        except (ImportError, ModuleNotFoundError):
            return False
    
    
    def _ptx_blackwell_kernel_is_installed() -> bool:
        try:
            from fastvideo_kernel import block_sparse_attn_ptx_blackwell
        except ImportError:
            return False
        return bool(getattr(block_sparse_attn_ptx_blackwell, "_HAS_VSA_PTX_BLACKWELL", False))
    
    
    def _sm90_kernel_is_installed() -> bool:
        try:
            from fastvideo_kernel.block_sparse_attn import _get_sm90_ops
        except ImportError:
            return False
        forward, backward = _get_sm90_ops()
        return forward is not None and backward is not None
    
    
    def validate_profile_dependencies(args: argparse.Namespace) -> None:
        """Fail before model loading when the selected measured route is absent."""
        if args.fa4 and not _fa4_is_installed():
            raise RuntimeError(
                "FastH3's FA4 profile requires the pinned flash-attn-4 package. Install it with "
                "`UV_TORCH_BACKEND=cu130 uv pip install -e \".[fasth3]\"`, or pass --no-fa4.")
        if _uses_vsa(args) and args.vsa_kernel == "ptx_blackwell" and not _ptx_blackwell_kernel_is_installed():
            raise RuntimeError(
                "FastH3's ptx_blackwell profile requires fastvideo-kernel 0.3.4 built with the Blackwell VSA extension. "
                "Install this checkout with `UV_TORCH_BACKEND=cu130 uv pip install -e \".[fasth3]\"` (or run "
                "`cd fastvideo-kernel && ./build.sh`), or pass --vsa-kernel triton.")
        if _uses_vsa(args) and args.vsa_kernel == "tk" and not _sm90_kernel_is_installed():
            raise RuntimeError(
                "FastH3's tk profile requires fastvideo-kernel built with the ThunderKittens sm_90a extension "
                "(`cd fastvideo-kernel && CMAKE_ARGS='-DFASTVIDEO_KERNEL_BUILD_TK=ON' ./build.sh`), or pass "
                "--vsa-kernel triton.")
    
    
    def _execution_backend(args: argparse.Namespace) -> str:
        if args.execution_backend is not None:
            return args.execution_backend
        return "ray" if os.environ.get("RAY_ADDRESS") else "mp"
    
    
    def build_generator_config(args: argparse.Namespace) -> GeneratorConfig:
        use_vsa = _uses_vsa(args)
        experimental: dict[str, object] = {
            "attention_backend": "VIDEO_SPARSE_ATTN_H3" if use_vsa else "FLASH_ATTN",
            "inference_torch_compile": args.inference_torch_compile,
            "vae_parallel_decode": args.parallel_vae,
            "vae_parallel_decode_strategy": "gather",
        }
        if args.text_conditioning_cache_max_bytes:
            experimental["text_conditioning_cache_max_bytes"] = args.text_conditioning_cache_max_bytes
        if args.h3_sequential_load is not None:
            experimental["h3_sequential_load"] = args.h3_sequential_load
        if args.video_decode_backend != "h3-vae":
            experimental["video_decode_backend"] = args.video_decode_backend
        if args.taeh3_checkpoint is not None:
            experimental["taeh3_checkpoint"] = args.taeh3_checkpoint
        if use_vsa:
            experimental.update({
                "VSA_sparsity": args.vsa_sparsity,
                "VSA_tile_size": args.vsa_tile_size,
            })
        token_reduction = token_reduction_options(args)
        if token_reduction is not None:
            experimental["h3_token_reduction"] = token_reduction
        return GeneratorConfig(
            model_path=args.model_path,
            pipeline=PipelineSelection(
                components=ComponentConfig(
                    lora_path=getattr(args, "lora_path", None),
                    lora_strength=float(getattr(args, "lora_strength", 1.0)),
                    text_encoder_weights=getattr(args, "text_encoder_weights", None),
                ),
                experimental=experimental,
            ),
            engine=EngineConfig(
                num_gpus=args.num_gpus,
                execution_backend=_execution_backend(args),
                use_fsdp_inference=args.num_gpus > 1 and not args.replicated_dit,
                parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                offload=OffloadConfig(
                    dit=False,
                    dit_layerwise=False,
                    text_encoder=args.offload_text_encoder,
                    vae=args.offload_vae,
                    pin_cpu_memory=args.pin_cpu_memory,
                    lazy_module_load=args.lazy_module_load,
                ),
                compile=CompileConfig(
                    enabled=args.torch_compile,
                    mode=args.compile_mode,
                    vae_enabled=args.compile_vae,
                ),
            ),
        )
    
    
    def build_request(args: argparse.Namespace, output_path: Path, seed: int) -> GenerationRequest:
        return GenerationRequest(
            prompt=args.prompt,
            negative_prompt="",
            sampling=SamplingConfig(
                height=args.height,
                width=args.width,
                num_frames=args.num_frames,
                fps=24,
                num_inference_steps=args.steps,
                # MiniMax-H3 is guidance-distilled; FastH3 inherits that contract.
                guidance_scale=1.0,
                batch_cfg=False,
                seed=seed,
            ),
            output=OutputConfig(
                output_path=str(output_path),
                save_video=True,
                return_frames=False,
            ),
        )
    
    
    def _actual_output_path(result: object, requested: Path) -> Path:
        video_path = getattr(result, "video_path", None)
        return Path(video_path) if video_path else requested
    
    
    def _denoise_seconds(result: object) -> float | None:
        stages = getattr(getattr(result, "logging_info", None), "stages", None)
        if not stages:
            return None
        for stage_name, metrics in stages.items():
            if "denois" not in stage_name.lower():
                continue
            execution_time = metrics.get("execution_time")
            return float(execution_time) if execution_time is not None else None
        return None
    
    
    def run(args: argparse.Namespace) -> list[float]:
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
        environment = configure_environment(args)
        validate_profile_dependencies(args)
    
        print(f"Profile: {args.profile} ({'non-parity fusions' if _h3_fusions_enabled(args) else 'fusions off'})")
        print(f"Output directory: {output_dir.resolve()}")
        print("Denoising contract: 5 sigma points = 4 DiT forwards" if args.steps == 5 else
              f"Denoising contract override: {args.steps} sigma points = {args.steps - 1} DiT forwards")
        print("Profile environment: " + " ".join(f"{key}={value if value is not None else '<unset>'}"
                                                      for key, value in environment.items()))
        print(f"Execution backend: {_execution_backend(args)}")
        if args.text_conditioning_cache_max_bytes:
            print(f"Text conditioning cache budget: {args.text_conditioning_cache_max_bytes} CPU tensor bytes")
            if args.warmup:
                print("The excluded warmup also conditions this prompt; use --no-warmup to include the first request.")
    
        generator = VideoGenerator.from_config(build_generator_config(args))
        measured_wall_times: list[float] = []
        measured_denoise_times: list[float] = []
        try:
            if args.warmup:
                warmup_path = output_dir / "_fasth3_warmup.mp4"
                print(f"[warmup] generating (excluded from timing summary): {warmup_path}")
                started = time.perf_counter()
                warmup_result = generator.generate(build_request(args, warmup_path, args.warmup_seed))
                warmup_wall = time.perf_counter() - started
                actual_warmup_path = _actual_output_path(warmup_result, warmup_path)
                print(f"[warmup] wall={warmup_wall:.3f}s (excluded)")
                print(f"Warmup output written to: {actual_warmup_path}")
    
            seeds = args.seeds or [args.seed]
            request_count = len(seeds) * args.repeats
            for index in range(1, request_count + 1):
                seed = seeds[(index - 1) % len(seeds)]
                seed_suffix = f"_seed_{seed}" if args.seeds else ""
                requested_path = output_dir / f"fasth3_{args.profile}_run_{index:02d}{seed_suffix}.mp4"
                print(f"[measured {index}/{request_count}] seed={seed}, generating: {requested_path}")
                started = time.perf_counter()
                result = generator.generate(build_request(args, requested_path, seed))
                wall = time.perf_counter() - started
                measured_wall_times.append(wall)
                actual_path = _actual_output_path(result, requested_path)
                print(f"Output written to: {actual_path}")
                print(f"E2E wall time: {wall:.3f}s")
                generation_time = getattr(result, "generation_time", None)
                if generation_time is not None:
                    print(f"Generation time: {float(generation_time):.3f}s")
                # Worker-lifetime allocator high-water mark: torch never resets it
                # between generations, so it includes model load and every prior run.
                peak_memory_mb = getattr(result, "peak_memory_mb", None)
                if peak_memory_mb is not None:
                    print(f"Peak memory: {float(peak_memory_mb):.1f} MB")
                denoise_time = _denoise_seconds(result)
                if denoise_time is not None:
                    measured_denoise_times.append(denoise_time)
                    print(f"Denoising time: {denoise_time:.3f}s")
    
            median = statistics.median(measured_wall_times)
            print(f"Measured E2E wall times (n={len(measured_wall_times)}, warmup excluded): "
                  f"{[round(value, 3) for value in measured_wall_times]}")
            print(f"Median E2E wall time: {median:.3f}s")
            if measured_denoise_times:
                print(f"Median denoising time: {statistics.median(measured_denoise_times):.3f}s")
            return measured_wall_times
        finally:
            generator.shutdown()
    
    
    def main() -> None:
        run(parse_args())
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_8step.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Eight-forward video+audio generation with the FastH3 8-Step V2 checkpoint.
    
    ``FastVideo/FastVideo-FastH3-8-Step-V2`` is a DMD-distilled MiniMax H3 T2AV
    student trained with video/audio scheduler shifts 10/3, VSA sparsity 0.8 and
    64-token tiles, on the explicit rung ladder ``[999, 874, 749, 624, 500, 375,
    250, 125]``. Its ``fastvideo_inference.json`` sidecar carries that ladder; the
    pipeline loads it, checks the declared shifts against the checkpoint scheduler
    configs, and runs exactly eight transformer forwards from nine sigma-grid
    points. This script only sets those defaults; it does not change the
    four-forward preview example.
    
    ``--steps`` must stay at 9 for this checkpoint: the trained ladder has eight
    rungs, and a different grid is not a valid recipe for it.
    """
    
    from __future__ import annotations
    
    import argparse
    from collections.abc import Sequence
    
    try:
        from . import basic_fasth3
    except ImportError:
        # Direct script execution puts this directory, rather than ``examples``, on
        # sys.path. Keep both ``python file.py`` and module/importlib use working.
        import basic_fasth3  # type: ignore[no-redef]
    
    MODEL = "FastVideo/FastVideo-FastH3-8-Step-V2"
    GRID_POINTS = 9  # nine sigma-grid points = eight DiT forwards
    VSA_SPARSITY = 0.8
    
    
    def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
        parser = basic_fasth3.build_parser(description=__doc__)
        parser.set_defaults(
            model_path=MODEL,
            output="outputs/fasth3_8step",
            steps=GRID_POINTS,
            vsa_sparsity=VSA_SPARSITY,
            vsa_tile_size=64,
        )
        args = basic_fasth3.validate_args(parser, parser.parse_args(argv))
        if args.steps != GRID_POINTS:
            parser.error(f"--steps must be {GRID_POINTS} for {MODEL}: the checkpoint's trained ladder has "
                         f"{GRID_POINTS - 1} rungs and the pipeline rejects any other grid")
        return args
    
    
    def main() -> None:
        basic_fasth3.run(parse_args())
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_h100.yaml"

    ```yaml
    # FastH3 Preview on four H100 80 GB GPUs (sm_90).
    #
    # Hopper has no FA4 and no sm_100a VSA kernel. This profile keeps the checkpoint,
    # the four forwards and the 90% VSA sparsity of the GB200 profile and changes
    # three things: the 64-token VSA path runs on the ThunderKittens sm_90a kernel
    # (build fastvideo-kernel with CMAKE_ARGS='-DFASTVIDEO_KERNEL_BUILD_TK=ON'), the
    # DiT is FSDP-sharded across the four GPUs instead of replicated, and the text
    # encoder stays resident as block-FP8 (35.5 GB instead of 66.7 GB; produce it
    # with scripts/checkpoint_conversion/quantize_minimax_h3_text_encoder_fp8.py),
    # so nothing is offloaded between requests. Both deferral flags below
    # (`lazy_module_load`, `h3_sequential_load`) are explicitly off for that reason:
    # with either one on, the pipeline frees the text encoder after conditioning and
    # reloads it on the next request. Keep the env prefix below, or pass
    # the equivalent CLI flags on examples/inference/basic/basic_fasth3.py
    # (`--num-gpus 4 --no-replicated-dit --vsa-kernel tk --no-fa4
    # --text-encoder-weights ./FastH3-TextEncoder-FP8 --no-offload-text-encoder
    # --no-offload-vae`).
    #
    # request.sampling below is the measured 4xH100 shape (960x544, 345 frames =
    # 14.375 s at 24 FPS). Legal H3 frame counts are 17n+5, max 345.
    #
    #   FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 FASTVIDEO_VSA_TK=1 \
    #     FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    #     fastvideo generate --config examples/inference/basic/basic_fasth3_h100.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-4-step-Preview-v1-VSA-DataFree
      pipeline:
        components:
          text_encoder_weights: ./FastH3-TextEncoder-FP8
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          VSA_sparsity: 0.9
          VSA_tile_size: 64
          inference_torch_compile: true
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
          h3_sequential_load: false
      engine:
        num_gpus: 4
        use_fsdp_inference: true
        parallelism:
          tp_size: 1
          sp_size: 4
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: true
    request:
      prompt: >-
        A wide cinematic shot of an alpine meadow at sunrise, pale pink mountain
        peaks above a blue valley filled with thin morning mist.
      negative_prompt: ""
      sampling:
        seed: 1000
        height: 544
        width: 960
        num_frames: 345
        fps: 24
        num_inference_steps: 5
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_h100/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_lora_preview.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Run a FastH3 four-step Preview LoRA with the measured FastVideo defaults.
    
    This is the LoRA counterpart of ``basic_fasth3.py``. Both routes share the
    same performance profile: four DiT forwards, regional fullgraph DiT compile,
    H3 fusions, compiled and sequence-parallel video VAE decode, replicated DiT,
    pinned CPU offload, FA4, and the ptx_blackwell tile-64 kernel for VSA adapters.
    
    The FastH3 adapters include low-rank factors plus exact dense deltas. Some also
    provide the VSA compression gate that is absent from the base checkpoint. Pass
    the adapter at construction so all three payload types receive the same
    ``--lora-strength``. The attention backend is inferred from that payload unless
    ``--vsa`` or ``--no-vsa`` is specified explicitly.
    """
    
    from __future__ import annotations
    
    import argparse
    import math
    from collections.abc import Sequence
    
    try:
        from . import basic_fasth3
    except ImportError:
        # Direct script execution puts this directory, rather than ``examples``, on
        # sys.path. Keep both ``python file.py`` and module/importlib use working.
        import basic_fasth3  # type: ignore[no-redef]
    
    BASE_MODEL = "MiniMaxAI/MiniMax-H3"
    
    
    def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
        parser = basic_fasth3.build_parser(description=__doc__)
        parser.set_defaults(model_path=BASE_MODEL, output="outputs/fasth3_lora_preview")
        parser.add_argument(
            "--lora-path",
            required=True,
            help="FastH3 adapter safetensors file or local adapter directory",
        )
        parser.add_argument(
            "--lora-strength",
            type=float,
            default=1.0,
            help="adapter strength; 0 zeros its weights but keeps its backend, and 1 applies its published scale",
        )
        parser.add_argument(
            "--vsa",
            action=argparse.BooleanOptionalAction,
            default=None,
            help="select VSA explicitly; by default it is inferred from the adapter's compression-gate payload",
        )
        args = basic_fasth3.validate_args(parser, parser.parse_args(argv))
        if not math.isfinite(args.lora_strength):
            parser.error("--lora-strength must be finite")
        return _resolve_attention_backend(parser, args)
    
    
    def _resolve_attention_backend(parser: argparse.ArgumentParser, args: argparse.Namespace) -> argparse.Namespace:
        # Header-only inspection keeps the payload on disk. A replacement compression
        # gate is an unambiguous VSA requirement; adapters without one default to dense.
        from fastvideo.models.loader.lora_patch import DenseLoRAPatch
    
        patch = DenseLoRAPatch.from_adapter(args.lora_path, strength=args.lora_strength)
        needs_vsa = bool(patch and any("gate_compress" in name for name in patch.replacement_parameters))
        if args.vsa is None:
            args.vsa = needs_vsa
        elif needs_vsa and not args.vsa:
            parser.error(f"{args.lora_path} provides to_gate_compress and must run with VSA; drop --no-vsa")
        return args
    
    
    def main() -> None:
        args = parse_args()
        print(f"FastH3 adapter: {args.lora_path}")
        print(f"LoRA strength: {args.lora_strength:g}")
        print(f"Attention: {'VSA-H3' if args.vsa else 'dense FA4'}")
        basic_fasth3.run(args)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_omniref_pdd.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Eight-forward Ref2VA video+audio generation with a FastH3 OmniRef PDD student.
    
    A FastH3 OmniRef PDD export is a Parallel Decoding Distillation (PDD) student of
    MiniMax-H3's reference-conditioned ``transformer_ref`` partition. Its directory
    (local, or a Hugging Face repo) carries only what distillation changed:
    ``transformer_ref/`` (output heads widened to the fine grid, trained VSA
    compression gates), the two scheduler configs, and ``fastvideo_inference.json``.
    The text encoder, tokenizer, processor, and both VAEs are base MiniMax-H3's.
    
    This script composes the two into one local model directory of symlinks and
    runs the recipe the contract records: fused blocks of the fine grid (one
    transformer forward each), the video/audio shifts, and VIDEO_SPARSE_ATTN_H3
    with its sparsity and tile size, where every reference video is its own
    sparse region. The contract's 128-token tiles run only on the sm_100a/sm_103a
    CUDA kernel (B200/B300/GB200/GB300) of a fastvideo-kernel build with the
    Blackwell VSA extension; the VSA-H3 backend raises at the first attention call
    when either is missing.
    With ``--num-gpus`` above 1 the DiT is sharded across the GPUs (FSDP) and the
    sequence is split across them (sequence parallelism).
    
    References are ordered. Pass them in order with --image / --video / --audio,
    for example ``--video dance.mp4 --image outfit.png --audio voice.wav``.
    
    ``--profile {spark,rtx-pro-6000,rtx-5090,rtx-4090}`` runs the consumer stack on
    one of those devices: a packed NVFP4 export, FP4 sparse attention with the dense
    prefix rows split off at 8-bit Q/K, and the pre-packed NVFP4 decoder, with the
    device's own offload policy and geometry. The 4090, having no FP4 hardware, runs
    the closest equivalent from a dense/FP8 export (FP8 linears, bf16 VSA, the dense decoder). See
    docs/inference/fasth3_omniref.md.
    
    ``--lossless-accel`` turns on every bit-identical speed-up the pipeline has
    (LOSSLESS_ACCEL_ENV below, plus resident encoders, pinned host memory and the
    sequence-parallel VAE); the output is bitwise the same as without it. It keeps
    the 63 GB Qwen3-VL text encoder resident on every GPU, so it needs about
    125 GB per GPU at four GPUs (B200/B300 class).
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import os
    from collections.abc import Sequence
    from dataclasses import dataclass
    from pathlib import Path
    from typing import Any
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        QuantizationConfig,
        SamplingConfig,
    )
    from fastvideo.configs.models.dits.minimax_h3 import MiniMaxH3ArchConfig
    from fastvideo.configs.pipelines.minimax_h3 import parse_base_model_revision
    from fastvideo.configs.pipelines.minimax_h3_token_reduction import MiniMaxH3TokenReductionSchedule
    from fastvideo.pipelines.basic.minimax_h3 import MiniMaxH3Reference
    
    CONTRACT = "fastvideo_inference.json"
    DEFAULT_HEIGHT, DEFAULT_WIDTH = 480, 832
    # Components the distilled export replaces, and the ones it shares with base MiniMax-H3.
    EXPORT_COMPONENTS = ("transformer_ref", "scheduler", "audio_scheduler")
    BASE_COMPONENTS = ("text_encoder", "tokenizer", "processor", "vae", "audio_vae")
    MANIFESTS = ("modular_model_index.json", "model_index.json")
    # Components the composed directory's manifest must declare, besides its transformer_ref.
    MANIFEST_COMPONENTS = ("scheduler", "audio_scheduler", *BASE_COMPONENTS)
    # Bit-identical speed-ups that FastVideo reads from the environment. Workers
    # inherit it, so these must be set before the generator starts.
    LOSSLESS_ACCEL_ENV = {
        # Fused NVLink Ulysses all-to-all instead of NCCL plus permute copies.
        "FASTVIDEO_ULYSSES_A2A": "auto",
        # RoPE, AdaLN modulation / gated residual and SwiGLU kernels that round to
        # bf16 exactly where the eager ops do (not the FP32 round-once fusions).
        "FASTVIDEO_MINIMAX_H3_EXACT_KERNELS": "all",
        # VSA tiles scattered straight into the kernels' heads-first layout.
        "FASTVIDEO_H3_VSA_HEADS_FIRST_TILE": "1",
        # VAE spatial tiles split across the sequence-parallel ranks.
        "FASTVIDEO_H3_VAE_TILE_PARALLEL": "1",
        # Content-keyed reuse of repeat reference encodes.
        "FASTVIDEO_H3_REF2VA_MEMO_ENTRIES": "16",
    }
    
    
    class _AppendReference(argparse.Action):
        """Collect --image/--video/--audio into one list that keeps command-line order."""
    
        def __call__(self, parser, namespace, value, option_string=None):
            references = list(getattr(namespace, self.dest, None) or [])
            references.append((self.const, value))
            setattr(namespace, self.dest, references)
    
    
    def build_parser() -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--model-path",
                            required=True,
                            help="FastH3 OmniRef PDD export: a local directory or a Hugging Face repo id")
        parser.add_argument("--revision", default=None, help="revision of --model-path when it is a Hugging Face repo")
        parser.add_argument("--base-model-path",
                            default=None,
                            help="base MiniMax-H3 snapshot (local directory or repo id). Default: the repo and revision "
                            "pinned by the export's base_model_revision")
        parser.add_argument("--base-revision",
                            default=None,
                            help="revision of --base-model-path when it is a repo id (the export's pinned revision "
                            "applies only to its own base repo); without --base-model-path, overrides that pin")
        parser.add_argument("--composed-dir",
                            default=None,
                            help="where to write the composed model directory of symlinks (default: "
                            "<output>/fasth3_omniref_model)")
        for flag in ("image", "video", "audio"):
            parser.add_argument(f"--{flag}",
                                dest="references",
                                action=_AppendReference,
                                const=flag,
                                metavar="PATH",
                                help=f"an ordered {flag} reference (repeatable)")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs/fasth3_omniref_pdd")
        parser.add_argument("--height", type=int, default=None)
        parser.add_argument("--width", type=int, default=None)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=1, help="sequence-parallel GPUs (must divide 56 heads)")
        parser.add_argument("--lossless-accel",
                            action="store_true",
                            help="enable every bit-identical speed-up (output unchanged; about 125 GB per GPU)")
        parser.add_argument("--profile",
                            choices=sorted(DEVICE_PROFILES),
                            default=None,
                            help="run the full NVFP4 consumer stack for one device, with its offload policy and "
                            "environment (see docs/inference/fasth3_omniref.md); the checkpoint must be "
                            "the packed NVFP4 export on Blackwell, or a dense/FP8 export on the 4090")
        parser.add_argument("--attention-prefix",
                            choices=("default", "fp8", "bf16"),
                            default="default",
                            help="numerics for the dense attention prefix rows (text, reference and audio). "
                            "'fp8' is the validated-quality mode and the device-profile default; 'bf16' is "
                            "higher precision but slower; 'default' keeps the profile's choice")
        parser.add_argument("--decoder",
                            default=None,
                            help="pre-packed NVFP4 VAE decoder (decoder-nvfp4.safetensors) used by --profile "
                            "instead of the VAE folder's own decoder")
        parser.add_argument("--adaln-table",
                            default=None,
                            help="precomputed AdaLN modulation table, so the 26 GB of adaln_proj never loads "
                            "(write one once with FASTVIDEO_H3_ADALN_DUMP). Strongly recommended: the 24/32 GB "
                            "profiles need it to keep the DiT resident")
        parser.add_argument("--token-reduction",
                            action="store_true",
                            help="training-free speed mode after antirez/h3.c: pair horizontally adjacent generated-video "
                            "tokens inside the middle DiT blocks; faster, but can change composition")
        parser.add_argument("--token-reduction-blocks",
                            default=None,
                            metavar="BEGIN:END",
                            help="blocks that run reduced (default 4:30)")
        parser.add_argument("--token-reduction-early",
                            default=None,
                            metavar="STEPS:END",
                            help="for the first STEPS forwards, reduce up to block END instead (default 4:40; 0:0 "
                            "disables)")
        parser.add_argument("--token-reduction-scale",
                            type=float,
                            default=None,
                            help="scale of the update each paired token gets from its pair (default 1.0); unpaired "
                            "tokens, such as the last column of an odd-width video, take the full update as in h3.c")
        return parser
    
    
    def token_reduction_options(args: argparse.Namespace) -> dict[str, Any] | None:
        """``h3_token_reduction`` options from the command line, or None when it is off."""
        if not args.token_reduction:
            return None
        options: dict[str, Any] = {"enabled": True}
        if args.token_reduction_blocks is not None:
            options["blocks"] = args.token_reduction_blocks
        if args.token_reduction_early is not None:
            options["early"] = args.token_reduction_early
        if args.token_reduction_scale is not None:
            options["update_scale"] = args.token_reduction_scale
        return options
    
    
    def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
        parser = build_parser()
        args = parser.parse_args(argv)
        if not args.references:
            parser.error("pass at least one ordered reference with --image, --video, or --audio")
        if not any(kind != "audio" for kind, _ in args.references):
            parser.error("Ref2VA needs at least one image or video reference")
        tuning = (args.token_reduction_blocks, args.token_reduction_early, args.token_reduction_scale)
        if not args.token_reduction and any(value is not None for value in tuning):
            parser.error("--token-reduction-blocks/-early/-scale need --token-reduction")
        if args.token_reduction:
            # Reject malformed values and intervals past H3's 50 blocks before any download; the
            # transformer loader checks the checkpoint's own depth.
            try:
                MiniMaxH3TokenReductionSchedule.from_options(token_reduction_options(args),
                                                             num_blocks=MiniMaxH3ArchConfig().num_layers)
            except ValueError as error:
                parser.error(str(error))
        return args
    
    
    def _snapshot(path_or_repo: str, revision: str | None, allow_patterns: list[str]) -> Path:
        local = Path(path_or_repo).expanduser()
        if local.is_dir():
            return local
        from huggingface_hub import snapshot_download
    
        return Path(snapshot_download(repo_id=path_or_repo, revision=revision, allow_patterns=allow_patterns))
    
    
    def load_contract(export_dir: Path) -> dict[str, Any]:
        path = export_dir / CONTRACT
        if not path.is_file():
            raise FileNotFoundError(f"{export_dir} has no {CONTRACT}; it is not a FastH3 distilled export.")
        contract = json.loads(path.read_text(encoding="utf-8"))
        if "pdd_steps" not in contract or contract.get("model_type") != "ref2va":
            raise ValueError(f"{path} is not a Ref2VA PDD contract; use the example matching the checkpoint.")
        return contract
    
    
    def base_model_source(args: argparse.Namespace, contract: dict[str, Any]) -> tuple[str, str | None]:
        """The base snapshot and revision: --base-model-path as given, else the export's pin."""
        base_repo, base_revision = base_model_from_contract(contract)
        if args.base_model_path:
            return args.base_model_path, args.base_revision
        return base_repo, args.base_revision or base_revision
    
    
    def base_model_from_contract(contract: dict[str, Any]) -> tuple[str, str]:
        """The base repo id and revision that the export pins as ``hf://<repo id>@<revision>``."""
        return parse_base_model_revision(contract.get("base_model_revision"))
    
    
    def _link(destination: Path, source: Path) -> None:
        if not source.exists():
            raise FileNotFoundError(f"Missing checkpoint component: {source}")
        source = source.resolve()
        if destination.is_symlink():
            if destination.resolve() == source:
                return
            destination.unlink()
        elif destination.exists():
            raise FileExistsError(f"{destination} exists and is not a symlink; choose another --composed-dir.")
        destination.symlink_to(source, target_is_directory=source.is_dir())
    
    
    def _declares_components(manifest: Path) -> bool:
        """Whether a Diffusers manifest declares every component of the composed directory."""
        declared = {
            name
            for name, spec in json.loads(manifest.read_text(encoding="utf-8")).items()
            if isinstance(spec, list) and spec and spec[0] is not None
        }
        return set(MANIFEST_COMPONENTS) <= declared and bool({"transformer", "transformer_ref"} & declared)
    
    
    def select_manifest(export_dir: Path, base_dir: Path) -> Path:
        """The export's manifest when it declares every composed component, else the base's."""
        for root in (export_dir, base_dir):
            for name in MANIFESTS:
                if (root / name).is_file() and _declares_components(root / name):
                    return root / name
        raise FileNotFoundError("Neither the export nor the base snapshot has a Diffusers model manifest that declares "
                                f"{', '.join(MANIFEST_COMPONENTS)} and transformer_ref.")
    
    
    def compose_model_dir(export_dir: Path, base_dir: Path, composed_dir: Path) -> Path:
        """One MiniMax-H3 model directory: distilled components from the export, the rest from the base."""
        composed_dir.mkdir(parents=True, exist_ok=True)
        for name in (*EXPORT_COMPONENTS, CONTRACT):
            _link(composed_dir / name, export_dir / name)
        manifest_source = select_manifest(export_dir, base_dir)
        for name in MANIFESTS:
            stale = composed_dir / name
            if name != manifest_source.name and stale.is_symlink():
                stale.unlink()
        _link(composed_dir / manifest_source.name, manifest_source)
        for name in BASE_COMPONENTS:
            _link(composed_dir / name, base_dir / name)
        return composed_dir
    
    
    def resolve_model(args: argparse.Namespace) -> tuple[Path, dict[str, Any]]:
        export_dir = _snapshot(args.model_path, args.revision,
                               [CONTRACT, *MANIFESTS, *(f"{name}/**" for name in EXPORT_COMPONENTS)])
        contract = load_contract(export_dir)
        if args.profile == "rtx-4090" and (export_dir / "transformer_ref" / "nvfp4_weights.safetensors").is_file():
            raise ValueError("rtx-4090 requires a dense or FP8 OmniRef export. The packed NVFP4 export omits "
                             "the weights needed for FP8 conversion; pass the dense/FP8 export with --model-path.")
        base_source, base_revision = base_model_source(args, contract)
        base_dir = _snapshot(base_source, base_revision, [*MANIFESTS, *(f"{name}/**" for name in BASE_COMPONENTS)])
        composed_dir = Path(args.composed_dir) if args.composed_dir else Path(args.output) / "fasth3_omniref_model"
        return compose_model_dir(export_dir, base_dir, composed_dir), contract
    
    
    def apply_lossless_accel_env() -> None:
        """Set LOSSLESS_ACCEL_ENV, keeping any value already in the environment."""
        for name, value in LOSSLESS_ACCEL_ENV.items():
            os.environ.setdefault(name, value)
    
    
    _CONSUMER_ENV = {
        # The checkpoint's trained attention backend; the contract fixes the tile size.
        "FASTVIDEO_ATTENTION_BACKEND": "VIDEO_SPARSE_ATTN_H3",
        # FP4 sparse attention on the consumer-Blackwell kernel, with the prefix split.
        "FASTVIDEO_H3_VSA_FP4": "1",
        "FASTVIDEO_H3_VSA_FP4_PREFIX": "fp8",
        # QAD trained the video rows with two-level P and K smoothing; match it.
        "FASTVIDEO_H3_VSA_FP4_TWO_LEVEL_P": "1",
        "FASTVIDEO_H3_VSA_FP4_K_SMOOTH": "1",
        # Bit-identical gate chunking; caps the 1.2 GiB transient at 768p10.
        "FASTVIDEO_H3_GATE_CHUNK_ROWS": "8192",
        # Bit-exact kernels, and none of the data-center-only routes.
        "FASTVIDEO_MINIMAX_H3_FUSIONS": "all",
        "FASTVIDEO_VSA_TRITON": "1",
        "FASTVIDEO_VSA_PTX_BLACKWELL": "0",
        "FASTVIDEO_FA4": "0",
    }
    
    
    @dataclass(frozen=True)
    class DeviceProfile:
        """Everything that differs between consumer devices for one OmniRef clip."""
    
        label: str
        width: int
        height: int
        offload: OffloadConfig
        env: dict[str, str]
        # Defer the denoise modules until the sampler needs them, for the cards that
        # cannot hold the text encoder and the DiT at once (the 24/32 GB recipes use it).
        sequential_load: bool = False
        # Linear quantization. sm_89 has no FP4 hardware, so the 4090 profile is the
        # closest equivalent rather than the FP4 stack, in the DiT and - because the
        # NVFP4 decoder's GEMMs need it too - in the VAE.
        transformer_quant: str = "NVFP4"
        layer_profile: str | None = "h3_dit_vsa"
        nvfp4_decoder: bool = True
    
    
    DEVICE_PROFILES: dict[str, DeviceProfile] = {
        "spark": DeviceProfile(
            label="NVIDIA DGX Spark (GB10, 128 GB unified)",
            width=832,
            height=480,
            # 128 GB unified holds the encoder, the DiT and the decoder at once:
            # the same resident policy as the released Spark recipe.
            offload=OffloadConfig(dit=False,
                                  dit_layerwise=False,
                                  text_encoder=False,
                                  vae=False,
                                  pin_cpu_memory=False,
                                  lazy_module_load=False),
            env={
                **_CONSUMER_ENV,
                # Byte-identical at both shapes and both decoders; the reference
                # memo saves 5-16% of warm wall time on repeated references.
                **LOSSLESS_ACCEL_ENV,
                # cuDNN mm_fp4 is 2.7-3x faster than CUTLASS on the H3 FFN shapes on GB10.
                "FASTVIDEO_NVFP4_MM_BACKEND": "cudnn",
                "FASTVIDEO_NVFP4_MM_ROW_SPLIT": "table",
                # The resident AdaLN per-timestep cache; it also gates the cross-block fused driver.
                "FASTVIDEO_H3_ADALN_CACHE": "1",
                "FASTVIDEO_H3_VAE_TILE_BATCH": "12",
                "FASTVIDEO_H3_VAE_INT8_OVERLAY": "0",
            },
        ),
        "rtx-pro-6000": DeviceProfile(
            label="NVIDIA RTX PRO 6000 (96 GB)",
            width=1344,
            height=768,
            # 96 GB fits the encoder, the DiT and the decoder at once.
            offload=OffloadConfig(dit=False,
                                  dit_layerwise=False,
                                  text_encoder=False,
                                  vae=False,
                                  pin_cpu_memory=True,
                                  lazy_module_load=False),
            env={**_CONSUMER_ENV, "FASTVIDEO_H3_VAE_TILE_BATCH": "8"},
        ),
        "rtx-5090": DeviceProfile(
            label="NVIDIA RTX 5090 (32 GB)",
            width=832,
            height=480,
            # The encoder is not resident, and the denoise modules load only when the
            # sampler needs them. The DiT itself stays whole: no layerwise streaming.
            offload=OffloadConfig(dit=False, dit_layerwise=False, text_encoder=True, vae=False, pin_cpu_memory=True),
            sequential_load=True,
            env={
                **_CONSUMER_ENV,
                # Bit-identical at both shapes and both decoders on the 5090; the
                # reference memo and VAE paths save 3-5 s on repeated requests.
                **LOSSLESS_ACCEL_ENV,
                "FASTVIDEO_H3_VAE_TILE_BATCH": "4",
            },
        ),
        "rtx-4090": DeviceProfile(
            label="NVIDIA RTX 4090 (24 GB, sm_89, no FP4)",
            width=832,
            height=480,
            # The 47 GB FP8 DiT cannot be resident on 24 GB: stream it, keeping the
            # validated 16 blocks resident. The encoder stays non-resident.
            offload=OffloadConfig(dit=False, dit_layerwise=True, text_encoder=True, vae=False, pin_cpu_memory=True),
            sequential_load=True,
            env={
                # No FP4 hardware: FP8 linears and bf16 VSA attention instead, and the
                # dense light VAE because the NVFP4 decoder's GEMMs need FP4 too.
                "FASTVIDEO_ATTENTION_BACKEND": "VIDEO_SPARSE_ATTN_H3",
                "FASTVIDEO_H3_VSA_FP4": "0",
                "FASTVIDEO_H3_VSA_FINE_ATTENTION": "emulator-bf16",
                "FASTVIDEO_MINIMAX_H3_FUSIONS": "all",
                "FASTVIDEO_VSA_TRITON": "1",
                "FASTVIDEO_VSA_PTX_BLACKWELL": "0",
                "FASTVIDEO_FA4": "0",
                # Validated 24 GB layerwise configuration: stream the packed weights
                # too, keep 16 blocks resident, and chunk the FFN.
                "FASTVIDEO_LAYERWISE_OFFLOAD_BUFFERS": "1",
                "FASTVIDEO_LAYERWISE_RESIDENT_BLOCKS": "16",
                "FASTVIDEO_H3_FFN_CHUNK_TOKENS": "16384",
                "FASTVIDEO_H3_PINNED_SWAP": "0",
                # A 24 GB card fragments easily once the DiT is streamed.
                "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
                "FASTVIDEO_H3_VAE_TILE_BATCH": "4",
            },
            transformer_quant="FP8",
            layer_profile=None,
            nvfp4_decoder=False,
        ),
    }
    
    
    def apply_attention_prefix(choice: str) -> None:
        """Apply ``--attention-prefix``; ``default`` keeps the profile's choice."""
        if choice != "default":
            os.environ["FASTVIDEO_H3_VSA_FP4_PREFIX"] = choice
    
    
    def apply_profile(profile: DeviceProfile, decoder: str | None, adaln_table: str | None = None) -> None:
        """Set a profile's environment, keeping any value already in the environment."""
        for name, value in profile.env.items():
            os.environ.setdefault(name, value)
        if decoder and profile.nvfp4_decoder:
            os.environ.setdefault("FASTVIDEO_H3_VAE_NVFP4_DECODER", decoder)
        elif decoder:
            print(f"--decoder ignored on {profile.label}: the NVFP4 decoder needs FP4 hardware; "
                  "this profile decodes with the VAE folder's own (dense) decoder")
        if adaln_table:
            # The AdaLN projections are a third of the DiT's bytes on disk; the
            # precomputed table drops them entirely. Every profile takes it: on the
            # 24/32 GB cards it is what makes residency possible, and elsewhere it
            # buys headroom for the reference tokens.
            os.environ.setdefault("FASTVIDEO_H3_ADALN_TABLE", adaln_table)
    
    
    def build_generator_config(model_dir: Path,
                               num_gpus: int,
                               lossless_accel: bool = False,
                               profile: DeviceProfile | None = None,
                               token_reduction: dict[str, Any] | None = None) -> GeneratorConfig:
        quantization = None
        if profile is not None:
            # `h3_dit_vsa` matches the packed export the consumer weights ship; the
            # export's metadata names its bf16 blocks, so no skip list is needed.
            quantization = QuantizationConfig(transformer_quant=profile.transformer_quant,
                                              layer_profile=profile.layer_profile)
            offload = profile.offload
            # Explicit: on unified memory the auto rule would defer the DiT and load
            # 50+ GB at the first denoise call even when everything fits.
            experimental = {"h3_sequential_load": profile.sequential_load}
            if num_gpus > 1:
                experimental.update({"vae_parallel_decode": True, "vae_parallel_encode": True})
        elif lossless_accel:
            # Resident encoders skip streaming the 63 GB text encoder (and the
            # VAEs) from host memory on every clip; pinned buffers copy the
            # decoded clip at full PCIe speed; the parallel VAE paths reassemble
            # the serial result exactly.
            offload = OffloadConfig(dit=False, dit_layerwise=False, text_encoder=False, vae=False, pin_cpu_memory=True)
            experimental = {"vae_parallel_decode": num_gpus > 1, "vae_parallel_encode": num_gpus > 1}
        else:
            offload = OffloadConfig(dit=False, dit_layerwise=False, text_encoder=True, vae=True, pin_cpu_memory=False)
            experimental = {}
        if token_reduction is not None:
            experimental["h3_token_reduction"] = dict(token_reduction)
        return GeneratorConfig(
            model_path=str(model_dir),
            engine=EngineConfig(
                num_gpus=num_gpus,
                # Multi-GPU device profiles run on Ray (the Spark pair spans two hosts).
                execution_backend="ray" if num_gpus > 1 and profile is not None else "mp",
                # A packed NVFP4 export is replicated across GPUs; the tokens are split
                # by sequence parallelism. Data-center checkpoints keep mp and FSDP.
                use_fsdp_inference=num_gpus > 1 and profile is None,
                parallelism=ParallelismConfig(tp_size=1, sp_size=num_gpus),
                offload=offload,
                quantization=quantization,
                # The NVFP4 decoder installs its own fused CUDA graphs; compiling the VAE
                # on top trips an inductor cudagraph assertion at 768p with the 36-block student.
                compile=CompileConfig(),
            ),
            pipeline=PipelineSelection(
                workload_type="i2v",
                # FastVideo reads the trained fused-block partition and attention
                # settings from the composed directory's fastvideo_inference.json.
                components=ComponentConfig(override_pipeline_cls_name="MiniMaxH3Ref2VAModularPipeline"),
                vae_tiling=profile is not None,
                experimental={
                    **experimental, "video_decode_backend": "h3-vae"
                } if profile is not None else experimental,
            ),
        )
    
    
    def main() -> None:
        args = parse_args()
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
        model_dir, contract = resolve_model(args)
        print(f"Composed model directory: {model_dir}")
        print(f"Contract: {contract['num_inference_steps']} fused blocks of a {contract['pdd_steps']}-interval grid, "
              f"{contract['attention_backend']} with sparsity {contract['vsa_sparsity']}, "
              f"{contract['vsa_tile_size']}-token tiles, reference keep rate {contract['vsa_ref_keep_rate']}")
        references = [MiniMaxH3Reference(source=path, media_type=kind) for kind, path in args.references]
    
        profile = DEVICE_PROFILES[args.profile] if args.profile else None
        if profile is not None:
            apply_profile(profile, args.decoder, args.adaln_table)
            print(f"Profile: {profile.label}")
        elif args.lossless_accel:
            apply_lossless_accel_env()
        apply_attention_prefix(args.attention_prefix)
        if args.width is None:
            args.width = profile.width if profile is not None else DEFAULT_WIDTH
        if args.height is None:
            args.height = profile.height if profile is not None else DEFAULT_HEIGHT
        generator = VideoGenerator.from_config(
            build_generator_config(model_dir, args.num_gpus, args.lossless_accel, profile, token_reduction_options(args)))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt="",
                    inputs=InputConfig(references=references),
                    sampling=SamplingConfig(
                        height=args.height,
                        width=args.width,
                        num_frames=args.num_frames,
                        fps=24,
                        # PDD counts fused blocks: one transformer forward each.
                        num_inference_steps=contract["num_inference_steps"],
                        guidance_scale=1.0,
                        batch_cfg=False,
                        seed=args.seed,
                    ),
                    output=OutputConfig(
                        output_path=str(output_dir / "fasth3_omniref_pdd.mp4"),
                        save_video=True,
                        return_frames=False,
                    ),
                ))
            print(f"Output written to: {result.video_path}")
            if result.generation_time is not None:
                print(f"Generation time: {result.generation_time:.1f} s")
            if result.peak_memory_mb is not None:
                print(f"Peak GPU memory allocated (rank 0): {result.peak_memory_mb / 1024:.1f} GiB")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_omniref_rtx4090.yaml"

    ```yaml
    # FastH3 OmniRef (Ref2VA) on one RTX 4090 (24 GB, no FP4): the FP8/bf16 equivalent, one clip per prompt.
    #
    # Point model_path at a composed OmniRef model directory: the distilled
    # dense or FP8 transformer_ref export (without nvfp4_weights.safetensors) symlinked
    # together with base MiniMax-H3's text_encoder, tokenizer, processor, vae and
    # audio_vae. examples/inference/basic/basic_fasth3_omniref_pdd.py builds that
    # directory and runs it with --profile rtx-4090.
    #
    # The contract in the export's fastvideo_inference.json fixes the attention
    # backend, the VSA tile size and the eight-forward PDD partition; the run only
    # picks the device's offload policy and its environment:
    #
    # sm_89 has no FP4 hardware, so this profile is the closest equivalent rather than
    # the FP4 stack: FP8 linears, bf16 VSA attention, the dense light VAE decoder (the
    # NVFP4 one needs FP4 hardware too), a non-resident encoder and expandable segments
    # to reduce memory fragmentation. Layerwise offload is mandatory: the 47 GB FP8
    # DiT cannot be resident on 24 GB. Run one process per clip; repeated requests in
    # one process exceed the 24 GB GPU and the host cgroup when the encoder reloads.
    #
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    # FASTVIDEO_H3_VSA_FP4=0 \
    # FASTVIDEO_H3_VSA_FINE_ATTENTION=emulator-bf16 \
    # FASTVIDEO_LAYERWISE_OFFLOAD_BUFFERS=1 \
    # FASTVIDEO_LAYERWISE_RESIDENT_BLOCKS=16 \
    # FASTVIDEO_H3_FFN_CHUNK_TOKENS=16384 \
    # FASTVIDEO_H3_PINNED_SWAP=0 \
    # PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
    # FASTVIDEO_H3_ADALN_TABLE=/path/to/adaln_table.pt \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_omniref_rtx4090.yaml
    #
    # See docs/inference/fasth3_omniref.md.
    generator:
      model_path: ./FastH3-OmniRef-Dense-Composed
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: FP8
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: true
          text_encoder: true
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
      pipeline:
        workload_type: i2v
        components:
          override_pipeline_cls_name: MiniMaxH3Ref2VAModularPipeline
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          video_decode_backend: h3-vae
          h3_sequential_load: true
    request:
      prompt: >-
        A person on a sofa, lit by a warm lamp, speaking to camera.
      negative_prompt: ""
      inputs:
        references:
          # Ordered: the clip is conditioned on these. Replace with your own media.
          - source: assets/images/couple.jpg
            media_type: image
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 8  # eight fused PDD blocks; the contract sets it
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/basic_fasth3_omniref_rtx4090/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_omniref_rtx5090.yaml"

    ```yaml
    # FastH3 OmniRef (Ref2VA) on one RTX 5090 (32 GB): the full NVFP4 stack, one clip per prompt.
    #
    # Point model_path at a composed OmniRef model directory: the distilled
    # transformer_ref export (with its packed nvfp4_weights.safetensors) symlinked
    # together with base MiniMax-H3's text_encoder, tokenizer, processor, vae and
    # audio_vae. examples/inference/basic/basic_fasth3_omniref_pdd.py builds that
    # directory and runs the same stack with --profile rtx-5090.
    #
    # The contract in the export's fastvideo_inference.json fixes the attention
    # backend, the VSA tile size and the eight-forward PDD partition; the run only
    # picks the device's offload policy and its environment:
    #
    # 32 GB: the text encoder stays off the GPU, the denoise modules load on demand and
    # the AdaLN table replaces adaln_proj. The DiT itself stays whole - no layerwise streaming.
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_H3_VSA_FP4_PREFIX=fp8 \
    # FASTVIDEO_H3_VSA_FP4_TWO_LEVEL_P=1 FASTVIDEO_H3_VSA_FP4_K_SMOOTH=1 \
    # FASTVIDEO_H3_GATE_CHUNK_ROWS=8192 \
    # FASTVIDEO_ULYSSES_A2A=auto FASTVIDEO_MINIMAX_H3_EXACT_KERNELS=all \
    # FASTVIDEO_H3_VSA_HEADS_FIRST_TILE=1 FASTVIDEO_H3_VAE_TILE_PARALLEL=1 \
    # FASTVIDEO_H3_REF2VA_MEMO_ENTRIES=16 \
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_H3_ADALN_TABLE=/path/to/adaln_table.pt \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=/path/to/decoder-nvfp4.safetensors \
    # FASTVIDEO_H3_VAE_TILE_BATCH=4 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_omniref_rtx5090.yaml
    #
    # See docs/inference/fasth3_omniref.md.
    generator:
      model_path: ./FastH3-OmniRef-Composed
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: true
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
      pipeline:
        workload_type: i2v
        components:
          override_pipeline_cls_name: MiniMaxH3Ref2VAModularPipeline
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
          video_decode_backend: h3-vae
          h3_sequential_load: true
    request:
      prompt: >-
        A person on a sofa, lit by a warm lamp, speaking to camera.
      negative_prompt: ""
      inputs:
        references:
          # Ordered: the clip is conditioned on these. Replace with your own media.
          - source: assets/images/couple.jpg
            media_type: image
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 8  # eight fused PDD blocks; the contract sets it
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/basic_fasth3_omniref_rtx5090/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_omniref_rtx_pro6000.yaml"

    ```yaml
    # FastH3 OmniRef (Ref2VA) on one RTX PRO 6000 (96 GB): the full NVFP4 stack, one clip per prompt.
    #
    # Point model_path at a composed OmniRef model directory: the distilled
    # transformer_ref export (with its packed nvfp4_weights.safetensors) symlinked
    # together with base MiniMax-H3's text_encoder, tokenizer, processor, vae and
    # audio_vae. examples/inference/basic/basic_fasth3_omniref_pdd.py builds that
    # directory and runs the same stack with --profile rtx-pro-6000.
    #
    # The contract in the export's fastvideo_inference.json fixes the attention
    # backend, the VSA tile size and the eight-forward PDD partition; the run only
    # picks the device's offload policy and its environment. 96 GB fits the encoder,
    # the DiT and the decoder at once.
    #
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_H3_VSA_FP4_PREFIX=fp8 \
    # FASTVIDEO_H3_VSA_FP4_TWO_LEVEL_P=1 FASTVIDEO_H3_VSA_FP4_K_SMOOTH=1 \
    # FASTVIDEO_H3_GATE_CHUNK_ROWS=8192 \
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_H3_ADALN_TABLE=/path/to/adaln_table.pt \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=/path/to/decoder-nvfp4.safetensors \
    # FASTVIDEO_H3_VAE_TILE_BATCH=8 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_omniref_rtx_pro6000.yaml
    #
    # See docs/inference/fasth3_omniref.md.
    generator:
      model_path: ./FastH3-OmniRef-Composed
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          vae: false
          pin_cpu_memory: true
          lazy_module_load: false
      pipeline:
        workload_type: i2v
        components:
          override_pipeline_cls_name: MiniMaxH3Ref2VAModularPipeline
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
          video_decode_backend: h3-vae
          h3_sequential_load: false
    request:
      prompt: >-
        A person on a sofa, lit by a warm lamp, speaking to camera.
      negative_prompt: ""
      inputs:
        references:
          # Ordered: the clip is conditioned on these. Replace with your own media.
          - source: assets/images/couple.jpg
            media_type: image
      sampling:
        seed: 1234
        height: 768
        width: 1344
        num_frames: 124
        fps: 24
        num_inference_steps: 8  # eight fused PDD blocks; the contract sets it
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/basic_fasth3_omniref_rtx_pro6000/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_omniref_spark.yaml"

    ```yaml
    # FastH3 OmniRef (Ref2VA) on one DGX Spark (GB10, unified memory): the full NVFP4 stack, one clip per prompt.
    #
    # Point model_path at a composed OmniRef model directory: the distilled
    # transformer_ref export (with its packed nvfp4_weights.safetensors) symlinked
    # together with base MiniMax-H3's text_encoder, tokenizer, processor, vae and
    # audio_vae. examples/inference/basic/basic_fasth3_omniref_pdd.py builds that
    # directory and runs the same stack with --profile spark.
    #
    # The contract in the export's fastvideo_inference.json fixes the attention
    # backend, the VSA tile size and the eight-forward PDD partition; the run only
    # picks the device's offload policy and its environment:
    #
    # GB10: everything stays resident; cuDNN mm_fp4 and the dense batched decoder.
    # FASTVIDEO_H3_ADALN_CACHE=1 keeps the resident per-timestep AdaLN cache (exact, no file needed).
    # FASTVIDEO_H3_VSA_PREFIX_DENSE_FP4=1 is optional and approximate: dense NVFP4 prefix attention,
    # 131.0 -> 94.8 s per Omni clip (1.38x) at 20.5-23.7 dB frames vs the exact run.
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_H3_VSA_FP4_PREFIX=fp8 \
    # FASTVIDEO_H3_VSA_FP4_TWO_LEVEL_P=1 FASTVIDEO_H3_VSA_FP4_K_SMOOTH=1 \
    # FASTVIDEO_H3_GATE_CHUNK_ROWS=8192 \
    # FASTVIDEO_ULYSSES_A2A=auto FASTVIDEO_MINIMAX_H3_EXACT_KERNELS=all \
    # FASTVIDEO_H3_VSA_HEADS_FIRST_TILE=1 FASTVIDEO_H3_VAE_TILE_PARALLEL=1 \
    # FASTVIDEO_H3_REF2VA_MEMO_ENTRIES=16 \
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_H3_ADALN_CACHE=1 \
    # FASTVIDEO_H3_VSA_PREFIX_DENSE_FP4=1 \
    # FASTVIDEO_H3_ADALN_TABLE=/path/to/adaln_table.pt \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=/path/to/decoder-nvfp4.safetensors \
    # FASTVIDEO_NVFP4_MM_BACKEND=cudnn FASTVIDEO_NVFP4_MM_ROW_SPLIT=table \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_omniref_spark.yaml
    #
    # See docs/inference/fasth3_omniref.md.
    generator:
      model_path: ./FastH3-OmniRef-Composed
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
      pipeline:
        workload_type: i2v
        components:
          override_pipeline_cls_name: MiniMaxH3Ref2VAModularPipeline
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
          video_decode_backend: h3-vae
          h3_sequential_load: false
    request:
      prompt: >-
        A person on a sofa, lit by a warm lamp, speaking to camera.
      negative_prompt: ""
      inputs:
        references:
          # Ordered: the clip is conditioned on these. Replace with your own media.
          - source: assets/images/couple.jpg
            media_type: image
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 8  # eight fused PDD blocks; the contract sets it
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/basic_fasth3_omniref_spark/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_omniref_spark_pair.yaml"

    ```yaml
    # FastH3 OmniRef (Ref2VA) across two DGX Sparks over QSFP RoCE, eight fused PDD
    # forwards per clip. Start Ray on both Sparks and source
    # examples/inference/optimizations/spark_pair_env.sh first; see
    # docs/getting_started/installation/spark_pair.md.
    #
    # Point model_path at a composed OmniRef model directory (see
    # basic_fasth3_omniref_pdd.py): the distilled transformer_ref export, with its
    # packed nvfp4_weights.safetensors, symlinked with base MiniMax-H3's encoder,
    # tokenizer, processor and VAEs.
    #
    # GB10 uses Triton VSA. The two nodes share the sequence (sp_size 2), which is
    # the only split this pipeline has: H3 generates a clip at a time, so there is
    # no depth to pipeline. The FP8 prefix split runs on the sequence-parallel path
    # too: prefix rows stay dense and video rows stay on the FP4 kernel.
    #
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_H3_VSA_FP4_PREFIX=fp8 \
    # FASTVIDEO_H3_VSA_FP4_TWO_LEVEL_P=1 FASTVIDEO_H3_VSA_FP4_K_SMOOTH=1 \
    # FASTVIDEO_H3_GATE_CHUNK_ROWS=8192 \
    # FASTVIDEO_ULYSSES_A2A=auto FASTVIDEO_MINIMAX_H3_EXACT_KERNELS=all \
    # FASTVIDEO_H3_VSA_HEADS_FIRST_TILE=1 FASTVIDEO_H3_VAE_TILE_PARALLEL=1 \
    # FASTVIDEO_H3_REF2VA_MEMO_ENTRIES=16 \
    # FASTVIDEO_NVFP4_MM_BACKEND=cudnn \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_H3_ADALN_TABLE=/path/to/adaln_table.pt \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=/path/to/decoder-nvfp4.safetensors \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_omniref_spark_pair.yaml
    #
    # See docs/inference/fasth3_omniref.md.
    generator:
      model_path: ./FastH3-OmniRef-Composed
      engine:
        num_gpus: 2
        execution_backend: ray
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 2
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        workload_type: i2v
        components:
          override_pipeline_cls_name: MiniMaxH3Ref2VAModularPipeline
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
          vae_parallel_decode: true
          vae_parallel_encode: true
          video_decode_backend: h3-vae
    request:
      prompt: >-
        A person on a sofa, lit by a warm lamp, speaking to camera.
      negative_prompt: ""
      inputs:
        references:
          # Ordered: the clip is conditioned on these. Replace with your own media.
          - source: assets/images/couple.jpg
            media_type: image
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 8  # eight fused PDD blocks; the contract sets it
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_omniref_spark_pair/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_simplified.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate 5-second FastH3 videos with a supported Preview adapter."""
    
    from __future__ import annotations
    
    import argparse
    import os
    import statistics
    import sys
    import time
    from pathlib import Path
    
    from huggingface_hub import hf_hub_download
    
    FASTVIDEO_ROOT = Path(__file__).resolve().parents[3]
    sys.path.insert(0, str(FASTVIDEO_ROOT))
    
    from fastvideo import VideoGenerator  # noqa: E402
    from fastvideo.api import (  # noqa: E402
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    # FastVideo exposes these three backend switches only through environment variables.
    os.environ.update({
        "FASTVIDEO_FA4": "1",
        "FASTVIDEO_MINIMAX_H3_FUSIONS": "all",
        "FASTVIDEO_VSA_PTX_BLACKWELL": "0",
    })
    os.environ.pop("FASTVIDEO_INFERENCE_TORCH_COMPILE", None)
    
    VARIANT_BACKENDS = {
        "dense-datafree": "FLASH_ATTN",
        "vsa-datafree": "VIDEO_SPARSE_ATTN_H3",
        "vsa-synthetic-step1300": "VIDEO_SPARSE_ATTN_H3",
        "vsa-synthetic-step1900": "VIDEO_SPARSE_ATTN_H3",
    }
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("variant", choices=VARIANT_BACKENDS)
        parser.add_argument("--prompt", required=True)
        return parser.parse_args()
    
    
    def main() -> None:
        """Run one compile warmup and three measured generations with one fixed recipe."""
        args = parse_args()
    
        attention_backend = VARIANT_BACKENDS[args.variant]
        experimental = {
            "attention_backend": attention_backend,
            "inference_torch_compile": attention_backend == "FLASH_ATTN",
            "vae_parallel_decode": True,
            "vae_parallel_decode_strategy": "gather",
        }
        if attention_backend == "VIDEO_SPARSE_ATTN_H3":
            experimental.update({
                "VSA_sparsity": 0.9,
                "VSA_tile_size": 64,
            })
    
        adapter_path = hf_hub_download(
            repo_id="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA",
            filename=f"{args.variant}/adapter_model.safetensors",
        )
        output_dir = FASTVIDEO_ROOT / "outputs/fasth3_lora_preview" / args.variant
        output_dir.mkdir(parents=True, exist_ok=True)
    
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path="MiniMaxAI/MiniMax-H3",
                pipeline=PipelineSelection(
                    components=ComponentConfig(lora_path=adapter_path, lora_strength=1.0),
                    experimental=experimental,
                ),
                engine=EngineConfig(
                    num_gpus=4,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=4),
                    offload=OffloadConfig(dit=False, dit_layerwise=False),
                    compile=CompileConfig(vae_enabled=True),
                ),
            )
        )
    
        generation_count = 4
        warmup_count = 1
        measured_count = generation_count - warmup_count
        measured_seconds: list[float] = []
    
        print(f"Variant: {args.variant} ({attention_backend})")
        print(f"Output directory: {output_dir}")
        try:
            for generation_index in range(generation_count):
                measured = generation_index >= warmup_count
                if measured:
                    measured_index = generation_index - warmup_count + 1
                    label = f"measured {measured_index}/{measured_count}"
                    output_path = output_dir / f"fasth3_all_run_{measured_index:02d}.mp4"
                else:
                    warmup_index = generation_index + 1
                    label = f"warmup {warmup_index}/{warmup_count}"
                    output_path = output_dir / f"_fasth3_warmup_{warmup_index:02d}.mp4"
    
                request = GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt="",
                    sampling=SamplingConfig(
                        height=768,
                        width=1344,
                        num_frames=345, # <-- Change video length: 5sec: 124; 10sec: 243; 15sec: 345.
                        fps=24,
                        num_inference_steps=5,
                        guidance_scale=1.0,
                        batch_cfg=False,
                        seed=1000,
                    ),
                    output=OutputConfig(
                        output_path=str(output_path),
                        save_video=True,
                        return_frames=False,
                    ),
                )
                started = time.perf_counter()
                result = generator.generate(request)
                elapsed = time.perf_counter() - started
                if measured:
                    measured_seconds.append(elapsed)
                suffix = "" if measured else " (excluded from median)"
                print(f"[{label}] {result.video_path or output_path}: {elapsed:.3f}s{suffix}")
        finally:
            generator.shutdown()
    
        print(f"Median E2E wall time: {statistics.median(measured_seconds):.3f}s")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_simplified.sh"

    ```sh
    #!/usr/bin/env bash
    
    PROMPT="integrated_multimodal_description: A red fox runs through fresh snow at dawn. overall_soundscape: Fast pawsteps in snow, winter wind, and distant birds."
    
    # Options: dense-datafree, vsa-datafree, vsa-synthetic-step1300, vsa-synthetic-step1900
    VARIANT="vsa-datafree"
    
    exec python "$(dirname "$0")/basic_fasth3_simplified.py" \
      "$VARIANT" \
      --prompt "$PROMPT"
    
    ```

??? note "basic_fasth3_simplified_profile.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Profile one FastH3 Preview generation with NVTX after warmup."""
    
    from __future__ import annotations
    
    import argparse
    from pathlib import Path
    
    import torch
    from huggingface_hub import hf_hub_download
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        QuantizationConfig,
        SamplingConfig,
    )
    from fastvideo.profiler import nvtx_range
    
    VARIANT_BACKENDS = {
        "dense-datafree": "FLASH_ATTN",
        "vsa-datafree": "VIDEO_SPARSE_ATTN_H3",
        "vsa-synthetic-step1300": "VIDEO_SPARSE_ATTN_H3",
        "vsa-synthetic-step1900": "VIDEO_SPARSE_ATTN_H3",
    }
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("variant", choices=VARIANT_BACKENDS)
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", required=True)
        parser.add_argument("--num-frames", type=int, default=345)
        parser.add_argument("--warmup-runs", type=int, default=3)
        return parser.parse_args()
    
    
    def main() -> None:
        """Warm the selected FastH3 recipe, then profile one identical generation."""
        args = parse_args()
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
    
        attention_backend = VARIANT_BACKENDS[args.variant]
        experimental = {
            "attention_backend": attention_backend,
            "inference_torch_compile": attention_backend == "FLASH_ATTN",
            "vae_parallel_decode": True,
            "vae_parallel_decode_strategy": "gather",
        }
        if attention_backend == "VIDEO_SPARSE_ATTN_H3":
            experimental.update({
                "VSA_sparsity": 0.9,
                "VSA_tile_size": 64,
            })
    
        adapter_path = hf_hub_download(
            repo_id="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA",
            filename=f"{args.variant}/adapter_model.safetensors",
        )
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path="MiniMaxAI/MiniMax-H3",
                pipeline=PipelineSelection(
                    components=ComponentConfig(lora_path=adapter_path, lora_strength=1.0),
                    experimental=experimental,
                ),
                engine=EngineConfig(
                    num_gpus=4,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=4),
                    offload=OffloadConfig(dit=False, dit_layerwise=False),
                    compile=CompileConfig(vae_enabled=True),
                    quantization=QuantizationConfig(transformer_quant="MXFP8"),
                ),
            )
        )
    
        request = GenerationRequest(
            prompt=args.prompt,
            negative_prompt="",
            sampling=SamplingConfig(
                height=768,
                width=1344,
                num_frames=args.num_frames,
                fps=24,
                num_inference_steps=5,
                guidance_scale=1.0,
                batch_cfg=False,
                seed=1000,
            ),
            output=OutputConfig(
                output_path=str(output_dir / "fasth3_profile.mp4"),
                save_video=True,
                return_frames=False,
            ),
        )
    
        try:
            for warmup_index in range(args.warmup_runs):
                warmup_result = generator.generate(request)
                print(f"Warmup {warmup_index + 1}/{args.warmup_runs}: {warmup_result.video_path}")
    
            torch.cuda.profiler.start()
            try:
                with nvtx_range("fasth3.profiled_generation"):
                    measured_result = generator.generate(request)
            finally:
                torch.cuda.profiler.stop()
    
            print(f"Profiled output: {measured_result.video_path}")
            if measured_result.generation_time is not None:
                print(f"Generation time: {measured_result.generation_time:.2f}s")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_fasth3_simplified_profile.sh"

    ```sh
    #!/usr/bin/env bash
    # Capture one FastH3 Preview generation with CUDA and FastVideo NVTX ranges.
    
    set -euo pipefail
    
    SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
    WORKTREE_ROOT="$(cd -- "${SCRIPT_DIR}/../../.." && pwd)"
    WORKSPACE_ROOT="$(cd -- "${WORKTREE_ROOT}/.." && pwd)"
    PYTHON_BIN="${WORKSPACE_ROOT}/.venv-fv/bin/python"
    NSYS_BIN=/usr/local/cuda/bin/nsys
    PROFILE_SCRIPT="${SCRIPT_DIR}/basic_fasth3_simplified_profile.py"
    
    export CUDA_VISIBLE_DEVICES=0,1,2,3
    export FASTVIDEO_FA4=1
    export FASTVIDEO_INFERENCE_TORCH_COMPILE=0
    export FASTVIDEO_MINIMAX_H3_FUSIONS=all
    export FASTVIDEO_NVTX_PROFILE=1
    export FASTVIDEO_VSA_PTX_BLACKWELL=0
    export PYTHONUNBUFFERED=1
    export PYTHONPATH="${WORKTREE_ROOT}${PYTHONPATH:+:${PYTHONPATH}}"
    
    PROMPT="integrated_multimodal_description: A red fox runs through fresh snow at dawn. overall_soundscape: Fast pawsteps in snow, winter wind, and distant birds."
    
    # Options: dense-datafree, vsa-datafree, vsa-synthetic-step1300, vsa-synthetic-step1900
    VARIANT="vsa-datafree"
    NUM_FRAMES=345
    WARMUP_RUNS=3
    
    PROFILE_ID="${VARIANT}_4gpu_sp4_${NUM_FRAMES}frames"
    RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$"
    RESULT_DIR="${WORKTREE_ROOT}/runs/fasth3_lora_preview_profile/${PROFILE_ID}/${RUN_ID}"
    MEDIA_DIR="${RESULT_DIR}/media"
    RUN_LOG="${RESULT_DIR}/run.log"
    mkdir -p "${MEDIA_DIR}"
    
    "${NSYS_BIN}" profile \
      --trace=cuda,nvtx \
      --sample=none \
      --cpuctxsw=none \
      --capture-range=cudaProfilerApi \
      --capture-range-end=stop \
      --output="${RESULT_DIR}/${PROFILE_ID}" \
      "${PYTHON_BIN}" "${PROFILE_SCRIPT}" \
      "${VARIANT}" \
      --num-frames "${NUM_FRAMES}" \
      --warmup-runs "${WARMUP_RUNS}" \
      --prompt "${PROMPT}" \
      --output "${MEDIA_DIR}" \
      2>&1 | tee "${RUN_LOG}"
    
    printf 'RESULT_DIR=%s\n' "${RESULT_DIR}"
    printf 'NSYS_REPORT=%s\n' "${RESULT_DIR}/${PROFILE_ID}.nsys-rep"
    printf 'MEDIA_DIR=%s\n' "${MEDIA_DIR}"
    
    ```

??? note "basic_fasth3_spark.yaml"

    ```yaml
    # FastH3 on one DGX Spark (one GB10). Install: docs/getting_started/installation/spark.md
    #
    # GB10 has no FA4 / ptx_blackwell VSA kernel. Keep the env prefix below, or pass
    # equivalent CLI flags on examples/inference/basic/basic_fasth3.py
    # (`--vsa-kernel triton --no-fa4 --num-gpus 1`).
    #
    # request.sampling below is an example, not a required recipe. Change height,
    # width, num_frames, num_inference_steps, seed, and prompt. Legal H3 frame
    # counts are 17n+5, max 345 (15 s). Native 16:9 sizes include 832x480 and
    # 1344x768. 1024x576 is a common recipe-matched 16:9.
    #
    #   FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    #     FASTVIDEO_STAGE_LOGGING=1 \
    #     fastvideo generate --config examples/inference/basic/basic_fasth3_spark.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-4-step-Preview-v1-VSA-DataFree
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: true
          vae: true
          pin_cpu_memory: true
          lazy_module_load: true
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          VSA_sparsity: 0.9
          VSA_tile_size: 64
          inference_torch_compile: true
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
    request:
      prompt: >-
        A wide cinematic shot of an alpine meadow at sunrise, pale pink mountain
        peaks above a blue valley filled with thin morning mist.
      negative_prompt: ""
      sampling:
        seed: 2026
        height: 768
        width: 1344
        num_frames: 124
        fps: 24
        num_inference_steps: 5
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_pair.yaml"

    ```yaml
    # FastH3 on two DGX Sparks (one GPU each) over QSFP RoCE.
    # Bring up the Ray cluster first: docs/getting_started/installation/spark_pair.md
    #
    # request.sampling below is an example, not a required recipe. Change height,
    # width, num_frames, num_inference_steps, seed, and prompt. Legal H3 frame
    # counts are 17n+5, max 345 (15 s).
    #
    #   source examples/inference/optimizations/spark_pair_env.sh
    #   export RAY_ADDRESS=<qsfp-head>:6379
    #   export FASTVIDEO_HOST_IP=<qsfp-head>
    #   FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 \
    #     FASTVIDEO_VAE_PARALLEL_DECODE=1 FASTVIDEO_STAGE_LOGGING=1 \
    #     fastvideo generate --config examples/inference/basic/basic_fasth3_spark_pair.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-4-step-Preview-v1-VSA-DataFree
      engine:
        num_gpus: 2
        execution_backend: ray
        use_fsdp_inference: false
        parallelism:
          tp_size: 1
          sp_size: 2
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: true
          vae: true
          pin_cpu_memory: true
          lazy_module_load: true
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          VSA_sparsity: 0.9
          VSA_tile_size: 64
          inference_torch_compile: true
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
    request:
      prompt: >-
        A wide cinematic shot of an alpine meadow at sunrise, pale pink mountain
        peaks above a blue valley filled with thin morning mist.
      negative_prompt: ""
      sampling:
        seed: 2026
        height: 768
        width: 1344
        num_frames: 124
        fps: 24
        num_inference_steps: 5
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_pair/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_pair_pruned_nvfp4.yaml"

    ```yaml
    # Start Ray on both Sparks and source spark_pair_env.sh first; see spark_pair.md.
    # FastH3 Trim eight-forward video+audio on two DGX Sparks over QSFP RoCE.
    # Download the complete checkpoint, including its trained schedule, as described in
    # docs/getting_started/installation/spark_performance.md.
    #
    # GB10 uses Triton VSA. The release packs attention, FFN and VSA gate weights.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    #
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cutlass \
    # FASTVIDEO_H3_VAE_TILE_BATCH=1 \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_pair_pruned_nvfp4.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-Trim-8-Step-NVFP4
      engine:
        num_gpus: 2
        execution_backend: ray
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 2
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: false
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_pair_pruned_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_pair_qad_v2_nvfp4.yaml"

    ```yaml
    # Start Ray on both Sparks and source spark_pair_env.sh first; see spark_pair.md.
    # FastH3-QAD-v2 eight-forward video+audio on two DGX Sparks over QSFP RoCE.
    # Uses the published fast-8L NVFP4 decoder on both workers (FASTVIDEO_H3_VAE_NVFP4_DECODER) with parallel temporal chunks.
    # Download the complete release checkpoint as described in
    # docs/getting_started/installation/spark_performance.md.
    # Download the fast-8L decoder the command below selects:
    # hf download FastVideo/FastH3-NVFP4-VAE-Decoder --include 'fast-8L/decoder-nvfp4.safetensors' --local-dir /path/to/fasth3-nvfp4-vae
    # Run it on both Sparks with the same absolute path: each worker loads the decoder itself.
    #
    # FP4 attention needs fastvideo-kernel built for 12.1a and eager DiT inference.
    # A missing extension is an error. Set h3_vsa_fp4.enabled to false for BF16 VSA.
    # FastH3-QAD-v2 retains its trained 64-token VSA layout. The protected FP4 attention
    # settings below are an inference choice, not its linears-only QAD recipe.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    #
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cudnn FASTVIDEO_NVFP4_MM_ROW_SPLIT=table \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=/path/to/fasth3-nvfp4-vae/fast-8L/decoder-nvfp4.safetensors \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_pair_qad_v2_nvfp4.yaml
    generator:
      model_path: FastVideo/FastH3-QAD-v2
      engine:
        num_gpus: 2
        execution_backend: ray
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 2
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: false  # Published NVFP4 decoder uses its fused eager inference path.
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
            sp_head_chunks: 7
            sp_pooled_key_mean: true
            sp_direct_keys: true
            sp_projection_overlap: true
            sp_input_gather: true
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_pair_qad_v2_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_pair_v2_nvfp4.yaml"

    ```yaml
    # Start Ray on both Sparks and source spark_pair_env.sh first; see spark_pair.md.
    # FastH3 V2 eight-forward video+audio on two DGX Sparks over QSFP RoCE.
    # Download the complete release checkpoint as described in
    # docs/getting_started/installation/spark_performance.md.
    #
    # FP4 attention needs fastvideo-kernel built for 12.1a and eager DiT inference.
    # A missing extension is an error. Set h3_vsa_fp4.enabled to false for BF16 VSA.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    #
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cutlass \
    # FASTVIDEO_H3_VAE_TILE_BATCH=1 \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_pair_v2_nvfp4.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-8-Step-V2-NVFP4-Consumer
      engine:
        num_gpus: 2
        execution_backend: ray
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 2
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: false
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: true
          vae_parallel_decode_strategy: gather
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_pair_v2_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_pruned_nvfp4.yaml"

    ```yaml
    # FastH3 Trim eight-forward video+audio on one DGX Spark.
    # Download the complete checkpoint, including its trained schedule, as described in
    # docs/getting_started/installation/spark_performance.md.
    #
    # GB10 uses Triton VSA. The release packs attention, FFN and VSA gate weights.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    # The VAE decodes with its dense weights, 12 tiles per call and a compiled
    # decoder: on GB10 the INT8 ConvRot overlay is slower and less accurate.
    # NVFP4 GEMMs use FlashInfer's cuDNN backend, 2-3x faster than CUTLASS on the
    # H3 FFN shapes on GB10 with identical outputs.
    # Optional, off by default: FASTVIDEO_H3_VSA_FP4=1 runs VSA on the FP4 attention kernel
    # (fastvideo-kernel built for 12.1a). It is faster but changes the output for now;
    # see spark_performance.md.
    #
    # FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cudnn \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_pruned_nvfp4.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-Trim-8-Step-NVFP4
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: false
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_pruned_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_qad_v2_nvfp4.yaml"

    ```yaml
    # FastH3-QAD-v2 eight-forward video+audio on one DGX Spark.
    # Uses the published fast-8L NVFP4 decoder selected with FASTVIDEO_H3_VAE_NVFP4_DECODER (see spark_performance.md).
    # Download the complete release checkpoint as described in
    # docs/getting_started/installation/spark_performance.md.
    # Download the fast-8L decoder the command below selects:
    # hf download FastVideo/FastH3-NVFP4-VAE-Decoder --include 'fast-8L/decoder-nvfp4.safetensors' --local-dir ./fasth3-nvfp4-vae
    #
    # FP4 attention needs fastvideo-kernel built for 12.1a and eager DiT inference.
    # A missing extension is an error. Set h3_vsa_fp4.enabled to false for BF16 VSA.
    # FastH3-QAD-v2 retains its trained 64-token VSA layout. The protected FP4 attention
    # settings below are an inference choice, not its linears-only QAD recipe.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    #
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cudnn FASTVIDEO_NVFP4_MM_ROW_SPLIT=table FASTVIDEO_H3_ADALN_CACHE=1 \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # FASTVIDEO_H3_VAE_NVFP4_DECODER=./fasth3-nvfp4-vae/fast-8L/decoder-nvfp4.safetensors \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_qad_v2_nvfp4.yaml
    generator:
      model_path: FastVideo/FastH3-QAD-v2
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: false  # Packed NVFP4 decoder has its own fused inference path.
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
            prefix_precision: fp8
            two_level_p: true
            smooth_k: true
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: false
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_qad_v2_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_spark_v2_nvfp4.yaml"

    ```yaml
    # FastH3 V2 eight-forward video+audio on one DGX Spark.
    # Download the complete release checkpoint as described in
    # docs/getting_started/installation/spark_performance.md.
    #
    # FP4 attention needs fastvideo-kernel built for 12.1a and eager DiT inference.
    # A missing extension is an error. Set h3_vsa_fp4.enabled to false for BF16 VSA.
    # The NVFP4 encoder and lightweight VAE ship in the same repository.
    #
    # FASTVIDEO_H3_VSA_FP4=1 FASTVIDEO_MINIMAX_H3_FUSIONS=all FASTVIDEO_NVFP4_MM_BACKEND=cudnn FASTVIDEO_NVFP4_MM_ROW_SPLIT=table \
    # FASTVIDEO_H3_VAE_TILE_BATCH=12 FASTVIDEO_H3_VAE_INT8_OVERLAY=0 \
    # FASTVIDEO_VSA_TRITON=1 FASTVIDEO_VSA_PTX_BLACKWELL=0 FASTVIDEO_FA4=0 \
    # FASTVIDEO_ATTENTION_BACKEND=VIDEO_SPARSE_ATTN_H3 FASTVIDEO_STAGE_LOGGING=1 \
    # fastvideo generate --config examples/inference/basic/basic_fasth3_spark_v2_nvfp4.yaml
    generator:
      model_path: FastVideo/FastVideo-FastH3-8-Step-V2-NVFP4-Consumer
      engine:
        num_gpus: 1
        use_fsdp_inference: false
        quantization:
          transformer_quant: NVFP4
          layer_profile: h3_dit_vsa
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: false
          image_encoder: false
          vae: false
          pin_cpu_memory: false
          lazy_module_load: false
        compile:
          enabled: false
          vae_enabled: true
      pipeline:
        workload_type: t2v
        vae_tiling: true
        experimental:
          attention_backend: VIDEO_SPARSE_ATTN_H3
          h3_vsa_fp4:
            enabled: true
          VSA_sparsity: 0.8
          VSA_tile_size: 64
          h3_sequential_load: false
          inference_torch_compile: false
          vae_parallel_decode: false
          video_decode_backend: h3-vae
    request:
      prompt: A quiet pottery studio with a potter finishing a bowl at the wheel.
      negative_prompt: ""
      sampling:
        seed: 1234
        height: 480
        width: 832
        num_frames: 124
        fps: 24
        num_inference_steps: 9  # nine sigma points, eight DiT forwards
        guidance_scale: 1.0
        batch_cfg: false
      output:
        output_path: outputs/fasth3_spark_v2_nvfp4/
        save_video: true
        return_frames: false
    
    ```

??? note "basic_fasth3_to_regen2k.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Draft with a FastH3 checkpoint at 768P, then regenerate the draft at 2560x1440 with Open-H3-Regenerate-2K.
    
    The draft's native latent goes straight to the regen's upscaler: the draft is never decoded to pixels and re-encoded.
    The regen stack is unchanged (base MiniMax-H3, the released merged LoRA and Sharp branches, three Euler steps).
    
        python examples/inference/basic/basic_fasth3_to_regen2k.py \
            --draft-model FastVideo/FastVideo-FastH3-8-Step-V2 --regen-model Efficient-Large-Model/Open-H3-Regenerate-2K \
            --prompt "A red fox trots through fresh snow" --output outputs/fasth3_regen2k
    
    A packed NVFP4 draft checkpoint (FastH3 QAD, FastH3 Trim NVFP4) needs ``--draft-quant h3_dit_vsa``; ``--vae-decoder``
    selects an NVFP4 decoder for the 2K decode.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import os
    from pathlib import Path
    
    import torch
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        PipelineSelection,
        QuantizationConfig,
        SamplingConfig,
    )
    from fastvideo.utils import maybe_download_model
    
    DRAFT_SIZE = (768, 1344)
    NUM_FRAMES = 124
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--draft-model", required=True, help="FastH3 checkpoint id or local path")
        parser.add_argument("--draft-quant", default=None, help="NVFP4 layer profile of a packed draft, e.g. h3_dit_vsa")
        parser.add_argument("--regen-model", default="Efficient-Large-Model/Open-H3-Regenerate-2K")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--draft-steps", type=int, default=9, help="sigma-grid points of the draft (9 = 8 forwards)")
        parser.add_argument("--draft-seed", type=int, default=1000)
        parser.add_argument("--seed", type=int, default=1766580932, help="regen refine noise seed")
        parser.add_argument("--output", type=Path, default=Path("outputs/fasth3_regen2k"))
        parser.add_argument("--vae-decoder",
                            default=None,
                            help="NVFP4 H3 video decoder for the regen decode (Blackwell), e.g. "
                            "quality-36L/decoder-nvfp4.safetensors from FastVideo/FastH3-NVFP4-VAE-Decoder")
        return parser.parse_args()
    
    
    def normalize_h3_latents(latents: torch.Tensor, regen_model: str) -> torch.Tensor:
        """Re-apply the H3 VAE's latent statistics: a draft run returns denormalized latents, the regen takes normalized."""
        vae_config = os.path.join(maybe_download_model(regen_model, allow_patterns=["base_model/vae/config.json"]),
                                  "base_model", "vae", "config.json")
        with open(vae_config, encoding="utf-8") as handle:
            config = json.load(handle)
        mean = torch.tensor(config["latents_mean"], dtype=torch.float32).view(-1, 1, 1, 1)
        std = torch.tensor(config["latents_std"], dtype=torch.float32).view(-1, 1, 1, 1)
        return (latents.float().cpu().reshape(-1, *latents.shape[-3:]) - mean) / std
    
    
    def draft_latent(args: argparse.Namespace) -> torch.Tensor:
        engine = EngineConfig(num_gpus=1, offload=OffloadConfig(dit=False, dit_layerwise=False, vae=False))
        if args.draft_quant:
            engine.quantization = QuantizationConfig(transformer_quant="NVFP4", layer_profile=args.draft_quant)
        generator = VideoGenerator.from_config(
            GeneratorConfig(model_path=args.draft_model,
                            engine=engine,
                            pipeline=PipelineSelection(components=ComponentConfig(),
                                                       experimental={
                                                           "attention_backend": "VIDEO_SPARSE_ATTN_H3",
                                                           "VSA_sparsity": 0.8,
                                                           "VSA_tile_size": 64,
                                                           "output_type": "latent",
                                                       })))
        try:
            result = generator.generate(
                GenerationRequest(prompt=args.prompt,
                                  sampling=SamplingConfig(height=DRAFT_SIZE[0],
                                                          width=DRAFT_SIZE[1],
                                                          num_frames=NUM_FRAMES,
                                                          fps=24,
                                                          num_inference_steps=args.draft_steps,
                                                          guidance_scale=1.0,
                                                          seed=args.draft_seed),
                                  output=OutputConfig(save_video=False, return_frames=True)))
        finally:
            generator.shutdown()
        return normalize_h3_latents(torch.as_tensor(result.samples), args.regen_model)
    
    
    def main() -> None:
        args = parse_args()
        args.output.mkdir(parents=True, exist_ok=True)
        latent_path = args.output / "draft_latent.pt"
        torch.save(draft_latent(args), latent_path)
    
        generator = VideoGenerator.from_config(
            GeneratorConfig(model_path=args.regen_model,
                            engine=EngineConfig(num_gpus=1,
                                                offload=OffloadConfig(dit=False, dit_layerwise=False, text_encoder=True,
                                                                      vae=False)),
                            pipeline=PipelineSelection(components=ComponentConfig(),
                                                       experimental={
                                                           "attention_backend": "TORCH_SDPA",
                                                           "draft_size": "768p",
                                                           **({
                                                               "h3_vae_nvfp4_decoder": args.vae_decoder
                                                           } if args.vae_decoder else {}),
                                                       })))
        try:
            result = generator.generate(
                GenerationRequest(prompt=args.prompt,
                                  inputs=InputConfig(video_path=str(latent_path)),
                                  sampling=SamplingConfig(height=1440,
                                                          width=2560,
                                                          num_frames=NUM_FRAMES,
                                                          fps=24,
                                                          num_inference_steps=3,
                                                          guidance_scale=1.0,
                                                          seed=args.seed),
                                  output=OutputConfig(output_path=str(args.output / "regen2k.mp4"),
                                                      save_video=True,
                                                      return_frames=False)))
            print(f"wrote {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_flux2.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Run full Flux2 text-to-image generation through FastVideo.
    
    User story:
        "I have a local or HF Diffusers-format full Flux2 checkpoint and want a
        minimal text-to-image generation command that uses embedded guidance."
    """
    import argparse
    import os
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description="Run full Flux2 text-to-image generation.")
        parser.add_argument(
            "--model-path",
            default="black-forest-labs/FLUX.2-dev",
            help="HF id or local diffusers-format full Flux2 weights directory.",
        )
        parser.add_argument(
            "--output",
            default="outputs/flux2/flux2.png",
            help="Output PNG path.",
        )
        parser.add_argument(
            "--prompt",
            default="a photo of a banana on a wooden table, studio lighting",
            help="Text prompt.",
        )
        parser.add_argument("--height", type=int, default=1024)
        parser.add_argument("--width", type=int, default=1024)
        parser.add_argument("--steps", type=int, default=50)
        parser.add_argument("--guidance-scale", type=float, default=4.0)
        parser.add_argument("--max-sequence-length", type=int, default=None)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=1)
        parser.add_argument("--tp-size", type=int, default=None)
        parser.add_argument("--sp-size", type=int, default=None)
        parser.add_argument(
            "--backend",
            default=None,
            help="Set FASTVIDEO_ATTENTION_BACKEND, for example TORCH_SDPA.",
        )
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        if args.backend:
            os.environ["FASTVIDEO_ATTENTION_BACKEND"] = args.backend
    
        output = Path(args.output)
        output.parent.mkdir(parents=True, exist_ok=True)
        tp_size = args.tp_size if args.tp_size is not None else (args.num_gpus if args.num_gpus > 1 else 1)
        sp_size = args.sp_size if args.sp_size is not None else (1 if args.num_gpus > 1 else args.num_gpus)
    
        generator_config = GeneratorConfig(
            model_path=args.model_path,
            engine=EngineConfig(
                num_gpus=args.num_gpus,
                parallelism=ParallelismConfig(tp_size=tp_size, sp_size=sp_size),
                use_fsdp_inference=False,
                offload=OffloadConfig(
                    dit=False,
                    vae=True,
                    text_encoder=True,
                    pin_cpu_memory=False,
                ),
            ),
            pipeline=PipelineSelection(
                workload_type="t2i",
                components=ComponentConfig(override_pipeline_cls_name="Flux2Pipeline"),
            ),
        )
    
        generator = VideoGenerator.from_config(generator_config)
        try:
            sampling = SamplingConfig(
                height=args.height,
                width=args.width,
                num_frames=1,
                fps=1,
                num_inference_steps=args.steps,
                guidance_scale=args.guidance_scale,
                seed=args.seed,
            )
            extensions = {}
            if args.max_sequence_length is not None:
                extensions["max_sequence_length"] = args.max_sequence_length
    
            request = GenerationRequest(
                prompt=args.prompt,
                sampling=sampling,
                output=OutputConfig(
                    output_path=str(output),
                    save_video=True,
                    return_frames=False,
                ),
                extensions=extensions,
            )
            generator.generate(request)
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_flux2_klein.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Run Flux2 Klein text-to-image generation through FastVideo.
    
    User story:
        "I need a short local smoke for the Flux2 Klein checkpoint before wiring it
        into an image workflow. Use the model's distilled four-step defaults and
        write a single PNG so I can compare the output against the reference."
    """
    
    import argparse
    import os
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    DEFAULT_PROMPT = "a brushed steel espresso machine on a marble counter, morning window light"
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description="Run Flux2 Klein text-to-image generation.")
        parser.add_argument(
            "--model-path",
            default="black-forest-labs/FLUX.2-klein-4B",
            help="HF id or local diffusers-format Flux2 Klein weights directory.",
        )
        parser.add_argument(
            "--output-path",
            default="outputs/flux2/flux2_klein.png",
            help="PNG output path or output directory.",
        )
        parser.add_argument("--prompt", default=DEFAULT_PROMPT, help="Prompt text.")
        parser.add_argument("--seed", type=int, default=0, help="Generation seed.")
        parser.add_argument("--height", type=int, default=1024, help="Output image height.")
        parser.add_argument("--width", type=int, default=1024, help="Output image width.")
        parser.add_argument("--steps", type=int, default=4, help="Number of denoising steps.")
        parser.add_argument("--num-gpus", type=int, default=1, help="Number of GPUs to use.")
        parser.add_argument(
            "--backend",
            default=None,
            help="Set FASTVIDEO_ATTENTION_BACKEND, for example TORCH_SDPA.",
        )
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        if args.backend:
            os.environ["FASTVIDEO_ATTENTION_BACKEND"] = args.backend
    
        generator_config = GeneratorConfig(
            model_path=args.model_path,
            engine=EngineConfig(
                num_gpus=args.num_gpus,
                use_fsdp_inference=False,
                offload=OffloadConfig(
                    dit=False,
                    vae=True,
                    text_encoder=True,
                    pin_cpu_memory=False,
                ),
            ),
            pipeline=PipelineSelection(workload_type="t2i"),
        )
    
        generator = VideoGenerator.from_config(generator_config)
        try:
            request = GenerationRequest(
                prompt=args.prompt,
                sampling=SamplingConfig(
                    height=args.height,
                    width=args.width,
                    num_frames=1,
                    fps=1,
                    num_inference_steps=args.steps,
                    guidance_scale=1.0,
                    seed=args.seed,
                ),
                output=OutputConfig(
                    output_path=args.output_path,
                    save_video=True,
                ),
            )
            generator.generate(request)
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_flux_dev.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    
    from __future__ import annotations
    
    import argparse
    import contextlib
    import os
    import re
    
    DEFAULT_PROMPTS = [
        "a photo of a cat",
        ("a cinematic photo of a red panda wearing a tiny backpack, standing on a "
         "rainy neon-lit street at night, shallow depth of field, sharp focus, "
         "35mm, bokeh"),
    ]
    
    
    def _safe_filename(text: str, max_len: int = 100) -> str:
        """Make a stable, filesystem-friendly filename base."""
        s = text[:max_len].strip()
        s = s.replace(os.sep, "_")
        if os.altsep:
            s = s.replace(os.altsep, "_")
        s = re.sub(r"\s+", " ", s)
        s = re.sub(r"[^A-Za-z0-9 .,_-]", "_", s)
        s = s.strip(" .")
        return s or "prompt"
    
    
    def _remove_existing_outputs(out_dir: str, filename_base: str) -> None:
        """Delete prior outputs so reruns do not get _1, _2 suffixes."""
        if not os.path.isdir(out_dir):
            return
    
        pattern = re.compile(rf"^{re.escape(filename_base)}(_\d+)?\.(mp4|png)$")
        for fn in os.listdir(out_dir):
            if pattern.match(fn):
                with contextlib.suppress(FileNotFoundError):
                    os.remove(os.path.join(out_dir, fn))
    
    
    def parse_args() -> argparse.Namespace:
        p = argparse.ArgumentParser(description="Run FLUX.1-dev text-to-image with FastVideo VideoGenerator.", )
        p.add_argument(
            "--model-path",
            default="official_weights/FLUX.1-dev",
            help="Local Diffusers checkpoint dir or HF repo id.",
        )
        p.add_argument(
            "--out-dir",
            "--outdir",
            default="outputs/flux_dev/samples",
            help="Directory for saved PNG outputs.",
        )
        p.add_argument(
            "--prompt",
            action="append",
            default=None,
            help="Prompt. Repeat for multiple images.",
        )
        p.add_argument(
            "--backend",
            default=None,
            help="Set FASTVIDEO_ATTENTION_BACKEND (e.g. TORCH_SDPA).",
        )
        p.add_argument("--seed", type=int, default=42, help="Base seed; each prompt uses seed + index.")
        p.add_argument("--height", type=int, default=1024, help="Output height.")
        p.add_argument("--width", type=int, default=1024, help="Output width.")
        p.add_argument("--steps", type=int, default=28, help="Number of inference steps.")
        p.add_argument("--guidance", type=float, default=3.5, help="Guidance scale.")
        p.add_argument("--num-gpus", type=int, default=1, help="GPU count.")
        return p.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        prompts: list[str] = args.prompt if args.prompt else DEFAULT_PROMPTS
    
        if args.backend:
            os.environ["FASTVIDEO_ATTENTION_BACKEND"] = args.backend
    
        from fastvideo import VideoGenerator
    
        os.makedirs(args.out_dir, exist_ok=True)
    
        init_kwargs = {
            "num_gpus": args.num_gpus,
            "workload_type": "t2i",
            "sp_size": 1,
            "tp_size": 1,
            "dit_cpu_offload": False,
            "dit_layerwise_offload": False,
            "text_encoder_cpu_offload": False,
            "vae_cpu_offload": False,
            "image_encoder_cpu_offload": False,
            "pin_cpu_memory": False,
            "use_fsdp_inference": False,
        }
    
        generator = VideoGenerator.from_pretrained(
            model_path=args.model_path,
            **init_kwargs,
        )
        try:
            for i, prompt in enumerate(prompts):
                seed = args.seed + i
                filename_base = (f"flux_dev_{i:02d}_seed{seed}_{_safe_filename(prompt, max_len=80)}")
                _remove_existing_outputs(args.out_dir, filename_base)
                output_path = os.path.join(args.out_dir, f"{filename_base}.png")
                print(f"[flux] prompt_idx={i} seed={seed} output_path={output_path}")
    
                generation_kwargs = {
                    "output_path": output_path,
                    "height": args.height,
                    "width": args.width,
                    "num_frames": 1,
                    "fps": 1,
                    "num_inference_steps": args.steps,
                    "guidance_scale": args.guidance,
                    "use_embedded_guidance": True,
                    "true_cfg_scale": 1.0,
                    "seed": seed,
                    "save_video": True,
                }
    
                generator.generate_video(prompt, **generation_kwargs)
    
            print(f"[flux] done. outputs written to: {args.out_dir}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_gen3c.py"

    ```py
    """
    GEN3C: 3D-aware camera-controlled video generation.
    
    This example generates a video from a single input image with camera control.
    The pipeline uses MoGe depth estimation, 3D point cloud forward warping,
    and the GEN3C diffusion model.
    
    Requirements:
      1. Install MoGe:
         uv pip install git+https://github.com/microsoft/MoGe.git
         If you hit `ImportError: libGL.so.1`, install:
         sudo apt-get update && sudo apt-get install -y libgl1 libglib2.0-0 libsm6 libxext6 libxrender1
      2. Download and convert weights:
         huggingface-cli download nvidia/GEN3C-Cosmos-7B --local-dir official_weights/GEN3C-Cosmos-7B
         python scripts/checkpoint_conversion/convert_gen3c_to_fastvideo.py \
           --source ./official_weights/GEN3C-Cosmos-7B/model.pt \
           --output ./converted_weights/GEN3C-Cosmos-7B \
           --components-source nvidia/Cosmos-Predict2-2B-Video2World
      3. Provide an input image for 3D-conditioned generation.
    """
    
    import argparse
    
    from fastvideo import VideoGenerator
    
    
    def main():
        parser = argparse.ArgumentParser(description="GEN3C video generation")
        parser.add_argument("--model_path", type=str, default="converted_weights/GEN3C-Cosmos-7B")
        parser.add_argument("--image_path", type=str, default=None, help="Input image for 3D cache conditioning")
        parser.add_argument("--prompt", type=str, default="A slow camera pan over a sunlit landscape.")
        parser.add_argument(
            "--negative_prompt",
            type=str,
            default=("The video captures a series of frames showing ugly scenes, static with no motion, motion blur, "
                     "over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, "
                     "underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, "
                     "jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special "
                     "effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and "
                     "flickering. Overall, the video is of poor quality."),
        )
        parser.add_argument(
            "--trajectory",
            type=str,
            default="left",
            choices=["left", "right", "up", "down", "zoom_in", "zoom_out", "clockwise", "counterclockwise", "none"])
        parser.add_argument("--movement_distance", type=float, default=0.3)
        parser.add_argument("--camera_rotation",
                            type=str,
                            default="center_facing",
                            choices=["center_facing", "no_rotation", "trajectory_aligned"])
        parser.add_argument("--height", type=int, default=704)
        parser.add_argument("--width", type=int, default=1280)
        parser.add_argument("--num_frames", type=int, default=121)
        parser.add_argument("--num_inference_steps", type=int, default=35)
        parser.add_argument("--guidance_scale", type=float, default=1.0)
        parser.add_argument("--output_path", type=str, default="outputs_video/gen3c.mp4")
        parser.add_argument("--seed", type=int, default=42)
        args = parser.parse_args()
    
        generator = VideoGenerator.from_pretrained(
            args.model_path,
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=True,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        video = generator.generate_video(
            args.prompt,
            negative_prompt=args.negative_prompt,
            image_path=args.image_path,
            trajectory_type=args.trajectory,
            movement_distance=args.movement_distance,
            camera_rotation=args.camera_rotation,
            height=args.height,
            width=args.width,
            num_frames=args.num_frames,
            num_inference_steps=args.num_inference_steps,
            guidance_scale=args.guidance_scale,
            fps=24,
            seed=args.seed,
            output_path=args.output_path,
            save_video=True,
        )
    
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_helios_distilled_t2v.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate one Helios-Distilled T2V chunk through FastVideo's typed API.
    
    Set ``HELIOS_MODEL_PATH`` to a local snapshot to avoid downloading the public
    checkpoint again. The 33-frame example is a short integration run; increase
    ``num_frames`` to 240 for the official eight-chunk default.
    """
    
    from __future__ import annotations
    
    import os
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        SamplingConfig,
    )
    
    MODEL_PATH = os.getenv("HELIOS_MODEL_PATH", "BestWishYsh/Helios-Distilled")
    OUTPUT_PATH = os.getenv(
        "HELIOS_OUTPUT_PATH",
        "outputs_video/helios/helios_distilled_t2v.mp4",
    )
    PROMPT = ("A vibrant tropical fish swims gracefully through a colorful coral reef "
              "in clear turquoise water, cinematic close-up, fluid motion, vivid detail.")
    NEGATIVE_PROMPT = ("Bright tones, overexposed, static, blurred details, subtitles, paintings, "
                       "images, overall gray, worst quality, low quality, JPEG artifacts, ugly, "
                       "deformed, disfigured, still picture, messy background.")
    
    
    def main() -> None:
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=MODEL_PATH,
                engine=EngineConfig(
                    num_gpus=1,
                    use_fsdp_inference=False,
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=True,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                    ),
                ),
            ))
        request = GenerationRequest(
            prompt=PROMPT,
            negative_prompt=NEGATIVE_PROMPT,
            sampling=SamplingConfig(
                seed=42,
                height=384,
                width=640,
                num_frames=33,
                fps=24,
                num_inference_steps=2,
                guidance_scale=1.0,
                pyramid_num_inference_steps_list=[2, 2, 2],
                history_sizes=[16, 2, 1],
                num_latent_frames_per_chunk=9,
                keep_first_frame=True,
                is_skip_first_chunk=False,
                use_zero_init=True,
                zero_steps=1,
                is_amplify_first_chunk=True,
            ),
            output=OutputConfig(
                output_path=OUTPUT_PATH,
                save_video=True,
                return_frames=False,
            ),
        )
    
        try:
            generator.generate(request=request)
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_hy15.py"

    ```py
    from fastvideo import VideoGenerator
    import json
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_hy15"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,
            vae_cpu_offload=True,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            # image_encoder_cpu_offload=False,
        )
    
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
    
        video = generator.generate_video(prompt,
                                         output_path=OUTPUT_PATH,
                                         save_video=True,
                                         negative_prompt="",
                                         num_frames=81,
                                         fps=16)
    
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
    
        video2 = generator.generate_video(prompt2,
                                          output_path=OUTPUT_PATH,
                                          save_video=True,
                                          negative_prompt="",
                                          num_frames=81,
                                          fps=16)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_hy15_1080p.py"

    ```py
    from fastvideo import VideoGenerator
    import json
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_hy15_1080p"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "weizhou03/HunyuanVideo-1.5-Diffusers-1080p-2SR",  # 480p -> 720p -> 1080p
            # or "weizhou03/HunyuanVideo-1.5-Diffusers-1080p" # 720p -> 1080p
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,
            vae_cpu_offload=True,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            # image_encoder_cpu_offload=False,
        )
    
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
    
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True, negative_prompt="")
    
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
    
        video2 = generator.generate_video(prompt2, output_path=OUTPUT_PATH, save_video=True, negative_prompt="")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_hyworld.py"

    ```py
    from fastvideo import VideoGenerator
    from fastvideo.models.dits.hyworld.resolution_utils import get_resolution_from_image
    
    # Default prompt from HY-WorldPlay run.sh
    DEFAULT_PROMPT = 'A paved pathway leads towards a stone arch bridge spanning a calm body of water.  Lush green trees and foliage line the path and the far bank of the water. A traditional-style pavilion with a tiered, reddish-brown roof sits on the far shore. The water reflects the surrounding greenery and the sky.  The scene is bathed in soft, natural light, creating a tranquil and serene atmosphere. The pathway is composed of large, rectangular stones, and the bridge is constructed of light gray stone.  The overall composition emphasizes the peaceful and harmonious nature of the landscape.'
    DEFAULT_IMAGE = 'https://raw.githubusercontent.com/Tencent-Hunyuan/HY-WorldPlay/main/assets/img/test.png'
    
    OUTPUT_PATH = "video_samples_hyworld"
    
    
    def main():
        import argparse
    
        # pose: (a, w, s, d) - (15, 31)
        # num_frames: (61, 125)
        parser = argparse.ArgumentParser(description="HYWorld video generation with FastVideo")
        parser.add_argument("--prompt", type=str, default=DEFAULT_PROMPT, help="Text prompt for video generation")
        parser.add_argument("--image", type=str, default=DEFAULT_IMAGE, help="Path or URL to input image")
        parser.add_argument("--pose", type=str, default='w-31', help="Pose string (e.g., 'a-31', 'w-31', 's-31', 'd-31')")
        parser.add_argument("--output_path", type=str, default=OUTPUT_PATH, help="Output video path")
        parser.add_argument("--num-frames", type=int, default=125, help="Number of frames")
        parser.add_argument("--seed", type=int, default=1, help="Random seed")
        parser.add_argument("--resolution", type=str, default="480p", help="Only support 480p for now")
        args = parser.parse_args()
    
        # Automatically determine resolution from input image
        HEIGHT, WIDTH = get_resolution_from_image(args.image, args.resolution)
        print(f"Image: {args.image}")
        print(f"Pose: {args.pose}")
        print(f"Resolution: {HEIGHT}x{WIDTH} (from {args.resolution} buckets)")
        print(f"Num frames: {args.num_frames}")
        print(f"Output path: {args.output_path}")
    
        # Initialize generator
        print("\nInitializing VideoGenerator for HYWorld...")
        generator = VideoGenerator.from_pretrained(
            "FastVideo/HY-WorldPlay-Bidirectional-Diffusers",
            num_gpus=1,
            use_fsdp_inference=True,
            dit_cpu_offload=True,
            vae_cpu_offload=True,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
            image_encoder_cpu_offload=True,
        )
    
        # Generate video
        # The pose string is automatically converted to camera matrices by the pipeline
        print("\nGenerating video...")
        generator.generate_video(
            prompt=args.prompt,
            image_path=args.image,
            pose=args.pose,  # Camera trajectory control
            output_path=args.output_path,
            save_video=True,
            negative_prompt="",
            num_frames=args.num_frames,
            fps=24,
            height=HEIGHT,
            width=WIDTH,
            seed=args.seed,
        )
    
        print(f"\nVideo saved to: {args.output_path}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_kandinsky5_i2v.py"

    ```py
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_kandinsky5_i2v"
    
    IMAGE_PATH = "assets/girl.png"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "kandinskylab/Kandinsky-5.0-I2V-Pro-distilled-5s-Diffusers",
            # "kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers"
            # "kandinskylab/Kandinsky-5.0-I2V-Lite-5s-Diffusers"
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        prompt = ("A woman stands up and walks away")
        _ = generator.generate_video(
            prompt,
            image_path=IMAGE_PATH,
            output_path=OUTPUT_PATH,
            save_video=True,
            height=1024,
            width=1024,
            num_frames=121,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_kandinsky5_t2v.py"

    ```py
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_kandinsky5_t2v"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers",
            # "kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers"
            # "kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers"
            # "kandinskylab/Kandinsky-5.0-T2V-Pro-distilled-5s-Diffusers"
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        _ = generator.generate_video(prompt,
                                     output_path=OUTPUT_PATH,
                                     save_video=True,
                                     height=512,
                                     width=768,
                                     num_frames=121)
    
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        _ = generator.generate_video(prompt2,
                                     output_path=OUTPUT_PATH,
                                     save_video=True,
                                     height=512,
                                     width=768,
                                     num_frames=121)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_kandinsky6_sr.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Kandinsky6 video super-resolution: upscale a low-resolution video x2, x2.25 or x4.
    
    The request needs no prompt and no height / width / num_frames: the geometry and frame rate follow the input video
    (the first 121 frames, 5 s at 24 fps, are processed and the source audio is kept).  Use
    ``kandinskylab/Kandinsky-6.0-VSR-distilled2steps-5s-Diffusers`` for the 2-step distilled model.
    See docs/inference/kandinsky6_sr.md.
    """
    import argparse
    
    from fastvideo import VideoGenerator
    
    
    def main():
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--model-path", default="kandinskylab/Kandinsky-6.0-VSR-5s-Diffusers")
        parser.add_argument("--video-path", required=True, help="Low-resolution source video")
        parser.add_argument("--output-path", default="outputs_video/kandinsky6_sr",
                            help="Output directory (the file is named after the input) or .mp4 path")
        parser.add_argument("--scale", type=float, default=2.25, choices=[2.0, 4.0, 2.25], help="Total upscale factor")
        parser.add_argument("--num-steps", type=int, default=None,
                            help="Denoising steps per tile (default: the checkpoint's preset, 4 or 2)")
        parser.add_argument("--tiles-batch-size", type=int, default=1, help="Tiles denoised per DiT call")
        parser.add_argument("--target-resolution", default=None, help="Optional final size: hd, fullhd, 2k or WxH")
        parser.add_argument("--seed", type=int, default=42)
        args = parser.parse_args()
    
        generator = VideoGenerator.from_pretrained(args.model_path, num_gpus=1)
        sampling = {"seed": args.seed}
        if args.num_steps is not None:
            sampling["num_inference_steps"] = args.num_steps
        result = generator.generate({
            "inputs": {
                "video_path": args.video_path
            },
            "sampling": sampling,
            "output": {
                "output_path": args.output_path,
                "save_video": True,
                "return_frames": False,
            },
            "extensions": {
                "sr_resolution_scale": args.scale,
                "sr_tiles_batch_size": args.tiles_batch_size,
                "sr_target_resolution": args.target_resolution,
            },
        })
        print(f"Wrote {result.video_path}")
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_kandinsky6_ti2va.py"

    ```py
    import os
    
    from fastvideo import VideoGenerator
    
    DEFAULT_PROMPT = (
        "cinematic shot: a giant stone samurai on a stormy cliff above a neon city opens glowing golden eyes and "
        "raises a katana. Blue lightning strikes the blade, creating a massive shockwave through the clouds. The "
        "camera rapidly pulls back from a low angle. Photorealistic, epic scale, dark blue and gold lighting, rain, "
        "sparks, volumetric lightning, blockbuster quality. Audio: heavy rain, deep thunder, metallic sword hum, "
        "rising brass and choir, electrical crackle, perfectly synchronized lightning impact, sub-bass shockwave. "
        "No dialogue, text, or logos."
    )
    
    OUTPUT_PATH = "video_samples_kandinsky6_ti2va"
    
    # The base checkpoint uses 50 steps and guidance 5.0. Set KANDINSKY6_MODEL_PATH to run the
    # distilled pi-Flow checkpoint with this same example:
    #   kandinskylab/Kandinsky-6.0-Pro-distill-5s-Diffusers
    # or a local directory named ``Kandinsky-6.0-Pro-distill-5s-Diffusers``.
    # That name selects the registered distilled defaults automatically: 10 steps,
    # guidance 1.0, eps 1e-6, final_step_size_scale 0.5, and
    # num_policy_substeps 128.
    MODEL_PATH = os.environ.get("KANDINSKY6_MODEL_PATH", "kandinskylab/Kandinsky-6.0-Pro-5s-Diffusers")
    
    IMAGE_PATH = None  # e.g. "assets/girl.png" to condition on an image
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            MODEL_PATH,
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        _ = generator.generate_video(
            DEFAULT_PROMPT,
            image_path=IMAGE_PATH,
            output_path=OUTPUT_PATH,
            save_video=True,
            height=512,
            width=768,
            num_frames=121,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_lingbot_video.py"

    ```py
    """Generate a five-second Dense LingBot-Video clip with the official defaults."""
    
    import argparse
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    
    
    def parse_args() -> argparse.Namespace:
        """Parse the converted checkpoint and output paths for the sample."""
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument(
            "--model-path",
            type=Path,
            required=True,
            help="Path to a converted Dense LingBot-Video checkpoint.",
        )
        parser.add_argument(
            "--output-path",
            type=Path,
            default=Path("outputs/lingbot-video/dense-t2v"),
            help="Directory for the generated video.",
        )
        return parser.parse_args()
    
    
    def main() -> None:
        """Load the converted Dense checkpoint and generate the default T2V sample."""
        args = parse_args()
        generator = VideoGenerator.from_pretrained(
            str(args.model_path),
            num_gpus=1,
            use_fsdp_inference=False,
            text_encoder_cpu_offload=True,
            vae_cpu_offload=False,
            pin_cpu_memory=True,
        )
        try:
            generator.generate({
                "prompt": "A red fox runs through fresh snow at sunrise.",
                "output": {
                    "output_path": str(args.output_path),
                    "save_video": True,
                    "return_frames": False,
                },
            })
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_lingbotworld2_causal_fast.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Run LingBot World 2 14B causal-fast I2V generation with FastVideo."""
    
    import os
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    
    REPO_ROOT = Path(__file__).resolve().parents[3]
    DATASET_DIR = REPO_ROOT / "examples" / "dataset" / "lingbotworld2"
    OUTPUT_PATH = REPO_ROOT / "outputs" / "lingbotworld2_causal_fast.mp4"
    
    
    def main() -> None:
        """Load the native FastVideo LingBot World 2 causal-fast pipeline and generate one video."""
        generator = VideoGenerator.from_pretrained(
            os.environ["LINGBOTWORLD2_MODEL_PATH"],
            num_gpus=8,
            sp_size=8,
            hsdp_shard_dim=8,
            use_fsdp_inference=True,
            dit_layerwise_offload=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=False,
            pin_cpu_memory=True,
            override_pipeline_cls_name="LingBotWorld2CausalFastPipeline",
        )
    
        try:
            generator.generate_video(
                "A serene lakeside scene with a lone tree standing in calm water, surrounded by distant snow-capped mountains under a bright blue sky with drifting white clouds; gentle ripples reflect the tree and sky, creating a tranquil, meditative atmosphere.",
                image_path=str(DATASET_DIR / "image.jpg"),
                action_path=str(DATASET_DIR),
                output_path=str(OUTPUT_PATH),
                save_video=True,
                height=480,
                width=832,
                num_frames=65,
                num_inference_steps=4,
                guidance_scale=1.0,
                negative_prompt="",
                fps=16,
                seed=42,
            )
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_lingbotworld_base_cam.py"

    ```py
    from fastvideo import VideoGenerator
    from fastvideo.models.dits.lingbotworld.cam_utils import prepare_camera_embedding
    
    # from fastvideo.api.sampling_param import SamplingParam
    OUTPUT_PATH = "video_samples_lingbotworld"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "FastVideo/LingBot-World-Base-Cam-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        num_frames = 81
        prompt = "The video presents a soaring journey through a fantasy jungle. The wind whips past the rider's blue hands gripping the reins, causing the leather straps to vibrate. The ancient gothic castle approaches steadily, its stone details becoming clearer against the backdrop of floating islands and distant waterfalls."
        image_path = "https://raw.githubusercontent.com/Robbyant/lingbot-world/main/examples/00/image.jpg"
        action_path = "examples/inference/basic/lingbotworld_examples/00"
        c2ws_plucker_emb, num_frames = prepare_camera_embedding(
            action_path=action_path,
            num_frames=num_frames,
            height=480,
            width=832,
            spatial_scale=8,
        )
    
        generator.generate_video(
            prompt,
            image_path=image_path,
            output_path=OUTPUT_PATH,
            save_video=True,
            num_frames=num_frames,
            height=480,
            width=832,
            c2ws_plucker_emb=c2ws_plucker_emb,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_lingbotworld_fast.py"

    ```py
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_lingbotworld_fast"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "FastVideo/LingBot-World-Fast-Diffusers",
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        prompt = (
            "A serene lakeside scene with a lone tree standing in calm water, "
            "surrounded by distant snow-capped mountains under a bright blue sky "
            "with drifting white clouds — gentle ripples reflect the tree and sky, "
            "creating a tranquil, meditative atmosphere.")
        action_path = "examples/datasets/lingbotworld2"
        image_path = f"{action_path}/image.jpg"
    
        generator.generate_video(
            prompt,
            image_path=image_path,
            action_path=action_path,
            output_path=OUTPUT_PATH,
            save_video=True,
            num_frames=81,
            height=480,
            width=832,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2.py"

    ```py
    from fastvideo import VideoGenerator
    
    PROMPT = ("A warm sunny backyard. The camera starts in a tight cinematic close-up "
              "of a woman and a man in their 30s, facing each other with serious "
              "expressions. The woman, emotional and dramatic, says softly, \"That's "
              "it... Dad's lost it. And we've lost Dad.\" The man exhales, slightly "
              "annoyed: \"Stop being so dramatic, Jess.\" A beat. He glances aside, "
              "then mutters defensively, \"He's just having fun.\" The camera slowly "
              "pans right, revealing the grandfather in the garden wearing enormous "
              "butterfly wings, waving his arms in the air like he's trying to take "
              "off. He shouts, \"Wheeeew!\" as he flaps his wings with full commitment. "
              "The woman covers her face, on the verge of tears. The tone is deadpan, "
              "absurd, and quietly tragic.")
    
    
    def main() -> None:
        # Uses FastVideo default sampling settings for LTX2 base.
        generator = VideoGenerator.from_pretrained(
            "Davids048/LTX2-Base-Diffusers",
            num_gpus=1,
        )
    
        output_path = "outputs_video/ltx2_basic/output_ltx2_base_t2v_1088_1920_1.1.mp4"
        generator.generate_video(
            prompt=PROMPT,
            output_path=output_path,
            save_video=True,
            num_frames=121,
            height=1088,
            width=1920,
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_3_distilled_i2v.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """LTX-2.3 distilled image-to-video with torch.compile + timing breakdown.
    
    This example runs the LTX-2.3 distilled student model on a single GPU with
    torch.compile fully enabled, then prints a per-stage timing breakdown so the
    user can see where wall-time goes. It is meant as the canonical entry point
    for trying out the LTX-2.3 i2v path on `hao-ai-lab/FastVideo:main`.
    
    Quick start
    -----------
        export LTX23_I2V_IMAGE=/path/to/your/portrait_or_product.jpg
        # optional overrides:
        #   export LTX23_I2V_PROMPT="a fashion model walks toward camera..."
        #   export LTX23_OUTPUT_DIR=outputs_video/ltx2_3_distilled_i2v
        python examples/inference/basic/basic_ltx2_3_distilled_i2v.py
    
    What the script does
    --------------------
    1. Loads FastVideo/LTX-2.3-Distilled-Diffusers (8 denoise + 3 refine steps,
       CFG=1, no refine LoRA — the distilled production recipe).
    2. Compiles the DiT, text encoder, and VAE (fullgraph, Inductor default
       mode — autotune adds ~7 min cold-compile here with no measurable
       e2e gain).
    3. Runs 2 warmup calls (untimed) + 2 measured calls. Two warmups are kept
       as a safety net — the first call pays cold compile + first-shape guard
       work, and a second warmup ensures any residual recompiles settle before
       we measure.
    4. Prints a per-stage breakdown and an average over the measured runs.
    
    Hardware notes
    --------------
    - Single-GPU example; for multi-GPU sequence-parallel see the gradio demo
      under `examples/inference/gradio/local/gradio_local_demo_ltx2_3/`.
    - First-time compile takes ~30-40 min on GB200 (~20 min on H100; cached
      in `$TORCHINDUCTOR_CACHE_DIR` afterwards). Subsequent invocations only
      pay the one-time process load + a few seconds of dynamo trace.
    - On GB200 / Blackwell, run with `env -u LD_LIBRARY_PATH ...` to avoid a
      system-cuBLAS / torch-cuBLAS mismatch that fails every GEMM. The
      `_inductor.shape_padding = False` line below also avoids a pad_mm
      landmine on the same generation of cards.
    """
    from __future__ import annotations
    
    import os
    import time
    from collections import OrderedDict
    from pathlib import Path
    
    import torch._inductor.config as _inductor
    
    from fastvideo import VideoGenerator
    from fastvideo.configs.pipelines.base import PipelineConfig
    from fastvideo.utils import maybe_download_model
    
    # Env knobs (set BEFORE importing fastvideo where possible — but
    # FASTVIDEO_ATTENTION_BACKEND is fine here because the worker reads it
    # on generator construction).
    os.environ.setdefault("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
    os.environ.setdefault("FASTVIDEO_STAGE_LOGGING", "1")
    
    # Inductor knobs. The first one (shape_padding=False) is mandatory on
    # Blackwell to avoid a cuBLAS INVALID_VALUE crash inside pad_mm during
    # the refine path. The rest are autotune-friendliness flags.
    _inductor.shape_padding = False
    _inductor.conv_1x1_as_mm = True
    _inductor.coordinate_descent_tuning = True
    _inductor.coordinate_descent_check_all_directions = True
    _inductor.epilogue_fusion = False
    
    MODEL_ID = os.path.expandvars(os.path.expanduser(os.getenv("LTX23_MODEL_PATH",
                                                               "FastVideo/LTX-2.3-Distilled-Diffusers")))
    OUTPUT_DIR = Path(os.getenv("LTX23_OUTPUT_DIR", "outputs_video/ltx2_3_distilled_i2v"))
    I2V_IMAGE = os.getenv("LTX23_I2V_IMAGE", "")
    DEFAULT_PROMPT = ("A fashion model takes a slow step forward and shifts her weight, "
                      "the soft fabric of her clothing swaying and rippling with the "
                      "motion, her hair shifting gently, soft even studio lighting on a "
                      "clean light background, elegant slow-motion runway feel.")
    PROMPT = os.getenv("LTX23_I2V_PROMPT", DEFAULT_PROMPT)
    
    # Per-stage timing helpers --------------------------------------------------
    
    
    def _print_stage_breakdown(result: dict, label: str) -> float | None:
        """Print stage execution times and return the sum, or None if missing."""
        logging_info = result.get("logging_info")
        stages = getattr(logging_info, "stages", None) if logging_info else None
        if not stages:
            print(f"  [{label}] stage breakdown unavailable")
            return None
        print(f"  [{label}] stage breakdown:")
        total = 0.0
        for name, metrics in stages.items():
            exec_s = float(metrics.get("execution_time", 0.0))
            total += exec_s
            print(f"    - {name}: {exec_s:.3f}s")
        print(f"    - stage_sum: {total:.3f}s")
        return total
    
    
    def _collect_stage_times(
        result: dict,
        stage_times: dict[str, list[float]],
        stage_order: OrderedDict[str, None],
    ) -> None:
        logging_info = result.get("logging_info")
        stages = getattr(logging_info, "stages", None) if logging_info else None
        if not stages:
            return
        for name, metrics in stages.items():
            stage_order.setdefault(name, None)
            stage_times.setdefault(name, []).append(float(metrics.get("execution_time", 0.0)))
    
    
    def _resolve_refine_upsampler(model_root: str) -> Path:
        """LTX-2.3 distilled snapshots ship a `spatial_upscaler/` subdir."""
        for name in ("spatial_upscaler", "spatial_upsampler"):
            cand = Path(model_root) / name
            if (cand / "config.json").is_file():
                return cand
        raise FileNotFoundError(f"No refine upsampler directory under {model_root}. "
                                f"Expected `{model_root}/spatial_upscaler/config.json`.")
    
    
    # Main ---------------------------------------------------------------------
    
    
    def main() -> None:
        if not I2V_IMAGE:
            raise SystemExit("LTX23_I2V_IMAGE is required for i2v. Example:\n"
                             "  export LTX23_I2V_IMAGE=/path/to/portrait_or_product.jpg\n"
                             "  python examples/inference/basic/basic_ltx2_3_distilled_i2v.py")
        if not Path(I2V_IMAGE).is_file():
            raise SystemExit(f"LTX23_I2V_IMAGE not found: {I2V_IMAGE}")
    
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        model_root = maybe_download_model(MODEL_ID)
        refine_upsampler_path = _resolve_refine_upsampler(model_root)
        print(f"Model:           {model_root}")
        print(f"Refine upsampler: {refine_upsampler_path}")
        print(f"i2v image:       {I2V_IMAGE}")
        print(f"Output dir:      {OUTPUT_DIR.resolve()}")
    
        # mode="default" — Inductor's default schedule matches max-autotune on
        # this pipeline (denoise/refine/decode all within ~5 ms, n=2) while
        # saving ~7 min of cold compile on a single GB200.
        torch_compile_kwargs = {
            "backend": "inductor",
            "fullgraph": True,
            "mode": "default",
            "dynamic": False,
        }
    
        # Loading the pipeline config *with model_path* binds model-specific
        # tuning (notably VAE precision/decoder defaults) into the config. Without
        # this, the generic pipeline config gives a substantially slower VAE
        # decode stage. `basic_ltx2_distilled_fast_profile.py` uses the same
        # pattern.
        pipeline_config = PipelineConfig.from_pretrained(model_root)
        pipeline_config.dit_config.quant_config = None
    
        generator = VideoGenerator.from_pretrained(
            model_root,
            num_gpus=1,
            # LTX-2.3 distilled uses the two-stage refine pipeline; the refine
            # LoRA is intentionally empty for the distilled student.
            ltx2_refine_enabled=True,
            ltx2_refine_upsampler_path=str(refine_upsampler_path),
            ltx2_refine_lora_path="",
            ltx2_refine_num_inference_steps=3,
            ltx2_refine_guidance_scale=1.0,
            ltx2_refine_add_noise=True,
            pipeline_config=pipeline_config,
            enable_torch_compile=True,
            enable_torch_compile_text_encoder=True,
            # Compile the VAE codec submodules (encoder / decoder) too. The
            # `LTX2CausalVideoAutoencoder` declares `_compile_conditions` so
            # `_compile_with_conditions` targets just those submodules and
            # leaves the surrounding tiling control flow eager — needed for
            # fullgraph + dynamic=False to succeed. VAE eager decode is
            # ~1.0s; compiling it brings the stage to ~0.3s.
            enable_torch_compile_vae=True,
            torch_compile_kwargs=torch_compile_kwargs,
            torch_compile_kwargs_vae=torch_compile_kwargs,
            # Keep everything resident — no CPU offload for serving-style runs.
            dit_cpu_offload=False,
            text_encoder_cpu_offload=False,
            vae_cpu_offload=False,
            ltx2_vae_tiling=False,
        )
    
        common_kwargs = dict(
            prompt=PROMPT,
            negative_prompt="",  # distilled is CFG-free; no negative needed
            guidance_scale=1.0,  # CFG=1 for distilled
            height=1280,
            width=832,  # portrait runway aspect
            num_frames=121,
            fps=24,  # ~5s clip
            num_inference_steps=8,  # distilled denoise steps
            # i2v: anchor the input image at frame 0 with full strength.
            # `ltx2_image_crf=0.0` skips an extra JPEG re-encode of an already
            # JPEG conditioning image.
            ltx2_images=[(I2V_IMAGE, 0, 1.0)],
            ltx2_image_crf=0.0,
            save_video=True,
        )
    
        warmup_runs = 2
        measured_runs = 2
        warmup_secs: list[float] = []
        measured_secs: list[float] = []
        stage_times: dict[str, list[float]] = {}
        stage_order: OrderedDict[str, None] = OrderedDict()
    
        try:
            # Warmup: untimed (but we still wall-clock them so the first compile
            # cost is visible to the reader).
            for w in range(warmup_runs):
                t0 = time.perf_counter()
                print(f"\n[warmup {w + 1}/{warmup_runs}] compiling + generating…")
                generator.generate_video(
                    output_path=str(OUTPUT_DIR / f"_warmup_{w + 1}.mp4"),
                    seed=7,
                    **common_kwargs,
                )
                dt = time.perf_counter() - t0
                warmup_secs.append(dt)
                print(f"[warmup {w + 1}/{warmup_runs}] wall={dt:.1f}s")
    
            # Cleanup warmup artifacts so the user only sees measured outputs.
            for w in range(warmup_runs):
                (OUTPUT_DIR / f"_warmup_{w + 1}.mp4").unlink(missing_ok=True)
    
            # Measured.
            for m in range(measured_runs):
                out_path = OUTPUT_DIR / f"output_ltx2_3_distilled_i2v_run_{m + 1}.mp4"
                print(f"\n[measured {m + 1}/{measured_runs}] generating: {out_path}")
                t0 = time.perf_counter()
                result = generator.generate_video(
                    output_path=str(out_path),
                    seed=2002 + m,
                    **common_kwargs,
                )
                wall = time.perf_counter() - t0
                e2e = (result.get("e2e_latency") if isinstance(result, dict) else None) or wall
                measured_secs.append(e2e)
                print(f"[measured {m + 1}/{measured_runs}] e2e={e2e:.2f}s wall={wall:.2f}s")
                if isinstance(result, dict):
                    _print_stage_breakdown(result, f"measured {m + 1}")
                    _collect_stage_times(result, stage_times, stage_order)
    
            # Summary.
            print("\n=== summary ===")
            print(f"warmup wall-times:      {[round(x, 1) for x in warmup_secs]}")
            if measured_secs:
                avg = sum(measured_secs) / len(measured_secs)
                print(f"measured e2e (n={len(measured_secs)}): "
                      f"{[round(x, 2) for x in measured_secs]} -> avg {avg:.2f}s")
            if stage_times:
                print(f"average stage times over {measured_runs} measured runs:")
                avg_total = 0.0
                for name in stage_order:
                    vals = stage_times.get(name) or []
                    if not vals:
                        continue
                    avg_v = sum(vals) / len(vals)
                    avg_total += avg_v
                    print(f"  - {name}: {avg_v:.3f}s")
                print(f"  - stage_sum_avg: {avg_total:.3f}s")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_3_distilled_i2v_typed.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """LTX-2.3 distilled image-to-video — typed API (``from_config`` / ``generate``).
    
    Identical generation behavior to ``basic_ltx2_3_distilled_i2v.py``, but
    expressed through the newer typed surface (``GeneratorConfig`` /
    ``GenerationRequest``) instead of the ``from_pretrained(**legacy_kwargs)``
    bridge. The typed API is now the preferred entry point — the legacy
    example still works but emits a ``DeprecationWarning`` for the LTX-2.3
    specific knobs.
    
    Quick start
    -----------
        export LTX23_I2V_IMAGE=/path/to/your/portrait_or_product.jpg
        # optional overrides:
        #   export LTX23_I2V_PROMPT="a fashion model walks toward camera..."
        #   export LTX23_OUTPUT_DIR=outputs_video/ltx2_3_distilled_i2v_typed
        python examples/inference/basic/basic_ltx2_3_distilled_i2v_typed.py
    
    What the script does
    --------------------
    1. Loads FastVideo/LTX-2.3-Distilled-Diffusers (8 denoise + 3 refine
       steps, CFG=1, no refine LoRA — the distilled production recipe).
    2. Compiles the DiT, text encoder, and VAE (fullgraph, Inductor default
       mode — autotune adds ~7 min cold-compile here with no measurable
       e2e gain).
    3. Runs 2 warmup calls (untimed) + 2 measured calls. Two warmups are
       kept as a safety net — the first call pays cold compile + first-shape
       guard work, and a second warmup ensures any residual recompiles
       settle before we measure.
    4. Prints a per-stage breakdown and an average over the measured runs.
    
    Hardware notes
    --------------
    - Single-GPU example; for multi-GPU sequence-parallel see the gradio
      demo under ``examples/inference/gradio/local/gradio_local_demo_ltx2_3/``.
    - First-time compile takes ~30-40 min on GB200 (~20 min on H100;
      cached in ``$TORCHINDUCTOR_CACHE_DIR`` afterwards). Subsequent
      invocations only pay the one-time process load + a few seconds of
      dynamo trace.
    - On GB200 / Blackwell, run with ``env -u LD_LIBRARY_PATH ...`` to
      avoid a system-cuBLAS / torch-cuBLAS mismatch that fails every GEMM.
      The ``_inductor.shape_padding = False`` line below also avoids a
      ``pad_mm`` landmine on the same generation of cards.
    
    Typed-API mapping (legacy kwarg ↔ typed field)
    ----------------------------------------------
    - ``num_gpus``                      ↔ ``engine.num_gpus``
    - ``enable_torch_compile``          ↔ ``engine.compile.enabled``
    - ``enable_torch_compile_text_encoder`` ↔ ``engine.compile.text_encoder_enabled``
    - ``enable_torch_compile_vae``      ↔ ``engine.compile.vae_enabled``
    - ``torch_compile_kwargs``          ↔ ``engine.compile.backend/fullgraph/mode/dynamic``
    - ``torch_compile_kwargs_vae``      ↔ empty ``compile.vae_kwargs`` (inherits master)
    - ``dit_cpu_offload``               ↔ ``engine.offload.dit``
    - ``text_encoder_cpu_offload``      ↔ ``engine.offload.text_encoder``
    - ``vae_cpu_offload``               ↔ ``engine.offload.vae``
    - ``ltx2_vae_tiling``               ↔ ``pipeline.vae_tiling``
    - ``ltx2_refine_enabled``           ↔ ``pipeline.preset_overrides["refine"]["enabled"]``
    - ``ltx2_refine_upsampler_path``    ↔ ``pipeline.components.upsampler_weights``
    - ``ltx2_refine_lora_path``         ↔ ``pipeline.components.lora_path``
    - ``ltx2_refine_num_inference_steps`` ↔ ``pipeline.preset_overrides["refine"]["num_inference_steps"]``
    - ``ltx2_refine_guidance_scale``    ↔ ``pipeline.preset_overrides["refine"]["guidance_scale"]``
    - ``ltx2_refine_add_noise``         ↔ ``pipeline.preset_overrides["refine"]["add_noise"]``
    - ``pipeline_config=PipelineConfig.from_pretrained(model_root)`` ↔ (no-op — ``PipelineConfig.from_kwargs`` already resolves the model-specific class from ``model_path``)
    - ``pipeline_config.dit_config.quant_config = None`` ↔ leave ``engine.quantization`` unset
    - ``ltx2_images`` / ``ltx2_image_crf`` ↔ ``request.extensions`` (LTX-2 specific, no
      first-class typed field yet)
    """
    from __future__ import annotations
    
    import os
    import time
    from collections import OrderedDict
    from pathlib import Path
    
    import torch._inductor.config as _inductor
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        PipelineSelection,
        SamplingConfig,
    )
    from fastvideo.utils import maybe_download_model
    
    os.environ.setdefault("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
    os.environ.setdefault("FASTVIDEO_STAGE_LOGGING", "1")
    
    # Inductor knobs. ``shape_padding=False`` is mandatory on Blackwell to
    # avoid a cuBLAS INVALID_VALUE crash inside pad_mm during the refine
    # path. The rest are autotune-friendliness flags.
    _inductor.shape_padding = False
    _inductor.conv_1x1_as_mm = True
    _inductor.coordinate_descent_tuning = True
    _inductor.coordinate_descent_check_all_directions = True
    _inductor.epilogue_fusion = False
    
    MODEL_ID = os.path.expandvars(os.path.expanduser(os.getenv("LTX23_MODEL_PATH",
                                                               "FastVideo/LTX-2.3-Distilled-Diffusers")))
    OUTPUT_DIR = Path(os.getenv("LTX23_OUTPUT_DIR", "outputs_video/ltx2_3_distilled_i2v_typed"))
    I2V_IMAGE = os.getenv("LTX23_I2V_IMAGE", "")
    DEFAULT_PROMPT = ("A fashion model takes a slow step forward and shifts her weight, "
                      "the soft fabric of her clothing swaying and rippling with the "
                      "motion, her hair shifting gently, soft even studio lighting on a "
                      "clean light background, elegant slow-motion runway feel.")
    PROMPT = os.getenv("LTX23_I2V_PROMPT", DEFAULT_PROMPT)
    
    
    def _print_stage_breakdown(result, label: str) -> float | None:
        logging_info = getattr(result, "logging_info", None)
        stages = getattr(logging_info, "stages", None) if logging_info else None
        if not stages:
            print(f"  [{label}] stage breakdown unavailable")
            return None
        print(f"  [{label}] stage breakdown:")
        total = 0.0
        for name, metrics in stages.items():
            exec_s = float(metrics.get("execution_time", 0.0))
            total += exec_s
            print(f"    - {name}: {exec_s:.3f}s")
        print(f"    - stage_sum: {total:.3f}s")
        return total
    
    
    def _collect_stage_times(
        result,
        stage_times: dict[str, list[float]],
        stage_order: OrderedDict[str, None],
    ) -> None:
        logging_info = getattr(result, "logging_info", None)
        stages = getattr(logging_info, "stages", None) if logging_info else None
        if not stages:
            return
        for name, metrics in stages.items():
            stage_order.setdefault(name, None)
            stage_times.setdefault(name, []).append(float(metrics.get("execution_time", 0.0)))
    
    
    def _resolve_refine_upsampler(model_root: str) -> Path:
        for name in ("spatial_upscaler", "spatial_upsampler"):
            cand = Path(model_root) / name
            if (cand / "config.json").is_file():
                return cand
        raise FileNotFoundError(f"No refine upsampler directory under {model_root}. "
                                f"Expected `{model_root}/spatial_upscaler/config.json`.")
    
    
    def main() -> None:
        if not I2V_IMAGE:
            raise SystemExit("LTX23_I2V_IMAGE is required for i2v. Example:\n"
                             "  export LTX23_I2V_IMAGE=/path/to/portrait_or_product.jpg\n"
                             "  python examples/inference/basic/"
                             "basic_ltx2_3_distilled_i2v_typed.py")
        if not Path(I2V_IMAGE).is_file():
            raise SystemExit(f"LTX23_I2V_IMAGE not found: {I2V_IMAGE}")
    
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        model_root = maybe_download_model(MODEL_ID)
        refine_upsampler_path = _resolve_refine_upsampler(model_root)
        print(f"Model:           {model_root}")
        print(f"Refine upsampler: {refine_upsampler_path}")
        print(f"i2v image:       {I2V_IMAGE}")
        print(f"Output dir:      {OUTPUT_DIR.resolve()}")
    
        # mode="default" — Inductor's default schedule matches max-autotune on
        # this pipeline (denoise/refine/decode all within ~5 ms, n=2) while
        # saving ~7 min of cold compile on a single GB200.
        generator_config = GeneratorConfig(
            model_path=model_root,
            engine=EngineConfig(
                num_gpus=1,
                # Keep DiT / text encoder / VAE resident on GPU — no CPU offload
                # for serving-style runs. ``image_encoder`` and
                # ``pin_cpu_memory`` are left at their schema defaults
                # (matches the legacy example, which only set these three).
                offload=OffloadConfig(
                    dit=False,
                    text_encoder=False,
                    vae=False,
                ),
                compile=CompileConfig(
                    enabled=True,
                    text_encoder_enabled=True,
                    # ``vae_enabled`` triggers ``_compile_with_conditions`` on
                    # ``LTX2CausalVideoAutoencoder``, which compiles just the
                    # encoder/decoder submodules and leaves the surrounding
                    # tiling control flow eager (required for ``fullgraph``).
                    # Empty ``vae_kwargs`` → inherits the master kwargs below.
                    vae_enabled=True,
                    backend="inductor",
                    fullgraph=True,
                    mode="default",
                    dynamic=False,
                ),
            ),
            pipeline=PipelineSelection(
                # ``PipelineConfig.from_kwargs`` resolves the model-specific
                # pipeline-config class from ``model_path`` automatically, so we
                # don't need to set ``components.pipeline_config_path`` — the
                # model-specific VAE precision / decoder defaults are picked up
                # the same way the legacy example's
                # ``PipelineConfig.from_pretrained(model_root)`` did them.
                components=ComponentConfig(upsampler_weights=str(refine_upsampler_path),
                                           # Distilled has no refine LoRA — omit ``lora_path``.
                                           ),
                vae_tiling=False,
                preset_overrides={
                    "refine": {
                        "enabled": True,
                        "num_inference_steps": 3,
                        "guidance_scale": 1.0,
                        "add_noise": True,
                    },
                },
            ),
        )
    
        generator = VideoGenerator.from_config(generator_config)
    
        def build_request(out_path: Path, seed: int) -> GenerationRequest:
            return GenerationRequest(
                prompt=PROMPT,
                # distilled is CFG-free; no negative prompt
                negative_prompt="",
                sampling=SamplingConfig(
                    num_videos_per_prompt=1,
                    seed=seed,
                    height=1280,
                    width=832,
                    num_frames=121,
                    fps=24,
                    num_inference_steps=8,
                    guidance_scale=1.0,
                ),
                output=OutputConfig(
                    output_path=str(out_path),
                    save_video=True,
                    return_frames=False,
                ),
                # LTX-2.3 i2v fields don't have first-class typed slots yet;
                # extensions is the documented bridge. ``ltx2_image_crf=0.0``
                # skips an extra JPEG re-encode of an already JPEG image.
                extensions={
                    "ltx2_images": [(I2V_IMAGE, 0, 1.0)],
                    "ltx2_image_crf": 0.0,
                },
            )
    
        warmup_runs = 2
        measured_runs = 2
        warmup_secs: list[float] = []
        measured_secs: list[float] = []
        stage_times: dict[str, list[float]] = {}
        stage_order: OrderedDict[str, None] = OrderedDict()
    
        try:
            for w in range(warmup_runs):
                print(f"\n[warmup {w + 1}/{warmup_runs}] compiling + generating…")
                t0 = time.perf_counter()
                generator.generate(build_request(OUTPUT_DIR / f"_warmup_{w + 1}.mp4", seed=7))
                dt = time.perf_counter() - t0
                warmup_secs.append(dt)
                print(f"[warmup {w + 1}/{warmup_runs}] wall={dt:.1f}s")
    
            for w in range(warmup_runs):
                (OUTPUT_DIR / f"_warmup_{w + 1}.mp4").unlink(missing_ok=True)
    
            for m in range(measured_runs):
                out_path = (OUTPUT_DIR / f"output_ltx2_3_distilled_i2v_typed_run_{m + 1}.mp4")
                print(f"\n[measured {m + 1}/{measured_runs}] generating: {out_path}")
                t0 = time.perf_counter()
                result = generator.generate(build_request(out_path, seed=2002 + m))
                wall = time.perf_counter() - t0
                # ``e2e_latency`` is currently surfaced via ``result.extra``;
                # ``GenerationResult`` exposes ``generation_time`` as a
                # first-class field but the LTX-2 pipeline only fills the
                # legacy ``e2e_latency`` key. Prefer the explicit one, fall
                # back to wall-clock.
                e2e = (result.extra.get("e2e_latency") if hasattr(result, "extra") else None) or wall
                measured_secs.append(e2e)
                print(f"[measured {m + 1}/{measured_runs}] "
                      f"e2e={e2e:.2f}s wall={wall:.2f}s")
                _print_stage_breakdown(result, f"measured {m + 1}")
                _collect_stage_times(result, stage_times, stage_order)
    
            print("\n=== summary ===")
            print(f"warmup wall-times:      "
                  f"{[round(x, 1) for x in warmup_secs]}")
            if measured_secs:
                avg = sum(measured_secs) / len(measured_secs)
                print(f"measured e2e (n={len(measured_secs)}): "
                      f"{[round(x, 2) for x in measured_secs]} -> avg {avg:.2f}s")
            if stage_times:
                print(f"average stage times over {measured_runs} measured runs:")
                avg_total = 0.0
                for name in stage_order:
                    vals = stage_times.get(name) or []
                    if not vals:
                        continue
                    avg_v = sum(vals) / len(vals)
                    avg_total += avg_v
                    print(f"  - {name}: {avg_v:.3f}s")
                print(f"  - stage_sum_avg: {avg_total:.3f}s")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_5_i2av.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate synchronized video and audio from an image and text with LTX-2.5."""
    
    from __future__ import annotations
    
    import argparse
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    MODEL_IDS = {
        "distilled": "FastVideo/LTX-2.5-Distilled-Diffusers",
        "dev": "FastVideo/LTX-2.5-Dev-Diffusers",
    }
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--variant", choices=tuple(MODEL_IDS), default="distilled")
        parser.add_argument(
            "--model-path",
            help="FastVideo-converted model directory or Hub ID; the raw split Lightricks repo is not directly loadable.",
        )
        parser.add_argument("--image", required=True)
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs/ltx2_5_i2av.mp4")
        parser.add_argument("--height", type=int)
        parser.add_argument("--width", type=int)
        parser.add_argument("--num-frames", type=int, default=121)
        parser.add_argument("--steps", type=int)
        parser.add_argument("--seed", type=int, default=10)
        parser.add_argument("--num-gpus", type=int, default=4)
        parser.add_argument("--torch-compile", action="store_true", help="Compile the transformer denoising path")
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        image_path = Path(args.image)
        if not image_path.is_file():
            raise SystemExit(f"Conditioning image not found: {image_path}")
    
        is_distilled = args.variant == "distilled"
        model_path = args.model_path or MODEL_IDS[args.variant]
        height = args.height or (1024 if is_distilled else 512)
        width = args.width or (1536 if is_distilled else 768)
        steps = args.steps or (8 if is_distilled else 30)
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=model_path,
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=False,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                    ),
                    compile=CompileConfig(enabled=args.torch_compile),
                ),
                pipeline=PipelineSelection(workload_type="i2v"),
            ))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    sampling=SamplingConfig(
                        seed=args.seed,
                        height=height,
                        width=width,
                        num_frames=args.num_frames,
                        fps=24,
                        num_inference_steps=steps,
                        guidance_scale=1.0 if is_distilled else 3.0,
                    ),
                    output=OutputConfig(
                        output_path=str(output_path),
                        save_video=True,
                        return_frames=False,
                    ),
                    extensions={
                        "ltx2_images": [(str(image_path), 0, 1.0)],
                        "ltx2_image_crf": 18.0,
                    },
                ))
            print(f"Synchronized video and audio written to: {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_5_t2av.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate synchronized video and audio from text with LTX-2.5."""
    
    from __future__ import annotations
    
    import argparse
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    MODEL_IDS = {
        "distilled": "FastVideo/LTX-2.5-Distilled-Diffusers",
        "dev": "FastVideo/LTX-2.5-Dev-Diffusers",
    }
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--variant", choices=tuple(MODEL_IDS), default="distilled")
        parser.add_argument(
            "--model-path",
            help="FastVideo-converted model directory or Hub ID; the raw split Lightricks repo is not directly loadable.",
        )
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs/ltx2_5_t2av.mp4")
        parser.add_argument("--height", type=int)
        parser.add_argument("--width", type=int)
        parser.add_argument("--num-frames", type=int, default=121)
        parser.add_argument("--steps", type=int)
        parser.add_argument("--seed", type=int, default=10)
        parser.add_argument("--num-gpus", type=int, default=4)
        parser.add_argument("--torch-compile", action="store_true", help="Compile the transformer denoising path")
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        is_distilled = args.variant == "distilled"
        model_path = args.model_path or MODEL_IDS[args.variant]
        height = args.height or (1024 if is_distilled else 512)
        width = args.width or (1536 if is_distilled else 768)
        steps = args.steps or (8 if is_distilled else 30)
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=model_path,
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=False,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                    ),
                    compile=CompileConfig(enabled=args.torch_compile),
                ),
                pipeline=PipelineSelection(workload_type="t2v"),
            ))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    sampling=SamplingConfig(
                        seed=args.seed,
                        height=height,
                        width=width,
                        num_frames=args.num_frames,
                        fps=24,
                        num_inference_steps=steps,
                        guidance_scale=1.0 if is_distilled else 3.0,
                    ),
                    output=OutputConfig(
                        output_path=str(output_path),
                        save_video=True,
                        return_frames=False,
                    ),
                ))
            print(f"Synchronized video and audio written to: {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_distilled.py"

    ```py
    from fastvideo import VideoGenerator
    
    PROMPT = ("A warm sunny backyard. The camera starts in a tight cinematic close-up "
              "of a woman and a man in their 30s, facing each other with serious "
              "expressions. The woman, emotional and dramatic, says softly, \"That's "
              "it... Dad's lost it. And we've lost Dad.\" The man exhales, slightly "
              "annoyed: \"Stop being so dramatic, Jess.\" A beat. He glances aside, "
              "then mutters defensively, \"He's just having fun.\" The camera slowly "
              "pans right, revealing the grandfather in the garden wearing enormous "
              "butterfly wings, waving his arms in the air like he's trying to take "
              "off. He shouts, \"Wheeeew!\" as he flaps his wings with full commitment. "
              "The woman covers her face, on the verge of tears. The tone is deadpan, "
              "absurd, and quietly tragic.")
    import os
    
    os.environ["FASTVIDEO_ATTENTION_BACKEND"] = "FLASH_ATTN"
    
    
    def main() -> None:
        generator = VideoGenerator.from_pretrained(
            "FastVideo/LTX2-Distilled-Diffusers",
            num_gpus=4,
        )
    
        output_path = "outputs_video/ltx2_basic/output_ltx2_distilled_t2v.mp4"
        generator.generate_video(
            prompt=PROMPT,
            output_path=output_path,
            save_video=True,
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ltx2_distilled_fast_profile.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    import json
    import os
    import time
    from collections import OrderedDict
    from pathlib import Path
    
    import torch
    import torch._inductor.config
    from fastvideo import VideoGenerator
    from fastvideo.configs.pipelines.base import PipelineConfig
    from fastvideo.layers.quantization.nvfp4_config import NVFP4Config
    from fastvideo.utils import maybe_download_model
    
    VALIDATION_JSON = (Path(__file__).resolve().parents[2] / "training" / "finetune" / "ltx2" / "validation.json")
    
    # Override with a local snapshot or converted directory when needed, e.g.
    #   export LTX2_MODEL_PATH=/raid/$USER/hf/FastVideo/LTX2-Distilled-Diffusers
    MODEL_ID = os.path.expandvars(os.path.expanduser(os.getenv("LTX2_MODEL_PATH", "FastVideo/LTX2-Distilled-Diffusers")))
    OUTPUT_DIR = Path("outputs_video/ltx2_distilled_fast_profile")
    
    os.environ["FASTVIDEO_ATTENTION_BACKEND"] = "FLASH_ATTN"
    os.environ["FASTVIDEO_STAGE_LOGGING"] = "1"
    
    # Tune Inductor flags
    config = torch._inductor.config
    config.conv_1x1_as_mm = True  # treat 1x1 convolutions as matrix muls
    config.coordinate_descent_tuning = True
    config.coordinate_descent_check_all_directions = True
    config.epilogue_fusion = False  # do not fuse pointwise ops into matmuls
    
    
    def load_validation_entries(path: Path) -> list[dict]:
        with path.open(encoding="utf-8") as f:
            data = json.load(f)
    
        if isinstance(data, dict) and isinstance(data.get("data"), list):
            return [entry for entry in data["data"] if isinstance(entry, dict)]
    
        raise ValueError(f"Unsupported validation format in {path}. Expected {{'data': [...]}}.")
    
    
    def print_stage_breakdown(
        result: dict,
        run_idx: int,
        num_runs: int,
    ) -> float | None:
        logging_info = result.get("logging_info")
        if logging_info is None:
            print(f"[{run_idx}/{num_runs}] Stage breakdown unavailable: no logging_info")
            return None
    
        stages = getattr(logging_info, "stages", None)
        if not stages:
            print(f"[{run_idx}/{num_runs}] Stage breakdown unavailable: no stage timings")
            return None
    
        print(f"[{run_idx}/{num_runs}] Stage breakdown:")
        total = 0.0
        for stage_name, stage_metrics in stages.items():
            exec_time = float(stage_metrics.get("execution_time", 0.0))
            total += exec_time
            print(f"  - {stage_name}: {exec_time:.3f}s")
        print(f"  - total(stage sum): {total:.3f}s")
        return total
    
    
    def extract_sr_forward_latency(result: dict, ) -> tuple[float | None, list[tuple[str, float]], list[str]]:
        logging_info = result.get("logging_info")
        if logging_info is None:
            return None, [], []
    
        stages = getattr(logging_info, "stages", None)
        if not stages:
            return None, [], []
    
        stage_names = list(stages.keys())
        sr_match_substr = os.getenv("FASTVIDEO_SR_LATENCY_STAGE_SUBSTR", "").strip().lower()
    
        sr_stage_entries: list[tuple[str, float]] = []
        for stage_name, stage_metrics in stages.items():
            stage_name_l = stage_name.lower()
            if sr_match_substr:
                is_sr_stage = sr_match_substr in stage_name_l
            else:
                is_sr_stage = ("srdenoisingstage" in stage_name_l or "sr_denoising" in stage_name_l
                               or "upsample" in stage_name_l or ("refine" in stage_name_l and "denois" in stage_name_l))
            if not is_sr_stage:
                continue
            exec_time = float(stage_metrics.get("execution_time", 0.0))
            sr_stage_entries.append((stage_name, exec_time))
    
        if not sr_stage_entries:
            return None, [], stage_names
        return sum(x[1] for x in sr_stage_entries), sr_stage_entries, stage_names
    
    
    def collect_stage_times(
        result: dict,
        stage_times: dict[str, list[float]],
        stage_order: OrderedDict[str, None],
    ) -> None:
        logging_info = result.get("logging_info")
        if logging_info is None:
            return
        stages = getattr(logging_info, "stages", None)
        if not stages:
            return
        for stage_name, stage_metrics in stages.items():
            stage_order.setdefault(stage_name, None)
            exec_time = float(stage_metrics.get("execution_time", 0.0))
            stage_times.setdefault(stage_name, []).append(exec_time)
    
    
    def print_stage_averages(
        stage_times: dict[str, list[float]],
        stage_order: OrderedDict[str, None],
        measured_runs: int,
    ) -> None:
        if measured_runs <= 0:
            return
        if not stage_times:
            print("No stage timings collected for measured runs.")
            return
    
        print(f"Average stage times over {measured_runs} measured runs:")
        total_avg = 0.0
        for stage_name in stage_order.keys():
            times = stage_times.get(stage_name, [])
            if not times:
                continue
            avg = sum(times) / len(times)
            total_avg += avg
            print(f"  - {stage_name}: {avg:.3f}s")
        print(f"  - total(stage sum avg): {total_avg:.3f}s")
    
    
    def resolve_refine_upsampler_path(model_root: str) -> Path:
        root = Path(model_root)
        candidates = [
            root / "spatial_upscaler",
            root / "spatial_upsampler",
        ]
    
        env_path = os.getenv("LTX2_REFINE_UPSAMPLER_PATH")
        if env_path:
            candidates.insert(0, Path(os.path.expandvars(os.path.expanduser(env_path))))
    
        for candidate in candidates:
            if (candidate / "config.json").is_file():
                return candidate
    
        checked = "\n".join(f"  - {candidate}" for candidate in candidates)
        raise FileNotFoundError("Could not find an LTX2 refine upsampler directory.\n"
                                "Checked:\n"
                                f"{checked}")
    
    
    def main() -> None:
        if not VALIDATION_JSON.exists():
            raise FileNotFoundError(f"Validation file not found: {VALIDATION_JSON}")
    
        validation_entries = load_validation_entries(VALIDATION_JSON)
        if not validation_entries:
            raise ValueError(f"No validation entries found in {VALIDATION_JSON}")
    
        benchmark_entry = validation_entries[0]
        prompt = benchmark_entry.get("caption")
        if not isinstance(prompt, str) or not prompt.strip():
            raise ValueError("First validation entry is missing a usable caption")
    
        num_runs = 12
        warmup_runs = 2
        avg_window = num_runs - warmup_runs
        measured_start_idx = max(warmup_runs, num_runs - avg_window)
    
        model_root = maybe_download_model(MODEL_ID)
        refine_upsampler_path = resolve_refine_upsampler_path(model_root)
        print(f"Using refine upsampler: {refine_upsampler_path}")
    
        pipeline_config = PipelineConfig.from_pretrained(model_root)
        # LTX-2 NVFP4 deploy contract (train==deploy surface):
        #   * Linears: NVFP4 block-scaled GEMMs (per-16 E2M1 + E4M3 SFs) on every
        #     arch, via flashinfer.
        #   * ATTN_QAT_INFER attention differs per arch: sm_120a/sm_121a use the
        #     fastvideo-kernel CUTLASS (SageAttention3-FP4) scheme that
        #     ATTN_QAT_TRAIN simulates; sm_100a (GB200) / sm_103a (GB300) use the
        #     FP4 FA4 kernel (flash-attention-fp4) with per-16 block-scaled NVFP4
        #     Q/K and BF16 P/V -- a train-sim mismatch that is gated by MS-SSIM
        #     measurement, not assumed equal. The selection receipt is logged at
        #     backend resolution ("ATTN_QAT_INFER resolved: ...").
        # Original-weight retention: the default purges the always-FP4 layers'
        # bf16 originals after conversion. Refine-only layers (the cross-modal
        # AV projections) always keep theirs: the base stage profile runs them
        # dense by deployment contract -- in the two-stage fast profile AND the
        # distilled single-stage deploy. retain_original_weights=True keeps
        # everything (debugging).
        pipeline_config.dit_config.quant_config = NVFP4Config()
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        torch_compile_kwargs = {
            "backend": "inductor",
            "fullgraph": True,
            # Uncomment for final best-performance profiling. It is disabled
            # for faster development iteration because autotuning is slow.
            # "mode": "max-autotune-no-cudagraphs",
            "dynamic": False,
        }
    
        generator = VideoGenerator.from_pretrained(
            model_root,
            num_gpus=1,
            ltx2_refine_enabled=True,
            ltx2_refine_upsampler_path=str(refine_upsampler_path),
            refine_lora_path="",  # keep refine LoRA disabled in this repo's typed adapter
            ltx2_refine_lora_path="",  # keep refine LoRA disabled for distilled model
            ltx2_refine_num_inference_steps=2,
            ltx2_refine_guidance_scale=1.0,
            ltx2_refine_add_noise=True,
            pipeline_config=pipeline_config,
            enable_torch_compile=True,
            enable_torch_compile_text_encoder=True,
            enable_torch_compile_vae=True,
            torch_compile_kwargs=torch_compile_kwargs,
            torch_compile_kwargs_vae=torch_compile_kwargs,
            dit_cpu_offload=False,
            text_encoder_cpu_offload=False,
            vae_cpu_offload=False,
            ltx2_vae_tiling=False,
        )
    
        run_times: list[float] = []
        e2e_times: list[float] = []
        sr_forward_times: list[float] = []
        non_stage_overhead_times: list[float] = []
        stage_times: dict[str, list[float]] = {}
        stage_order: OrderedDict[str, None] = OrderedDict()
    
        try:
            for i in range(num_runs):
                output_path = OUTPUT_DIR / f"output_ltx2_basic_t2v_run_{i + 1}.mp4"
                if output_path.exists():
                    output_path.unlink()
                    print(f"[{i + 1}/{num_runs}] Removed existing file: {output_path}")
    
                print(f"[{i + 1}/{num_runs}] Generating: {output_path}")
                if os.environ.get("FASTVIDEO_STAGE_LOGGING") == "0" and torch.cuda.is_available():
                    torch.cuda.synchronize()
    
                start = time.perf_counter()
                result = generator.generate_video(
                    prompt=prompt,
                    output_path=str(output_path),
                    fps=24,
                    seed=10,
                    save_video=True,
                    guidance_scale=1.0,
                    height=benchmark_entry.get("height", 1088),
                    width=benchmark_entry.get("width", 1920),
                    num_frames=121,
                    num_inference_steps=5,
                    # image_path="examples/inference/basic/prompt1.png",
                    # ltx2_image_crf=0.0
                )
                if os.environ.get("FASTVIDEO_STAGE_LOGGING") == "0":
                    torch.cuda.synchronize()
    
                elapsed = result.get("generation_time") if isinstance(result, dict) else None
                e2e_elapsed = result.get("e2e_latency") if isinstance(result, dict) else None
                if elapsed is None:
                    elapsed = time.perf_counter() - start
                if e2e_elapsed is None:
                    e2e_elapsed = time.perf_counter() - start
    
                run_times.append(elapsed)
                e2e_times.append(e2e_elapsed)
                print(f"[{i + 1}/{num_runs}] Generation time: {elapsed:.2f}s")
                print(f"[{i + 1}/{num_runs}] End-to-end latency: {e2e_elapsed:.2f}s")
    
                if isinstance(result, dict):
                    stage_sum = print_stage_breakdown(result, i + 1, num_runs)
                    if stage_sum is not None:
                        non_stage_overhead = e2e_elapsed - stage_sum
                        print(f"[{i + 1}/{num_runs}] Non-stage overhead (e2e - stage sum): {non_stage_overhead:.3f}s")
                        if i >= measured_start_idx:
                            non_stage_overhead_times.append(non_stage_overhead)
    
                    sr_forward_total, sr_stage_entries, stage_names = extract_sr_forward_latency(result)
                    if sr_forward_total is None:
                        print(f"[{i + 1}/{num_runs}] SR forward latency unavailable")
                        if stage_names:
                            print(f"    Available stage keys: {', '.join(stage_names)}")
                            print("    Tip: set FASTVIDEO_SR_LATENCY_STAGE_SUBSTR=<substring> to match your SR stage key.")
                    else:
                        print(f"[{i + 1}/{num_runs}] SR forward latency: {sr_forward_total:.3f}s")
                        for sr_stage_name, sr_exec_time in sr_stage_entries:
                            print(f"    - {sr_stage_name}: {sr_exec_time:.3f}s")
                        if i >= measured_start_idx:
                            sr_forward_times.append(sr_forward_total)
    
                    if i >= measured_start_idx:
                        collect_stage_times(result, stage_times, stage_order)
    
            measured_times = run_times[measured_start_idx:]
            avg_time = sum(measured_times) / len(measured_times)
            print(f"Average video generation time over {len(measured_times)} runs "
                  f"(runs {measured_start_idx + 1}-{len(run_times)}, skipping first {warmup_runs} warmup runs): "
                  f"{avg_time:.2f}s")
    
            measured_e2e_times = e2e_times[measured_start_idx:]
            avg_e2e_time = sum(measured_e2e_times) / len(measured_e2e_times)
            print(f"Average end-to-end latency over {len(measured_e2e_times)} runs "
                  f"(runs {measured_start_idx + 1}-{len(e2e_times)}, skipping first {warmup_runs} warmup runs): "
                  f"{avg_e2e_time:.2f}s")
    
            if sr_forward_times:
                avg_sr_forward = sum(sr_forward_times) / len(sr_forward_times)
                print(f"Average SR forward latency over {len(sr_forward_times)} runs: {avg_sr_forward:.3f}s")
            else:
                print("Average SR forward latency unavailable (no SR stages matched).")
    
            print_stage_averages(stage_times, stage_order, len(measured_times))
    
            if non_stage_overhead_times:
                avg_non_stage_overhead = sum(non_stage_overhead_times) / len(non_stage_overhead_times)
                print("Average non-stage overhead over "
                      f"{len(non_stage_overhead_times)} measured runs: {avg_non_stage_overhead:.3f}s")
            else:
                print("Average non-stage overhead unavailable (no stage timings).")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_lucy_edit.py"

    ```py
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_lucy_edit"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "decart-ai/Lucy-Edit-Dev",
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=True,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        prompt = ("Change the apron and blouse to a classic clown costume: satin "
                  "polka-dot jumpsuit in bright primary colors, ruffled white collar, "
                  "oversized pom-pom buttons, white gloves, oversized red shoes, red "
                  "foam nose; soft window light from left, eye-level medium shot.")
        video_path = "https://d2drjpuinn46lb.cloudfront.net/painter_original_edit.mp4"
    
        generator.generate_video(
            prompt,
            negative_prompt="",
            video_path=video_path,
            output_path=OUTPUT_PATH,
            save_video=True,
            height=480,
            width=832,
            num_frames=81,
            fps=24,
            guidance_scale=5.0,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_matrixgame2.py"

    ```py
    from fastvideo import VideoGenerator
    from fastvideo.models.dits.matrixgame2.utils import create_action_presets
    
    import torch
    
    # Available variants: "base_distilled_model", "gta_distilled_model", "templerun_distilled_model"
    # Each variant has different keyboard_dim:
    #   - base_distilled_model: keyboard_dim=4
    #   - gta_distilled_model: keyboard_dim=2
    #   - templerun_distilled_model: keyboard_dim=7 (keyboard only, no mouse)
    MODEL_VARIANT = "base_distilled_model"
    
    # Variant-specific settings
    VARIANT_CONFIG = {
        "base_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-Base-Distilled-Diffusers",
            "keyboard_dim":
            4,
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/universal/0000.png",
        },
        "gta_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-GTA-Distilled-Diffusers",
            "keyboard_dim":
            2,
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/gta_drive/0000.png",
        },
        "templerun_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-TempleRun-Distilled-Diffusers",
            "keyboard_dim":
            7,
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/temple_run/0000.png",
        },
    }
    
    OUTPUT_PATH = "video_samples_matrixgame2"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        config = VARIANT_CONFIG[MODEL_VARIANT]
    
        generator = VideoGenerator.from_pretrained(
            config["model_path"],
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        num_frames = 597
        actions = create_action_presets(num_frames, keyboard_dim=config["keyboard_dim"])
        grid_sizes = torch.tensor([150, 44, 80])
    
        generator.generate_video(
            prompt="",
            image_path=config["image_url"],
            mouse_cond=actions["mouse"].unsqueeze(0),
            keyboard_cond=actions["keyboard"].unsqueeze(0),
            grid_sizes=grid_sizes,
            num_frames=num_frames,
            height=352,
            width=640,
            num_inference_steps=50,
            output_path=OUTPUT_PATH,
            save_video=True,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_matrixgame2_streaming.py"

    ```py
    from fastvideo.entrypoints.streaming_generator import StreamingVideoGenerator
    from fastvideo.models.dits.matrixgame2.utils import get_current_action_async, expand_action_to_frames
    
    import torch
    import asyncio
    
    # Available variants: "base_distilled_model", "gta_distilled_model", "templerun_distilled_model"
    # Each variant has different keyboard_dim:
    #   - base_distilled_model: keyboard_dim=4
    #   - gta_distilled_model: keyboard_dim=2
    #   - templerun_distilled_model: keyboard_dim=7 (keyboard only, no mouse)
    MODEL_VARIANT = "base_distilled_model"
    
    # Variant-specific settings
    VARIANT_CONFIG = {
        "base_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-Base-Distilled-Diffusers",
            "keyboard_dim":
            4,
            "mode":
            "universal",
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/universal/0000.png",
        },
        "gta_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-GTA-Distilled-Diffusers",
            "keyboard_dim":
            2,
            "mode":
            "gta_drive",
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/gta_drive/0000.png",
        },
        "templerun_distilled_model": {
            "model_path":
            "FastVideo/Matrix-Game-2.0-TempleRun-Distilled-Diffusers",
            "keyboard_dim":
            7,
            "mode":
            "templerun",
            "image_url":
            "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-2/demo_images/temple_run/0000.png",
        },
    }
    
    OUTPUT_PATH = "video_samples_matrixgame2"
    
    
    async def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        config = VARIANT_CONFIG[MODEL_VARIANT]
    
        generator = StreamingVideoGenerator.from_pretrained(
            config["model_path"],
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        max_blocks = 50
        num_frames = 597
        actions = {"keyboard": torch.zeros((num_frames, config["keyboard_dim"])), "mouse": torch.zeros((num_frames, 2))}
        grid_sizes = torch.tensor([150, 44, 80])
        mode = config["mode"]
    
        generator.reset(
            prompt="",
            image_path=config["image_url"],
            mouse_cond=actions["mouse"].unsqueeze(0),
            keyboard_cond=actions["keyboard"].unsqueeze(0),
            grid_sizes=grid_sizes,
            num_frames=num_frames,
            height=352,
            width=640,
            num_inference_steps=50,
            output_path=OUTPUT_PATH,
            save_video=True,
        )
        print("Initialization complete.")
    
        for block_id in range(max_blocks):
            print(f"\n=== Block {block_id + 1}/{max_blocks} ===")
    
            action = await get_current_action_async(mode)
            keyboard_cond, mouse_cond = expand_action_to_frames(action, 12)
            await generator.step_async(keyboard_cond, mouse_cond)
    
            if (await asyncio.to_thread(input, "\nContinue? (y/n): ")).lower() == 'n':
                break
    
        # Save final video
        generator.finalize()
        generator.shutdown()
    
    
    if __name__ == "__main__":
        asyncio.run(main())
    
    ```

??? note "basic_matrixgame3.py"

    ```py
    from fastvideo import VideoGenerator
    
    MODEL_PATH = "FastVideo/Matrix-Game-3.0-Base-Distilled-Diffusers"
    IMAGE_URL = "https://raw.githubusercontent.com/SkyworkAI/Matrix-Game/main/Matrix-Game-3/demo_images/001/image.png"
    PROMPT = "A colorful, animated cityscape with a gas station and various buildings."
    OUTPUT_PATH = "video_samples_matrixgame3"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            MODEL_PATH,
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        generator.generate_video(
            prompt=PROMPT,
            image_path=IMAGE_URL,
            height=720,
            width=1280,
            num_frames=57,
            num_inference_steps=3,
            guidance_scale=1.0,
            seed=42,
            output_path=OUTPUT_PATH,
            save_video=True,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_minimax_h3_fl2va.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate synchronized video/audio from a first frame with MiniMax H3."""
    
    from __future__ import annotations
    
    import argparse
    from pathlib import Path
    
    from PIL import Image
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        SamplingConfig,
    )
    from fastvideo.pipelines.basic.minimax_h3.packing import resolve_canvas_size
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--model-path", default="MiniMaxAI/MiniMax-H3")
        # Rank-reduced AdaLN checkpoint (-39% params, -23 GiB VRAM): pass
        #   --model-path noctuashap/MiniMax-H3-pruned-r16
        # (or a local dir produced by
        #   scripts/checkpoint_conversion/convert_minimax_h3_adaln_rank.py).
        # adaln_rank is read from the checkpoint config; no other flags needed.
        # Rank-reduced checkpoints are inference-only: training needs the
        # full-rank release.
        parser.add_argument("--image", required=True, help="First-frame image path.")
        parser.add_argument("--last-image", help="Optional last-frame image path.")
        parser.add_argument("--output", default="outputs/minimax_h3_fl2va")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--num-frames", type=int, default=192, help="192 frames is exactly 8 seconds at 24 fps.")
        parser.add_argument("--steps", type=int, default=50)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=4)
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        first_image = Image.open(args.image).convert("RGB")
        last_image = Image.open(args.last_image).convert("RGB") if args.last_image else None
        height, width = resolve_canvas_size(*first_image.size)
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
    
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=False,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                    ),
                ),
            ))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt="",
                    inputs=InputConfig(pil_image=first_image, last_image=last_image),
                    sampling=SamplingConfig(
                        height=height,
                        width=width,
                        num_frames=args.num_frames,
                        fps=24,
                        num_inference_steps=args.steps,
                        guidance_scale=1.0,
                        batch_cfg=False,
                        seed=args.seed,
                    ),
                    output=OutputConfig(
                        output_path=str(output_dir / "minimax_h3_fl2va.mp4"),
                        save_video=True,
                        return_frames=False,
                    ),
                ))
            print(f"Output written to: {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_minimax_h3_ref2va.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate synchronized video/audio from ordered references with MiniMax H3."""
    
    from __future__ import annotations
    
    import argparse
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    from fastvideo.pipelines.basic.minimax_h3 import MiniMaxH3Reference
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--model-path", default="MiniMaxAI/MiniMax-H3")
        # Rank-reduced AdaLN checkpoint (-39% params, -23 GiB VRAM): pass
        #   --model-path noctuashap/MiniMax-H3-pruned-r16
        # (or a local dir produced by
        #   scripts/checkpoint_conversion/convert_minimax_h3_adaln_rank.py).
        # adaln_rank is read from the checkpoint config; no other flags needed.
        # Rank-reduced checkpoints are inference-only: training needs the
        # full-rank release.
        parser.add_argument("--reference-video", required=True)
        parser.add_argument("--reference-audio", help="Optional additional audio reference.")
        parser.add_argument("--output", default="outputs/minimax_h3_ref2va")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--height", type=int, default=768)
        parser.add_argument("--width", type=int, default=1344)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--steps", type=int, default=50)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=4)
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        references = [MiniMaxH3Reference(source=args.reference_video, media_type="video")]
        if args.reference_audio:
            references.append(MiniMaxH3Reference(source=args.reference_audio, media_type="audio"))
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
    
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=False,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                    ),
                ),
                pipeline=PipelineSelection(
                    workload_type="i2v",
                    components=ComponentConfig(override_pipeline_cls_name="MiniMaxH3Ref2VAModularPipeline"),
                ),
            ))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt="",
                    inputs=InputConfig(references=references),
                    sampling=SamplingConfig(
                        height=args.height,
                        width=args.width,
                        num_frames=args.num_frames,
                        fps=24,
                        num_inference_steps=args.steps,
                        guidance_scale=1.0,
                        batch_cfg=False,
                        seed=args.seed,
                    ),
                    output=OutputConfig(
                        output_path=str(output_dir / "minimax_h3_ref2va.mp4"),
                        save_video=True,
                        return_frames=False,
                    ),
                ))
            print(f"Output written to: {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_minimax_h3_t2v.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate video and audio from text with MiniMax H3."""
    
    from __future__ import annotations
    
    import argparse
    import os
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        CompileConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--model-path", default="MiniMaxAI/MiniMax-H3")
        # Rank-reduced AdaLN checkpoint (-39% params, -23 GiB VRAM): pass
        #   --model-path noctuashap/MiniMax-H3-pruned-r16
        # (or a local dir produced by
        #   scripts/checkpoint_conversion/convert_minimax_h3_adaln_rank.py).
        # adaln_rank is read from the checkpoint config; no other flags needed.
        # Rank-reduced checkpoints are inference-only: training needs the
        # full-rank release.
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--output", default="outputs/minimax_h3_t2v")
        parser.add_argument("--height", type=int, default=768)
        parser.add_argument("--width", type=int, default=1344)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--steps", type=int, default=50)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=4)
        parser.add_argument(
            "--execution-backend",
            choices=("mp", "uni", "ray"),
            default=None,
            help="mp for one node; ray for a Ray cluster (two DGX Sparks). "
            "Default: ray when RAY_ADDRESS is set, otherwise mp",
        )
        parser.add_argument("--torch-compile", action="store_true", help="torch.compile the DiT transformer path")
        parser.add_argument("--compile-vae",
                            action=argparse.BooleanOptionalAction,
                            default=True,
                            help="compile the video VAE decoder independently of the DiT (on by default; "
                            "the Spark lazy-load path needs this registered before first materialize)")
        parser.add_argument("--compile-mode",
                            default=None,
                            help='torch.compile mode, e.g. "reduce-overhead" for CUDA graphs')
        parser.add_argument("--inference-torch-compile",
                            action="store_true",
                            help="regional fullgraph torch.compile of each DiT block after load (the #1718 "
                            "training-port semantics: no kwargs; fullgraph + emulate_precision_casts injected). "
                            "First generation pays the inductor JIT (~1-2 min); use --repeats >= 2 and time "
                            "the last repeat. FASTVIDEO_INFERENCE_TORCH_COMPILE=1 is equivalent")
        parser.add_argument("--lazy-module-load",
                            action=argparse.BooleanOptionalAction,
                            default=None,
                            help="load each heavy component on first use and free it after the last stage that "
                            "needs it, so peak memory is the largest overlapping set instead of the sum of every "
                            "component. Omit for auto (on for unified-memory devices such as GB10; off on discrete "
                            "GPUs). Costs a reload per generation; pass --no-lazy-module-load to keep every "
                            "component resident")
        parser.add_argument("--repeats",
                            type=int,
                            default=1,
                            help="generate N times; with --torch-compile the first run pays "
                            "compilation, so steady-state is the last repeat")
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
    
        # Boot-time run configuration folded into FastVideoArgs (the same
        # experimental-dict route basic_fasth3.py uses for the VSA knobs).
        experimental: dict[str, object] = {}
        if args.inference_torch_compile:
            experimental["inference_torch_compile"] = True
    
        execution_backend = args.execution_backend or ("ray" if os.environ.get("RAY_ADDRESS") else "mp")
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                pipeline=PipelineSelection(experimental=experimental),
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    execution_backend=execution_backend,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=OffloadConfig(
                        dit=False,
                        dit_layerwise=False,
                        text_encoder=True,
                        vae=True,
                        pin_cpu_memory=False,
                        lazy_module_load=args.lazy_module_load,
                    ),
                    compile=CompileConfig(
                        enabled=args.torch_compile,
                        mode=args.compile_mode,
                        vae_enabled=args.compile_vae,
                    ),
                ),
            ))
        try:
            request = GenerationRequest(
                prompt=args.prompt,
                negative_prompt="",
                sampling=SamplingConfig(
                    height=args.height,
                    width=args.width,
                    num_frames=args.num_frames,
                    fps=24,
                    num_inference_steps=args.steps,
                    guidance_scale=1.0,
                    batch_cfg=False,
                    seed=args.seed,
                ),
                output=OutputConfig(
                    output_path=str(output_dir / "minimax_h3_t2v.mp4"),
                    save_video=True,
                    return_frames=False,
                ),
            )
            result = generator.generate(request)
            print(f"Output written to: {result.video_path}")
            if result.generation_time is not None:
                # machine-readable: benchmark harnesses parse this line to separate
                # generation from model-load time (last occurrence = steady state)
                print(f"Generation time: {result.generation_time:.2f}s")
            # Worker-lifetime allocator high-water mark: torch never resets it
            # between generations, so it includes model load and every prior run.
            if result.peak_memory_mb is not None:
                print(f"Peak memory: {result.peak_memory_mb:.1f} MB")
            for _ in range(args.repeats - 1):
                result = generator.generate(request)
                if result.generation_time is not None:
                    print(f"Generation time: {result.generation_time:.2f}s")
                # Same worker-lifetime peak as above; it does not reset per repeat.
                if result.peak_memory_mb is not None:
                    print(f"Peak memory: {result.peak_memory_mb:.1f} MB")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_mmaudio.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """MMAudio large-44k-v2 video-to-audio example."""
    
    import argparse
    import os
    
    from fastvideo import VideoGenerator
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--video-path", required=True)
        parser.add_argument("--output-path", default="outputs_audio/mmaudio.wav")
        parser.add_argument("--duration-seconds", type=float, default=8.0)
        parser.add_argument("--prompt", default="")
        parser.add_argument("--negative-prompt", default="music")
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        generator = VideoGenerator.from_pretrained(
            os.environ.get(
                "MMAUDIO_MODEL_PATH",
                "converted_weights/mmaudio/large_44k_v2",
            ),
            workload_type="v2a",
            num_gpus=1,
        )
        result = generator.generate_video(
            prompt=args.prompt,
            negative_prompt=args.negative_prompt,
            video_path=args.video_path,
            audio_end_in_s=args.duration_seconds,
            output_path=args.output_path,
            save_video=True,
            return_frames=False,
        )
        print(result["video_path"])
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_mps.py"

    ```py
    from fastvideo import VideoGenerator, PipelineConfig
    from fastvideo.api.sampling_param import SamplingParam
    
    
    def main():
        config = PipelineConfig.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
        config.text_encoder_precisions = ["fp16"]
    
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
            pipeline_config=config,
            use_fsdp_inference=False,  # Disable FSDP for MPS
            dit_cpu_offload=True,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
            disable_autocast=False,
            num_gpus=1,
        )
    
        # Create sampling parameters with reduced number of frames
        sampling_param = SamplingParam.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
        sampling_param.num_frames = 25  # Reduce from default 81 to 25 frames bc we have to use the SDPA attn backend for mps
        sampling_param.height = 256
        sampling_param.width = 256
    
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
    
        video = generator.generate_video(prompt, sampling_param=sampling_param)
    
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
    
        video2 = generator.generate_video(prompt2, sampling_param=sampling_param)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_open_h3_regenerate_2k.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Regenerate a 768P MiniMax-H3 draft video at 2560x1440 with Open-H3-Regenerate-2K.
    
    The draft is VAE-encoded (the first 121 frames at 24 fps, 1344x768), its latent is upscaled, and three refine steps
    of the H3 transformer with the released LoRA run at 2560x1440. The output video is silent. See
    docs/inference/open_h3_regenerate_2k.md.
    
        python examples/inference/basic/basic_open_h3_regenerate_2k.py --video draft.mp4 --prompt "..." --output out/
    """
    
    from __future__ import annotations
    
    import argparse
    import time
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        PipelineSelection,
        QuantizationConfig,
        SamplingConfig,
    )
    
    DEFAULT_MODEL = "Efficient-Large-Model/Open-H3-Regenerate-2K"
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--model-path", default=DEFAULT_MODEL, help="release repo id or a local copy of it")
        parser.add_argument("--video", default=None, help="768P draft video (URL-free local path)")
        parser.add_argument("--prompt", required=True, help="text the refine steps are conditioned on")
        parser.add_argument("--output", type=Path, default=Path("outputs/open_h3_regenerate_2k"))
        parser.add_argument("--steps", type=int, choices=(2, 3), default=3, help="refine steps (3 is the released setting)")
        parser.add_argument("--seed", type=int, default=1766580932)
        parser.add_argument("--attention-backend", default="TORCH_SDPA")
        parser.add_argument("--draft-size", choices=("768p", "576p"), default="768p",
                            help="size the draft is encoded at; 576p for drafts from other video models")
        parser.add_argument("--vae-decoder", default=None,
                            help="NVFP4 decoder-nvfp4.safetensors that replaces the VAE decoder at load "
                            "(Blackwell only, see docs/inference/open_h3_regenerate_2k.md)")
        parser.add_argument("--refine-transformer", default=None,
                            help="refine on another MiniMax-H3 DiT (e.g. a FastH3 export) instead of the release's own")
        parser.add_argument("--refine-transformer-quant", default=None,
                            help="NVFP4 layer profile for a packed refine DiT, e.g. h3_dit_vsa")
        parser.add_argument("--draft-latent", default=None,
                            help="native draft latent .pt to refine instead of encoding --video")
        parser.add_argument("--runs", type=int, default=1, help="repeat the request to measure warm timings")
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        if (args.video is None) == (args.draft_latent is None):
            raise SystemExit("pass exactly one of --video or --draft-latent")
        args.output.mkdir(parents=True, exist_ok=True)
        experimental = {
            "attention_backend": args.attention_backend,
            "draft_size": args.draft_size,
        }
        if args.vae_decoder:
            experimental["h3_vae_nvfp4_decoder"] = args.vae_decoder
        experimental["refine_transformer_dir"] = args.refine_transformer
        experimental["draft_latent_path"] = args.draft_latent
        engine = EngineConfig(num_gpus=1,
                              offload=OffloadConfig(dit=False, dit_layerwise=False, text_encoder=True, vae=False))
        if args.refine_transformer_quant:
            engine.quantization = QuantizationConfig(transformer_quant="NVFP4", layer_profile=args.refine_transformer_quant)
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                engine=engine,
                pipeline=PipelineSelection(
                    components=ComponentConfig(),
                    experimental=experimental,
                ),
            ))
        try:
            for run in range(args.runs):
                started = time.perf_counter()
                result = generator.generate(
                    GenerationRequest(
                        prompt=args.prompt,
                        inputs=InputConfig(video_path=args.video),
                        sampling=SamplingConfig(height=1440,
                                                width=2560,
                                                num_frames=124,
                                                fps=24,
                                                num_inference_steps=args.steps,
                                                guidance_scale=1.0,
                                                seed=args.seed),
                        output=OutputConfig(output_path=str(args.output / f"regen2k_{run}.mp4"),
                                            save_video=True,
                                            return_frames=False),
                    ))
                print(f"run {run}: {time.perf_counter() - started:.1f}s -> {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_pan2.py"

    ```py
    import json
    import os
    
    from fastvideo import VideoGenerator
    
    # PAN2 is prompted with a structured caption, serialized as one-line JSON: the style, lighting and camera, each
    # subject, the first frame, and timed events with their camera motion and actions. Its prompt rewriter
    # (`inference/pan-prompt-rewriter` in ifm-ai/PAN2) turns a plain description into one. This is the release's own
    # text-to-video example (`inference/prompts/examples.json`), a 10 s clip whose event times span the video.
    CAPTION = json.loads("""
    {
      "video_style": "Realistic sports cinematography in one uninterrupted continuous shot.",
      "lighting": "Direct morning sunlight from the pool's far side; bright surface reflections, natural skin color and blue-green underwater light with moving caustics.",
      "perspective_view": "Low side three-quarter view from an adjacent empty lane, tracking right alongside the swimmer. The waterproof camera descends through the surface after entry, follows underwater, then rises above water while maintaining the same side and direction.",
      "subjects_lifecycle": [
        {
          "subject_id": "<|Subject1|>",
          "display_name": "Racing swimmer",
          "subject_attribute": "Athletic man in his early 30s, clean-shaven, wearing a white silicone cap, dark racing goggles and navy knee-length racing jammers."
        }
      ],
      "init_frame_visual_description": "The swimmer crouches on a white starting block at the left of an outdoor competition pool, facing right along his lane. His fingers curl over the block's front edge, hips raised and feet staggered. The low camera sits just above the water in the neighboring lane, framing his entire starting posture and several meters of clear water ahead. Blue-and-white lane ropes converge toward the distant end wall. Sunlight defines his shoulders and the matte fabric of his jammers; small surface ripples break the reflection of the pale pool deck, with a dark floor guide visible beneath them.",
      "events": [
        {
          "event_index": 0,
          "time_range_sec": "0 to 2.2",
          "event_description": "He drives off the block, extends his arms beyond his head and enters fingertips first farther down the lane. His torso and pointed feet follow through the opening, leaving a brief upright splash behind him. He lengthens into a submerged glide as the camera follows right and descends through the rippling surface beside his entry trail.",
          "camera_motion": [
            {
              "time_range_sec": "0 to 0.3",
              "camera_motion": [
                "static"
              ]
            },
            {
              "time_range_sec": "0.3 to 1.5",
              "camera_motion": [
                "track_right"
              ]
            },
            {
              "time_range_sec": "1.5 to 2.2",
              "camera_motion": [
                "track_right",
                "dolly_down"
              ]
            }
          ],
          "contained_actions": [
            {
              "time_range_sec": "0.2 to 1.5",
              "action": "<|Subject1|> pushes from the block, dives forward with arms extended and enters the water hands first, followed by torso and feet."
            },
            {
              "time_range_sec": "1.5 to 2.2",
              "action": "<|Subject1|> glides underwater in a long streamlined shape, carrying forward momentum from the dive."
            }
          ]
        },
        {
          "event_index": 1,
          "time_range_sec": "2.2 to 5.8",
          "event_description": "Seen fully underwater, he adds two compact dolphin kicks, then angles toward the surface. One arm separates into the first pull as his legs switch to a fast flutter kick. His head breaks the surface and he establishes front crawl; from below, alternating forearms press water backward while small bubbles trail his hands and shoulders. The floor guide passes beneath him as the camera matches his forward speed.",
          "camera_motion": [
            {
              "time_range_sec": "2.2 to 5.8",
              "camera_motion": [
                "track_right"
              ]
            }
          ],
          "contained_actions": [
            {
              "time_range_sec": "2.2 to 3.5",
              "action": "<|Subject1|> performs two dolphin kicks during the glide and directs his streamlined body upward."
            },
            {
              "time_range_sec": "3.5 to 5.8",
              "action": "<|Subject1|> breaks out into front crawl, alternating underwater pulls and changing to a continuous flutter kick."
            }
          ]
        },
        {
          "event_index": 2,
          "time_range_sec": "5.8 to 10",
          "event_description": "The camera rises through the waterline, revealing his recovering arms above the surface while keeping his advancing body at useful scale. He powers onward with alternating reaches and pulls, each hand entry producing a short splash in a regular rhythm. He rolls his head toward the camera for one breath, returns his face to the water and drives into the next strokes without slowing.",
          "camera_motion": [
            {
              "time_range_sec": "5.8 to 6.6",
              "camera_motion": [
                "track_right",
                "dolly_up"
              ]
            },
            {
              "time_range_sec": "6.6 to 10",
              "camera_motion": [
                "track_right"
              ]
            }
          ],
          "contained_actions": [
            {
              "time_range_sec": "5.8 to 10",
              "action": "<|Subject1|> races forward in front crawl with alternating arm recoveries and rhythmic hand entries, takes one side breath and returns his face to the water while maintaining his kick."
            }
          ]
        }
      ],
      "quality": {
        "video_quality": "Resolved athletic form and transparent water, with brief motion blur on fast hands and splashes.",
        "text_logos_overlays": null,
        "artifacts": null
      }
    }
    """)
    PROMPT = json.dumps(CAPTION, ensure_ascii=False, separators=(",", ":"))
    NUM_FRAMES = 241  # 10 s at 24 fps, the caption's length.
    
    OUTPUT_PATH = "video_samples_pan2"
    MODEL_PATH = os.environ.get("PAN2_MODEL_PATH", "IFM/PAN2")
    
    IMAGE_PATH = None
    
    
    def main():
        # The 29B DiT runs in bf16; with more GPUs, num_gpus enables Ulysses sequence parallelism (the 32 attention
        # heads must be divisible by it).
        generator = VideoGenerator.from_pretrained(
            MODEL_PATH,
            num_gpus=int(os.environ.get("PAN2_NUM_GPUS", "1")),
            use_fsdp_inference=False,
            dit_cpu_offload=False,
            dit_layerwise_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        generator.generate_video(
            PROMPT,
            image_path=IMAGE_PATH,
            num_frames=NUM_FRAMES,
            output_path=OUTPUT_PATH,
            save_video=True,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_pika_h3_flex.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Generate synchronized video/audio with Pika H3 Flex.
    
    Five task shapes share one model release:
    
    ``t2va``  text only
    ``i2va``  first image
    ``l2va``  last image
    ``fl2va`` first and last images
    ``ref2va`` ordered image/video/audio references
    
    The six-forward ladder is part of the adapter contract; this script deliberately
    does not expose a step-count flag.  ``--lossless-accel`` turns on the existing
    training-free FastVideo switches (bit-identical kernels, reference memo,
    parallel VAE tiles) before the generator starts.  ``--nvfp4-decoder`` and
    ``--nvfp4-text-encoder`` opt into the existing Blackwell FP4 weight paths;
    ``--weights nvfp4-qad`` (or ``nvfp4-qad-fp4-attention``) selects FastVideo's NVFP4 QAD release;
    ``--nvfp4-dit h3_dit`` loads any packed NVFP4 DiT export (e.g.
    FastVideo/Pika-H3-Flex-NVFP4-QAD).  They change weights, not the six-forward sampler.  Kernel/VSA work is separate.
    
    ``--nvfp4-attention`` turns on FlashAttention-4 NVFP4 attention (Q/K in NVFP4, P/V in BF16; Blackwell and FA4 only)
    with the named exact Q/K preconditioning, which must match the ``qk_transform`` the checkpoint was QAD-trained with
    (``smooth_k+hadamard`` for Pika-H3-Flex-NVFP4-QAD).  ``--nvfp4-attention-bf16-blocks 45,49`` keeps those
    ``transformer_blocks`` on BF16 attention, as in training.  ``none`` quantizes Q/K without preconditioning.
    Without ``--nvfp4-attention`` attention stays BF16.
    
    ``--resolution`` (480p/768p), ``--aspect`` (one of Pika's eleven buckets), and
    ``--duration`` (5-15 s) pick the bucket and the ``17n + 5`` frame count;
    ``--height``/``--width``/``--num-frames`` override them with explicit values.
    Launch with ``FASTVIDEO_ATTENTION_BACKEND=FLASH_ATTN FASTVIDEO_FA4=1`` on a
    FlashAttention-4 host (Hopper/Blackwell); without FA4 attention falls back to
    FA3/FA2 or, if neither is installed, to SDPA.
    
    ``--offload resident`` keeps every component on the GPU, which is how the
    GB200 timings in docs/inference/pika_h3_flex.md were measured; the default
    ``lazy`` mode loads components on demand for smaller devices and is slower.
    
    Examples:
        FASTVIDEO_ATTENTION_BACKEND=FLASH_ATTN FASTVIDEO_FA4=1 \
        python examples/inference/basic/basic_pika_h3_flex.py --task t2va --offload resident \
            --prompt "a paper boat drifting down a rainy street"
        python examples/inference/basic/basic_pika_h3_flex.py --task t2va \
            --resolution 480p --aspect 9:16 --duration 10 --prompt "a lighthouse at dusk"
        python examples/inference/basic/basic_pika_h3_flex.py --task fl2va \
            --image first.png --last-image last.png --prompt "the flower opens"
        python examples/inference/basic/basic_pika_h3_flex.py --task ref2va \
            --reference image:person.png --reference video:dance.mp4 \
            --reference audio:voice.wav --prompt "the person dances to the music"
    """
    
    from __future__ import annotations
    
    import argparse
    import os
    from pathlib import Path
    from typing import Any
    
    from fastvideo import VideoGenerator, envs
    from fastvideo.api import (
        CompileConfig,
        ComponentConfig,
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        QuantizationConfig,
        SamplingConfig,
    )
    from fastvideo.attention.utils.nvfp4_qk_precondition import QK_TRANSFORMS, parse_block_indices
    from fastvideo.models.vision_utils import load_image
    from fastvideo.pipelines.basic.minimax_h3 import MiniMaxH3Reference
    from fastvideo.pipelines.basic.pika_h3_flex.buckets import (
        PIKA_ASPECTS,
        PIKA_FPS,
        PIKA_MAX_DURATION,
        PIKA_MIN_DURATION,
        canvas_for_aspect,
        resolve_frames,
    )
    
    # Training-free switches FastVideo already exposes. Workers inherit the
    # environment, so they must be set before VideoGenerator starts.
    LOSSLESS_ACCEL_ENV = {
        "FASTVIDEO_MINIMAX_H3_EXACT_KERNELS": "all",
        "FASTVIDEO_H3_REF2VA_MEMO_ENTRIES": "16",
        "FASTVIDEO_H3_VAE_TILE_PARALLEL": "1",
        "FASTVIDEO_ULYSSES_A2A": "auto",
    }
    
    TASKS = ("t2va", "i2va", "l2va", "fl2va", "ref2va")
    RESOLUTIONS = {"480p": "p480", "768p": "p768"}
    
    
    def _reference(value: str) -> MiniMaxH3Reference:
        try:
            media_type, source = value.split(":", 1)
        except ValueError as error:
            raise argparse.ArgumentTypeError("A reference must be image:PATH, video:PATH, or audio:PATH.") from error
        if media_type not in ("image", "video", "audio"):
            raise argparse.ArgumentTypeError(f"Unknown reference type {media_type!r}.")
        return MiniMaxH3Reference(source=source, media_type=media_type)
    
    
    WEIGHT_PRESETS = {
        "bf16": {
            "model_path": "Pika-Labs/Pika-H3-Flex"
        },
        "nvfp4-qad": {
            "model_path": "FastVideo/Pika-H3-Flex-NVFP4-QAD",
            "nvfp4_dit": "h3_dit"
        },
        "nvfp4-qad-fp4-attention": {
            "model_path": "FastVideo/Pika-H3-Flex-NVFP4-FP4Attn-QAD",
            "nvfp4_dit": "h3_dit",
            "nvfp4_attention": "smooth_k+hadamard",
            "nvfp4_attention_bf16_blocks": "45,49"
        },
    }
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--weights",
                            choices=tuple(WEIGHT_PRESETS),
                            default="bf16",
                            help="bf16: Pika's release; nvfp4-qad: FastVideo's NVFP4 QAD release; "
                            "nvfp4-qad-fp4-attention: NVFP4 QAD with FP4 attention (both need Blackwell)")
        parser.add_argument("--model-path", help="local model directory or Hub repo (overrides --weights)")
        parser.add_argument("--task", choices=TASKS, default="t2va")
        parser.add_argument("--prompt", required=True)
        parser.add_argument("--image", help="first frame (i2va/fl2va)")
        parser.add_argument("--last-image", help="last frame (l2va/fl2va)")
        parser.add_argument("--reference",
                            action="append",
                            type=_reference,
                            default=[],
                            help="ordered reference (repeatable; ref2va)")
        parser.add_argument("--resolution", choices=tuple(RESOLUTIONS), default="768p", help="Pika resolution tier")
        parser.add_argument("--aspect", choices=PIKA_ASPECTS, default="16:9", help="bucket aspect ratio (W:H)")
        parser.add_argument("--duration",
                            type=float,
                            default=5.0,
                            help=f"seconds ({PIKA_MIN_DURATION:g}-{PIKA_MAX_DURATION:g}); rounded up to the 17n+5 grid")
        parser.add_argument("--height", type=int, help="explicit canvas height (with --width; overrides the bucket)")
        parser.add_argument("--width", type=int, help="explicit canvas width (with --height; overrides the bucket)")
        parser.add_argument("--num-frames", type=int, help="explicit frame count (overrides --duration)")
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--num-gpus", type=int, default=1)
        parser.add_argument("--compile", action="store_true", help="torch.compile the DiT")
        parser.add_argument("--lossless-accel", action="store_true", help="enable bit-identical speed-ups")
        parser.add_argument("--offload",
                            choices=("lazy", "resident"),
                            default="lazy",
                            help="lazy: load components on demand and offload the encoders/VAE (fits smaller devices); "
                            "resident: keep everything on the GPU (fastest, about 105-130 GiB on GB200)")
        parser.add_argument("--low-vram", action="store_true", help="stream the DiT layerwise (lazy offload only)")
        parser.add_argument("--nvfp4-decoder",
                            help="Blackwell-only NVFP4 H3 decoder (quality-36L or fast-8L decoder-nvfp4.safetensors)")
        parser.add_argument("--nvfp4-text-encoder",
                            help="Blackwell-only serialized NVFP4 Qwen3-VL text_encoder directory")
        parser.add_argument("--nvfp4-dit",
                            choices=("h3_dit", "h3_dit_ffn"),
                            help="load a packed NVFP4 DiT export with this layer profile (h3_dit: attention + FFN linears)")
        parser.add_argument("--nvfp4-attention",
                            choices=tuple(QK_TRANSFORMS),
                            help="FA4 NVFP4 Q/K attention with this exact Q/K preconditioning (default: BF16 attention)")
        parser.add_argument("--nvfp4-attention-bf16-blocks",
                            help="comma-separated transformer_blocks indices that keep BF16 attention, e.g. 45,49")
        parser.add_argument("--output", default="outputs/pika_h3_flex")
        args = parser.parse_args()
        for name, value in WEIGHT_PRESETS[args.weights].items():
            if getattr(args, name) is None:
                setattr(args, name, value)
        if args.nvfp4_attention_bf16_blocks and not args.nvfp4_attention:
            parser.error("--nvfp4-attention-bf16-blocks needs --nvfp4-attention")
        try:
            parse_block_indices(args.nvfp4_attention_bf16_blocks)
        except ValueError as error:
            parser.error(f"--nvfp4-attention-bf16-blocks: {error}")
    
        if args.task in ("i2va", "fl2va") and not args.image:
            parser.error(f"--task {args.task} needs --image")
        if args.task in ("l2va", "fl2va") and not args.last_image:
            parser.error(f"--task {args.task} needs --last-image")
        if args.task == "ref2va" and not args.reference:
            parser.error("--task ref2va needs at least one --reference")
        if args.task != "ref2va" and args.reference:
            parser.error("--reference is only valid with --task ref2va")
        if (args.height is None) != (args.width is None):
            parser.error("--height and --width must be passed together")
        if args.low_vram and args.offload == "resident":
            parser.error("--low-vram streams the DiT and cannot be combined with --offload resident")
        return args
    
    
    def _offload(args: argparse.Namespace) -> OffloadConfig:
        if args.offload == "resident":
            return OffloadConfig(dit=False,
                                 dit_layerwise=False,
                                 text_encoder=False,
                                 vae=False,
                                 pin_cpu_memory=False,
                                 lazy_module_load=False)
        return OffloadConfig(
            dit=False,
            dit_layerwise=args.low_vram,
            text_encoder=True,
            vae=True,
            pin_cpu_memory=not args.low_vram,
            lazy_module_load=True,
        )
    
    
    def _canvas(args: argparse.Namespace) -> tuple[int, int]:
        if args.height is not None:
            return args.height, args.width
        return canvas_for_aspect(args.aspect, RESOLUTIONS[args.resolution])
    
    
    def _num_frames(args: argparse.Namespace) -> int:
        if args.num_frames is not None:
            return args.num_frames
        return resolve_frames(round(args.duration * PIKA_FPS))
    
    
    def _inputs(args: argparse.Namespace) -> InputConfig:
        if args.task == "ref2va":
            return InputConfig(references=args.reference)
        first = args.image if args.task in ("i2va", "fl2va") else None
        last = args.last_image if args.task in ("l2va", "fl2va") else None
        # The stage loads ``image_path`` itself but requires ``last_image`` as a PIL image.
        return InputConfig(image_path=first, last_image=load_image(last) if last else None)
    
    
    def _pipeline(args: argparse.Namespace) -> PipelineSelection:
        components = ComponentConfig()
        if args.task == "ref2va":
            components.override_pipeline_cls_name = "PikaH3FlexRef2VAModularPipeline"
        if args.nvfp4_decoder:
            components.h3_vae_nvfp4_decoder = args.nvfp4_decoder
        if args.nvfp4_text_encoder:
            components.text_encoder_weights = args.nvfp4_text_encoder
        return PipelineSelection(
            workload_type="t2v" if args.task == "t2va" else "i2v",
            components=components,
            vae_tiling=True,
        )
    
    
    def _apply_nvfp4_attention(args: argparse.Namespace) -> None:
        """Workers inherit the environment, so set it before VideoGenerator starts."""
        if not args.nvfp4_attention:
            return
        envs.FASTVIDEO_NVFP4_FA4.set(True)
        envs.FASTVIDEO_NVFP4_FA4_QK_TRANSFORM.set(args.nvfp4_attention)
        envs.FASTVIDEO_NVFP4_FA4_BF16_BLOCKS.set(args.nvfp4_attention_bf16_blocks or "")
        envs.setdefault_external("CUTE_DSL_ENABLE_TVM_FFI", "1")
    
    
    def main() -> None:
        args = parse_args()
        _apply_nvfp4_attention(args)
        if args.lossless_accel:
            for key, value in LOSSLESS_ACCEL_ENV.items():
                os.environ.setdefault(key, value)
    
        height, width = _canvas(args)
        num_frames = _num_frames(args)
        print(f"Pika H3 Flex {args.task}: {width}x{height}, {num_frames} frames ({num_frames / PIKA_FPS:.2f} s)")
        output_path = Path(args.output) / f"pika_h3_flex_{args.task}.mp4"
        output_path.parent.mkdir(parents=True, exist_ok=True)
        offload = _offload(args)
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                engine=EngineConfig(
                    num_gpus=args.num_gpus,
                    use_fsdp_inference=args.num_gpus > 1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=args.num_gpus),
                    offload=offload,
                    compile=CompileConfig(enabled=args.compile),
                    quantization=(QuantizationConfig(transformer_quant="NVFP4", layer_profile=args.nvfp4_dit)
                                  if args.nvfp4_dit else None),
                ),
                pipeline=_pipeline(args),
            ))
        try:
            result = generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt="",
                    inputs=_inputs(args),
                    sampling=SamplingConfig(
                        height=height,
                        width=width,
                        num_frames=num_frames,
                        fps=24,
                        num_inference_steps=6,
                        guidance_scale=1.0,
                        batch_cfg=False,
                        seed=args.seed,
                    ),
                    output=OutputConfig(
                        output_path=str(output_path),
                        save_video=True,
                        return_frames=False,
                    ),
                ))
            print(f"Output written to: {result.video_path}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_qwen_image21.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Qwen-Image-2.1 generation, editing, references and transparent PNG output."""
    
    import argparse
    
    from fastvideo import VideoGenerator
    from fastvideo.api import (
        EngineConfig,
        GenerationRequest,
        GeneratorConfig,
        InputConfig,
        OffloadConfig,
        OutputConfig,
        ParallelismConfig,
        PipelineSelection,
        SamplingConfig,
    )
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--model-path", default="Qwen/Qwen-Image-2.1")
        parser.add_argument("--revision")
        parser.add_argument("--prompt", default="A red ceramic teapot, isolated on a transparent background.")
        parser.add_argument("--reference", action="append", default=[], help="Ordered reference image; repeat up to ten times")
        parser.add_argument("--negative-prompt", default=None)
        parser.add_argument("--true-cfg-scale", type=float, default=1.0)
        parser.add_argument("--height", type=int, default=1024)
        parser.add_argument("--width", type=int, default=1024)
        parser.add_argument("--reference-resolution", type=int, default=1024)
        parser.add_argument("--steps", type=int, default=40)
        parser.add_argument("--seed", type=int, default=42)
        parser.add_argument("--use-kv-cache", action=argparse.BooleanOptionalAction, default=True)
        parser.add_argument("--output", default="outputs/qwen_image21/image.png")
        args = parser.parse_args()
        if len(args.reference) > 10:
            parser.error("At most ten ordered reference images are supported")
        workload = "i2i" if args.reference else "t2i"
        generator = VideoGenerator.from_config(
            GeneratorConfig(
                model_path=args.model_path,
                revision=args.revision,
                engine=EngineConfig(
                    num_gpus=1,
                    parallelism=ParallelismConfig(tp_size=1, sp_size=1),
                    offload=OffloadConfig(dit=True, dit_layerwise=True, text_encoder=True, vae=True,
                                          lazy_module_load=True),
                ),
                pipeline=PipelineSelection(
                    workload_type=workload,
                    experimental={
                        "reference_resolution": args.reference_resolution,
                        "use_kv_cache": args.use_kv_cache,
                    },
                ),
            ))
        try:
            generator.generate(
                GenerationRequest(
                    prompt=args.prompt,
                    negative_prompt=args.negative_prompt,
                    inputs=InputConfig(references=args.reference or None),
                    sampling=SamplingConfig(height=args.height, width=args.width, num_frames=1, fps=1,
                                            num_inference_steps=args.steps, guidance_scale=1.0,
                                            true_cfg_scale=args.true_cfg_scale, seed=args.seed),
                    output=OutputConfig(output_path=args.output, save_video=True, return_frames=False),
                ))
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_ray.py"

    ```py
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=2,
            use_fsdp_inference=True,
            dit_cpu_offload=False,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            distributed_executor_backend="ray",
            # image_encoder_cpu_offload=False,
        )
    
        # Generate videos with the same simple API, regardless of GPU count
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True)
    
        # Generate another video with a different prompt, without reloading the
        # model!
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        video2 = generator.generate_video(prompt2, output_path=OUTPUT_PATH, save_video=True)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_sd35_t2i.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    
    from __future__ import annotations
    
    import argparse
    import os
    import re
    from typing import List
    
    DEFAULT_PROMPTS = [
        "a photo of a cat",
        "a cinematic photo of a red panda wearing a tiny backpack, standing on a rainy neon-lit street at night, shallow depth of field, sharp focus, 35mm, bokeh",
    ]
    
    
    def _safe_filename(text: str, max_len: int = 100) -> str:
        """
        Make a stable, filesystem-friendly filename base.
        VideoGenerator uses prompt[:100].strip() internally, so we mirror that,
        but also remove path separators and other problematic characters.
        """
        s = text[:max_len].strip()
        s = s.replace(os.sep, "_")
        if os.altsep:
            s = s.replace(os.altsep, "_")
        s = re.sub(r"\s+", " ", s)
        s = re.sub(r"[^A-Za-z0-9 .,_-]", "_", s)
        s = s.strip(" .")
        return s or "prompt"
    
    
    def _remove_existing_outputs(out_dir: str, filename_base: str) -> None:
        """
        Ensure deterministic naming by deleting any existing outputs that would
        cause VideoGenerator to append suffixes like _1, _2, etc.
        """
        if not os.path.isdir(out_dir):
            return
    
        pattern = re.compile(rf"^{re.escape(filename_base)}(_\d+)?\.(mp4|png)$")
        for fn in os.listdir(out_dir):
            if pattern.match(fn):
                try:
                    os.remove(os.path.join(out_dir, fn))
                except FileNotFoundError:
                    pass
    
    
    def parse_args() -> argparse.Namespace:
        p = argparse.ArgumentParser(description="Run SD3.5 Medium text-to-image with FastVideo VideoGenerator.")
        p.add_argument("--model-path",
                       default="stabilityai/stable-diffusion-3.5-medium",
                       help="Path to local diffusers-format SD3.5 weights directory.")
        p.add_argument(
            "--out-dir",
            "--outdir",
            default="outputs/sd35/samples",
            help="Output directory for generated mp4 files.",
        )
        p.add_argument(
            "--prompt",
            action="append",
            default=None,
            help="Prompt text. Repeat --prompt multiple times to generate multiple samples.",
        )
        p.add_argument("--negative", default="lowres, blurry, jpeg artifacts, watermark, text", help="Negative prompt.")
        p.add_argument(
            "--backend",
            default=None,
            help="Set FASTVIDEO_ATTENTION_BACKEND (e.g. TORCH_SDPA). If omitted, respects the existing env var.",
        )
        p.add_argument("--seed", type=int, default=42, help="Base seed. Each prompt uses seed + prompt_idx.")
        p.add_argument("--height", type=int, default=768, help="Output height.")
        p.add_argument("--width", type=int, default=768, help="Output width.")
        p.add_argument("--steps", type=int, default=28, help="Number of inference steps.")
        p.add_argument("--guidance", type=float, default=6.0, help="Guidance scale.")
        p.add_argument("--num-gpus", type=int, default=1, help="Number of GPUs to use.")
        return p.parse_args()
    
    
    def main() -> None:
        args = parse_args()
        prompts: List[str] = args.prompt if args.prompt else DEFAULT_PROMPTS
    
        if args.backend:
            os.environ["FASTVIDEO_ATTENTION_BACKEND"] = args.backend
    
        from fastvideo import VideoGenerator
    
        os.makedirs(args.out_dir, exist_ok=True)
    
        init_kwargs = {
            "num_gpus": args.num_gpus,
            "workload_type": "t2i",
            "sp_size": 1,
            "tp_size": 1,
            "dit_cpu_offload": False,
            "dit_layerwise_offload": False,
            "text_encoder_cpu_offload": False,
            "vae_cpu_offload": False,
            "image_encoder_cpu_offload": False,
            "pin_cpu_memory": False,
            "use_fsdp_inference": False,
        }
    
        generator = VideoGenerator.from_pretrained(model_path=args.model_path, **init_kwargs)
        try:
            for i, prompt in enumerate(prompts):
                seed = args.seed + i
    
                filename_base = f"sd35_{i:02d}_seed{seed}_{_safe_filename(prompt, max_len=80)}"
                _remove_existing_outputs(args.out_dir, filename_base)
    
                output_path = os.path.join(args.out_dir, f"{filename_base}.png")
                print(f"[sd35] prompt_idx={i} seed={seed} output_path={output_path}")
    
                generation_kwargs = {
                    "output_path": output_path,
                    "height": args.height,
                    "width": args.width,
                    "num_frames": 1,
                    "fps": 1,
                    "num_inference_steps": args.steps,
                    "guidance_scale": args.guidance,
                    "seed": seed,
                    "negative_prompt": args.negative,
                    "save_video": True,
                }
    
                generator.generate_video(prompt, **generation_kwargs)
    
            print(f"[sd35] done. outputs written to: {args.out_dir}")
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_self_forcing_causal.py"

    ```py
    import os
    import time
    from fastvideo import VideoGenerator, SamplingParam
    
    OUTPUT_PATH = "video_samples_causal"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        model_name = "wlsaidhi/SFWan2.1-T2V-1.3B-Diffusers"
        generator = VideoGenerator.from_pretrained(
            model_name,
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            text_encoder_cpu_offload=False,
            dit_cpu_offload=False,
        )
    
        sampling_param = SamplingParam.from_pretrained(model_name)
    
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True, sampling_param=sampling_param)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_self_forcing_causal_wan2_2_i2v.py"

    ```py
    # NOTE: This is still a work in progress, and the checkpoints are not released yet.
    
    from fastvideo import VideoGenerator, SamplingParam
    import json
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_self_forcing_causal_wan2_2_14B_i2v"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "FastVideo/SFWan2.2-I2V-A14B-Preview-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            dit_precision="fp32",
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            dmd_denoising_steps=[1000, 850, 700, 550, 350, 275, 200, 125],
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        sampling_param = SamplingParam.from_pretrained("FastVideo/SFWan2.2-I2V-A14B-Preview-Diffusers")
        sampling_param.num_frames = 81
        sampling_param.width = 832
        sampling_param.height = 480
        sampling_param.seed = 1000
    
        with open("assets/prompts/mixkit_i2v.jsonl", "r") as f:
            prompt_image_pairs = json.load(f)
    
        for prompt_image_pair in prompt_image_pairs:
            prompt = prompt_image_pair["prompt"]
            image_path = prompt_image_pair["image_path"]
            _ = generator.generate_video(prompt,
                                         image_path=image_path,
                                         output_path=OUTPUT_PATH,
                                         save_video=True,
                                         sampling_param=sampling_param)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_self_forcing_causal_wan2_2_t2v.py"

    ```py
    # NOTE: This is still a work in progress, and the checkpoints are not released yet.
    
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_self_forcing_causal_wan2_2_14B_t2v"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "rand0nmr/SFWan2.2-T2V-A14B-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            dmd_denoising_steps=[1000, 850, 700, 550, 350, 275, 200, 125],
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            init_weights_from_safetensors=
            "/mnt/sharefs/users/hao.zhang/wei/SFwan2.2_distill_self_forcing_release_cfg2/checkpoint-246_weight_only/generator_inference_transformer/",
            init_weights_from_safetensors_2=
            "/mnt/sharefs/users/hao.zhang/wei/SFwan2.2_distill_self_forcing_release_cfg2/checkpoint-246_weight_only/generator_2_inference_transformer/",
            num_frame_per_block=7,
            # image_encoder_cpu_offload=False,
        )
    
        # sampling_param = SamplingParam.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
        # sampling_param.num_frames = 45
        # sampling_param.image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
        # Generate videos with the same simple API, regardless of GPU count
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        _ = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True, num_frames=81)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_stable_audio.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Stable Audio Open 1.0 — text-to-audio (baseline) example.
    
    User story (game-audio designer, prototyping):
        "I'm prototyping a level and I need 6 seconds of background
        ambience — gentle wind, distant thunder, a hint of birdsong. I
        don't want to dig through a sound library; I want to type what I
        hear in my head and get a wav back. If it's wrong I'll iterate
        on the prompt. This is the first stop."
    
    User story (musician sketching ideas):
        "I want to bounce a 30s lo-fi drum loop to use as a placeholder
        bed while I build the rest of the track. Type prompt, get audio,
        drop into the DAW. The actual production beat I'll record
        myself, but I need *something* to write the chords against."
    
    User story (researcher exploring the model):
        "First time touching Stable Audio Open — what does it sound
        like at default settings? This is the smallest amount of code
        that goes from prompt to mp4."
    
    How it works:
        Pure text-to-audio (T2A). The pipeline runs:
            T5 + NumberConditioner -> StableAudioDiT -> Oobleck VAE
        via the `dpmpp-3m-sde` k-diffusion sampler. All components are
        FastVideo-native — no diffusers / transformers model imports at
        runtime (see REVIEW item 30). Mirrors upstream
        `stable_audio_tools.inference.generation.generate_diffusion_cond`
        bit-for-bit (~0.2% abs_mean drift on 25 steps).
    
    Tunable knobs (the "creative dials"):
        audio_end_in_s
            1–6   — quick ideation (sub-10s wall clock at 100 steps)
            10–30 — full musical phrase / loop length (the README example
                    uses 30s)
            47.5  — model maximum (full sample_size = 2097152 / 44100 Hz)
        num_inference_steps
            25  — fast preview, occasional artifacts
            100 — preset default (matches the HF model card)
            250 — diminishing returns past here
        guidance_scale
            3   — looser, more variation per seed
            7   — preset default; matches README
            12+ — sharper but can sound "fried"
    
    Prerequisites:
      1. Accept the terms on https://huggingface.co/stabilityai/stable-audio-open-1.0
         and export your HF token in the shell:
             export HF_TOKEN=hf_...
      2. Install optional inference deps (one-time):
             uv pip install k_diffusion einops_exts alias_free_torch torchsde
    """
    from fastvideo import VideoGenerator
    
    PROMPT = "Lo-fi hip hop instrumental with vinyl crackle and gentle piano."
    
    
    def main() -> None:
        generator = VideoGenerator.from_pretrained(
            "FastVideo/stable-audio-open-1.0-Diffusers",
            num_gpus=1,
        )
        output_path = "outputs_audio/stable_audio_basic/output_stable_audio.wav"
        generator.generate_video(
            prompt=PROMPT,
            output_path=output_path,
            save_video=True,
            # 6-second clip; the model max is ~47.5s.
            audio_end_in_s=6.0,
            # The registered preset gives 100 steps + CFG=7.0 by default;
            # override num_inference_steps / guidance_scale here for QA.
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_stable_audio_a2a.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Stable Audio Open 1.0 — audio-to-audio variation example.
    
    User story (musician, late at night):
        "I generated this 12-second lo-fi loop earlier and I love the chord
        progression and overall vibe, but the snare hit at 0:08 sounds wrong
        and the rhythm feels stiff. I don't want to start over from scratch
        and lose what's working — I want the model to keep the harmony and
        mood but reroll the percussion + groove."
    
    User story (sound designer, on a deadline):
        "I have one good 'sword clang' SFX. The art director wants 8 sibling
        variations that all feel like the same sword from different angles —
        same metal, same weight, slightly different impact. I'd rather
        refine my one good take than text-prompt my way through 50 misses."
    
    Pass `init_audio=path/to/clip` (any wav/mp3/mp4/m4a/flac the standard
    deps decode) and the model will use it as a starting point for the
    text prompt instead of pure noise.
    
    Picking `init_audio_strength` (0.0 to 1.0):
    
        Higher = closer to the source clip. Lower = more transformation.
        (Same convention as the "Input Audio Strength" slider in
        Stability's commercial Stable Audio web UI, so values transfer
        directly.)
    
          | strength | what you get                                       |
          |----------|----------------------------------------------------|
          |   1.00   | Output ≈ reference. No transformation.             |
          |   0.85   | Texture micro-variation only.                      |
          |   0.70   | Light reroll, same instruments.                    |
          |   0.60   | Default. Instrument identity is replaceable        |
          |          | (cello can take over from piano on the same notes).|
          |   0.50   | Heavy — only melody / chord progression survives.  |
          |   0.30   | Reference acts as a loose mood prompt.             |
          |   0.00   | Plain T2A — reference ignored.                     |
    
        Rule of thumb by intent:
          * "Fix one part of this clip"            -> 0.75 .. 0.85
          * "Same notes, different instrument"     -> 0.55 .. 0.65
          * "Same chord progression, new content"  -> 0.40 .. 0.55
          * "Use this as a loose mood prompt"      -> 0.20 .. 0.35
    
        If the reference timbre is bleeding through more than you want,
        lower it; if the structure is gone, raise it.
    
    Prerequisites: same as `basic_stable_audio.py`.
    """
    from fastvideo import VideoGenerator
    
    PROMPT = "Change the piano to a cello playing the same notes"
    # Path to any audio-bearing file (wav, mp3, mp4, m4a, flac, ...).
    # Set to `None` to skip A2A and run plain T2A.
    INIT_AUDIO_PATH: str | None = None
    # Reference fidelity in [0, 1] -- higher = closer to source.
    INIT_AUDIO_STRENGTH = 0.6
    
    
    def main() -> None:
        generator = VideoGenerator.from_pretrained(
            "FastVideo/stable-audio-open-1.0-Diffusers",
            num_gpus=1,
        )
        generator.generate_video(
            prompt=PROMPT,
            output_path="outputs_audio/stable_audio_a2a/output_a2a.wav",
            save_video=True,
            audio_end_in_s=6.0,
            init_audio=INIT_AUDIO_PATH,
            init_audio_strength=INIT_AUDIO_STRENGTH,
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_stable_audio_inpaint.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Stable Audio Open 1.0 — inpainting / outpainting (loop extension) example.
    
    User story (loop extension — the killer app):
        "I have a 6-second drum loop my client likes. They want it as
        background bed for a 30-second ad. I need it to loop seamlessly,
        but a hard cut every 6s sounds bad. Let me extend it to 30s,
        keeping the first 6s exactly as-is and letting the model continue
        the groove for the remaining 24s."
    
    User story (audio repair):
        "There's a microphone bump at 0:14 in this 30-second field
        recording — really obvious in headphones. Mask out 0:13 to 0:15
        and let the model regenerate plausible ambience that blends in.
        Everything else stays exactly as I recorded it."
    
    User story (transition smoothing):
        "I have two 10-second clips I want to crossfade. Mask out a 1s
        overlap region in the middle and let the model invent a coherent
        transition between the two."
    
    How it works (RePaint-style blending):
        Stable Audio Open 1.0 wasn't trained as an inpainting model
        (`model_type=diffusion_cond`, not `diffusion_cond_inpaint`), so we
        can't use the upstream's mask-conditioned approach directly. We
        use the RePaint trick instead, which works on any v-prediction
        diffusion model:
    
          1. Encode the reference clip into latent space.
          2. At every denoising step `i`, replace the kept region of the
             in-flight latent (where mask == 1) with the reference
             re-noised to the next timestep's sigma. Only the unkept
             region (mask == 0) is freely denoised.
          3. After the loop, the kept region is exactly the reference;
             the unkept region is freshly generated content.
    
        This is approximate compared to a properly trained inpainting
        checkpoint — the seam between kept/unkept can have slight EQ
        discontinuity — but it works on the existing public model.
    
    Tunable: the mask is a 1-D tensor in {0, 1} at the model's sample
    rate. Conventions:
        1.0 = keep this sample from the reference
        0.0 = regenerate this sample
    
    Prerequisites: same as `basic_stable_audio.py`.
    """
    import os
    
    from fastvideo import VideoGenerator
    
    PROMPT = "Steady lo-fi hip hop drum loop with vinyl crackle."
    # Required: path to the reference audio file (wav, mp3, mp4, m4a, flac,
    # ...) you want to extend or repair. The pipeline raises if a mask is
    # passed without a reference, so this must be a real path.
    REFERENCE_AUDIO_PATH = "path/to/your/loop.wav"
    KEEP_SECONDS = 6.0  # first KEEP_SECONDS preserved exactly
    TOTAL_SECONDS = 12.0  # extend the loop to this duration
    
    
    def main() -> None:
        if not os.path.isfile(REFERENCE_AUDIO_PATH):
            raise FileNotFoundError(f"REFERENCE_AUDIO_PATH={REFERENCE_AUDIO_PATH!r} does not exist. "
                                    "Edit this script to point at a real audio file (wav/mp3/mp4/"
                                    "m4a/flac) before running.")
        generator = VideoGenerator.from_pretrained(
            "FastVideo/stable-audio-open-1.0-Diffusers",
            num_gpus=1,
        )
        generator.generate_video(
            prompt=PROMPT,
            output_path="outputs_audio/stable_audio_inpaint/output_inpaint.wav",
            save_video=True,
            audio_end_in_s=TOTAL_SECONDS,
            inpaint_audio=REFERENCE_AUDIO_PATH,
            # Tuple form: keep first KEEP_SECONDS, regenerate the rest.
            inpaint_mask=(KEEP_SECONDS, TOTAL_SECONDS),
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_stable_audio_small.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Stable Audio Open Small — fast / lightweight T2A example.
    
    User story (interactive UI builder):
        "I'm building a sound-design UI where the user types a prompt and
        we want sub-2-second feedback so the experience feels like
        autocomplete, not a render queue. The full Stable Audio Open 1.0
        takes ~8s on a single GPU; the small variant takes a fraction of
        that — quality is lower but completely usable for real-time
        iteration."
    
    User story (overnight batch jobs):
        "I'm generating 10,000 short SFX variants for a procedural game.
        Wall-clock matters more than per-clip polish — give me the small
        model so I can fit the run in one night instead of a week."
    
    How it works:
        The small variant is a separate Stability AI checkpoint
        (`stabilityai/stable-audio-open-small`) that ships the same Oobleck
        VAE as the 1.0 base model but a smaller / faster DiT (`embed_dim=1024`,
        `depth=16`, `qk_norm="ln"`) and only one duration conditioner
        (`seconds_total`, no `seconds_start`). FastVideo loads from the
        converted Diffusers-format repo `FastVideo/stable-audio-open-small-Diffusers`
        via the standard component loader; per-variant arch fields come
        from `transformer/config.json` and `conditioner/config.json`.
    
    Prerequisites: same as `basic_stable_audio.py`. The converted repo is
    public so no gated-access flow is required.
    """
    from fastvideo import VideoGenerator
    
    PROMPT = "Lo-fi hip hop instrumental with vinyl crackle and gentle piano."
    
    
    def main() -> None:
        generator = VideoGenerator.from_pretrained(
            "FastVideo/stable-audio-open-small-Diffusers",
            num_gpus=1,
        )
        output_path = "outputs_audio/stable_audio_small/output_stable_audio_small.wav"
        generator.generate_video(
            prompt=PROMPT,
            output_path=output_path,
            save_video=True,
            # Small variant trains on a ~11.9s window — keep `audio_end_in_s`
            # at or below that.
            audio_end_in_s=6.0,
        )
        generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan2_2.py"

    ```py
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_wan2_2_14B_t2v"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=2,
            use_fsdp_inference=False,  # set to True if GPU is out of memory 
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        # sampling_param = SamplingParam.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
        # sampling_param.num_frames = 45
        # sampling_param.image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
        # Generate videos with the same simple API, regardless of GPU count
        prompt = ("A curious raccoon peers through a vibrant field of yellow sunflowers, its eyes "
                  "wide with interest. The playful yet serene atmosphere is complemented by soft "
                  "natural light filtering through the petals. Mid-shot, warm and cheerful tones.")
        _ = generator.generate_video(prompt,
                                     output_path=OUTPUT_PATH,
                                     save_video=True,
                                     height=720,
                                     width=1280,
                                     num_frames=81)
        # video = generator.generate_video(prompt, sampling_param=sampling_param, output_path="wan_t2v_videos/")
    
        # Generate another video with a different prompt, without reloading the
        # model!
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        _ = generator.generate_video(prompt2,
                                     output_path=OUTPUT_PATH,
                                     save_video=True,
                                     height=720,
                                     width=1280,
                                     num_frames=81)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan2_2_Fun.py"

    ```py
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_wan2_1_Fun"
    OUTPUT_NAME = "wan2.1_test"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "IRMChen/Wan2.1-Fun-1.3B-Control-Diffusers",
            # "alibaba-pai/Wan2.2-Fun-A14B-Control",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        prompt = "一位年轻女性穿着一件粉色的连衣裙，裙子上有白色的装饰和粉色的纽扣。她的头发是紫色的，头上戴着一个红色的大蝴蝶结，显得非常可爱和精致。她还戴着一个红色的领结，整体造型充满了少女感和活力。她的表情温柔，双手轻轻交叉放在身前，姿态优雅。背景是简单的灰色，没有任何多余的装饰，使得人物更加突出。她的妆容清淡自然，突显了她的清新气质。整体画面给人一种甜美、梦幻的感觉，仿佛置身于童话世界中。"
        negative_prompt = "色调艳丽，过曝，静态，细节模糊不清，字幕，风格，作品，画作，画面，静止，整体发灰，最差质量，低质量，JPEG压缩残留，丑陋的，残缺的，多余的手指，画得不好的手部，画得不好的脸部，畸形的，毁容的，形态畸形的肢体，手指融合，静止不动的画面，杂乱的背景，三条腿，背景人很多，倒着走"
        # prompt                  = "A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical."
        # negative_prompt         = "Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code."
        image_path = "https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/wan_fun/asset_Wan2_2/v1.0/8.png"
        control_video_path = "https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/wan_fun/asset_Wan2_2/v1.0/pose.mp4"
    
        video = generator.generate_video(prompt,
                                         negative_prompt=negative_prompt,
                                         image_path=image_path,
                                         video_path=control_video_path,
                                         output_path=OUTPUT_PATH,
                                         output_video_name=OUTPUT_NAME,
                                         save_video=True)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan2_2_i2v.py"

    ```py
    from fastvideo import VideoGenerator
    
    # from fastvideo.api.sampling_param import SamplingParam
    
    OUTPUT_PATH = "video_samples_wan2_2_14B_i2v"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.2-I2V-A14B-Diffusers",
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,  # DiT need to be offloaded for MoE
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            # Set pin_cpu_memory to false if CPU RAM is limited and there're no frequent CPU-GPU transfer
            pin_cpu_memory=True,
            # image_encoder_cpu_offload=False,
        )
    
        prompt = "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
        image_path = "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/wan_i2v_input.JPG"
    
        video = generator.generate_video(prompt,
                                         image_path=image_path,
                                         output_path=OUTPUT_PATH,
                                         save_video=True,
                                         height=832,
                                         width=480,
                                         num_frames=81)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan2_2_ti2v.py"

    ```py
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_wan2_2_5B_ti2v"
    
    
    def main():
        # FastVideo will automatically use the optimal default arguments for the
        # model.
        # If a local path is provided, FastVideo will make a best effort
        # attempt to identify the optimal arguments.
        model_name = "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
        generator = VideoGenerator.from_pretrained(
            model_name,
            # FastVideo will automatically handle distributed setup
            num_gpus=1,
            use_fsdp_inference=False,  # set to True if GPU is out of memory
            dit_cpu_offload=True,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,  # set to false if low CPU RAM or hit obscure "CUDA error: Invalid argument"
            # image_encoder_cpu_offload=False,
        )
    
        # I2V is triggered just by passing in an image_path argument
        prompt = "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
        image_path = "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/wan_i2v_input.JPG"
        video = generator.generate_video(prompt, output_path=OUTPUT_PATH, save_video=True, image_path=image_path)
    
        # Generate another video with a different prompt, without reloading the
        # model!
    
        # T2V mode
        prompt2 = ("A majestic lion strides across the golden savanna, its powerful frame "
                   "glistening under the warm afternoon sun. The tall grass ripples gently in "
                   "the breeze, enhancing the lion's commanding presence. The tone is vibrant, "
                   "embodying the raw energy of the wild. Low angle, steady tracking shot, "
                   "cinematic.")
        video2 = generator.generate_video(prompt2, output_path=OUTPUT_PATH, save_video=True)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan_animate.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Wan2.2-Animate-14B: animate a character image with someone else's performance.
    
    The reference image fixes who the character is; a preprocessed skeleton video
    drives the body and a preprocessed face-crop video drives the expression. The
    driving inputs are the artifacts the official preprocessing pipeline emits
    (https://github.com/Wan-Video/Wan2.2, ``wan/modules/animate/preprocess``):
    ``src_pose.mp4``, ``src_face.mp4``, and the aligned reference ``src_ref.png``
    (replace mode adds ``src_bg.mp4`` + ``src_mask.mp4`` and typically the
    relighting LoRA -- see scripts/checkpoint_conversion/wan_animate_relight_lora.py).
    
    CFG is off by default (guidance 1.0): the prompt is non-core for this model.
    """
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_wan_animate"
    
    # Outputs of the official preprocessing run on your reference image + driving video.
    REF_IMAGE_PATH = "preprocessed/src_ref.png"
    POSE_VIDEO_PATH = "preprocessed/src_pose.mp4"
    FACE_VIDEO_PATH = "preprocessed/src_face.mp4"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "Wan-AI/Wan2.2-Animate-14B-Diffusers",
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=True,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        generator.generate_video(
            "视频中的人在做动作",  # the official default prompt; non-core for this model
            image_path=REF_IMAGE_PATH,
            pose_video_path=POSE_VIDEO_PATH,
            face_video_path=FACE_VIDEO_PATH,
            output_path=OUTPUT_PATH,
            save_video=True,
            height=720,
            width=1280,
            num_frames=77,
            fps=30,
            guidance_scale=1.0,
            num_inference_steps=20,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "basic_wan_s2v.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Wan2.2-S2V-14B: animate a reference image in sync with a speech track.
    
    The audio drives the motion -- lip sync, head movement, and gesture rhythm all
    come from the waveform, while the reference image fixes who the subject is and
    the prompt sets the scene and camera.
    """
    from fastvideo import VideoGenerator
    
    OUTPUT_PATH = "video_samples_wan_s2v"
    
    
    def main():
        generator = VideoGenerator.from_pretrained(
            "FastVideo/Wan2.2-S2V-14B-Diffusers",
            num_gpus=1,
            use_fsdp_inference=False,
            dit_cpu_offload=True,
            vae_cpu_offload=False,
            text_encoder_cpu_offload=True,
            pin_cpu_memory=True,
        )
    
        # num_frames follows FastVideo's 4k+1 contract. 81 frames is one clip; a
        # longer count (e.g. 165 = 81 + 84) chains clips, each continuing from the
        # last 73 frames of the previous one, until the request is covered. Audio
        # past the end of the video is dropped; video past the end of the audio
        # plays over silence.
        prompt = ("A woman in a recording studio singing into a condenser microphone, "
                  "warm key light from the left, shallow depth of field, medium close-up, "
                  "subtle head movement in time with the music.")
    
        generator.generate_video(
            prompt,
            image_path="https://raw.githubusercontent.com/Wan-Video/Wan2.2/main/examples/i2v_input.JPG",
            audio_path="https://raw.githubusercontent.com/Wan-Video/Wan2.2/main/examples/talk.wav",
            output_path=OUTPUT_PATH,
            save_video=True,
            height=480,
            width=832,
            num_frames=81,
            fps=16,
            guidance_scale=5.0,
            num_inference_steps=40,
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "benchmark_fasth3_spark_nvfp4.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Time a resident FastH3 eight-forward Spark recipe with the release prompts.
    
    One process loads the model, runs one excluded ceramics warmup, then times
    each prompt at least twice. Every call writes a video. This script does not alter
    the V2 schedule, VSA sparsity, or video resolution.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import statistics
    import time
    from copy import deepcopy
    from pathlib import Path
    
    from fastvideo import VideoGenerator
    from fastvideo.api.parser import load_raw_config, parse_config
    from fastvideo.api.schema import RunConfig
    
    PROMPT_IDS = ("latency-ceramics-005", "latency-harbor-005")
    
    
    def _stage_metrics(result: object) -> dict[str, dict]:
        logging_info = getattr(result, "logging_info", None)
        stages = getattr(logging_info, "stages", None)
        if isinstance(logging_info, dict):
            stages = logging_info.get("stages", stages)
        if not isinstance(stages, dict):
            return {}
        return {name: metrics for name, metrics in stages.items() if isinstance(metrics, dict)}
    
    
    def _stage_seconds(metrics: dict[str, dict]) -> dict[str, float]:
        return {name: float(stage["execution_time"]) for name, stage in metrics.items()
                if stage.get("execution_time") is not None}
    
    
    def _peak_mb(metrics: dict[str, dict], key: str) -> float | None:
        values = [float(stage[key]) for stage in metrics.values() if stage.get(key) is not None]
        return max(values) if values else None
    
    
    def _stage_total(stages: dict[str, float], fragment: str, exclude: str | None = None) -> float | None:
        matches = [
            seconds for name, seconds in stages.items()
            if fragment in name.lower() and (exclude is None or exclude not in name.lower())
        ]
        return sum(matches) if matches else None
    
    
    def _request(base: RunConfig, prompt: str, frames: int, width: int, height: int,
                 output: Path):
        request = deepcopy(base.request)
        request.prompt = prompt
        request.inputs.prompt_path = None
        request.sampling.num_frames = frames
        request.sampling.width = width
        request.sampling.height = height
        request.output.output_path = str(output)
        request.output.save_video = True
        request.output.return_frames = False
        return request
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--config", type=Path, required=True)
        parser.add_argument("--prompts", type=Path, required=True)
        parser.add_argument("--output-dir", type=Path, required=True)
        parser.add_argument("--model-path", type=Path)
        parser.add_argument("--frames", type=int, default=124)
        parser.add_argument("--width", type=int, default=832)
        parser.add_argument("--height", type=int, default=480)
        parser.add_argument("--repeats", type=int, default=2)
        args = parser.parse_args()
    
        if args.frames not in (124, 243):
            parser.error("use 124 frames for roughly five seconds or 243 for roughly ten seconds")
        if args.repeats < 2:
            parser.error("the release protocol requires at least two timed calls")
    
        config = parse_config(RunConfig, load_raw_config(args.config))
        if args.model_path:
            config.generator.model_path = str(args.model_path)
        if config.request.sampling.num_inference_steps != 9:
            parser.error("the V2 contract requires nine sigma points for eight DiT forwards")
        if config.generator.engine.offload.lazy_module_load is not False:
            parser.error("the resident recipe requires lazy_module_load: false")
        contract = Path(config.generator.model_path) / "fastvideo_inference.json"
        if not contract.is_file():
            parser.error(f"missing trained V2 schedule: {contract}")
        inference = json.loads(contract.read_text())
        if inference.get("num_inference_steps") != 9 or inference.get("transformer_forwards") != 8:
            parser.error("the checkpoint is not the trained V2 eight-forward schedule")
    
        prompts = json.loads(args.prompts.read_text())
        if any(prompt_id not in prompts for prompt_id in PROMPT_IDS):
            parser.error(f"prompt JSON must contain {', '.join(PROMPT_IDS)}")
        args.output_dir.mkdir(parents=True, exist_ok=True)
    
        generator = VideoGenerator.from_config(config.generator)
        try:
            for prompt_index, prompt_id in enumerate(PROMPT_IDS):
                times = []
                first_index = 0 if prompt_index == 0 else 1
                for index in range(first_index, args.repeats + 1):
                    warmup = index == 0
                    label = "warmup" if warmup else f"run-{index:02d}"
                    requested_path = args.output_dir / f"{prompt_id}-{args.width}x{args.height}-{args.frames}-{label}.mp4"
                    request = _request(config, prompts[prompt_id], args.frames, args.width, args.height,
                                       requested_path)
                    started = time.perf_counter()
                    result = generator.generate(request)
                    wall = time.perf_counter() - started
                    output = Path(result.video_path) if result.video_path else requested_path
                    if not output.is_file():
                        raise RuntimeError(f"generation returned without an MP4: {output}")
                    metrics = _stage_metrics(result)
                    stages = _stage_seconds(metrics)
                    row = {
                        "prompt_id": prompt_id,
                        "warmup": warmup,
                        "frames": args.frames,
                        "width": args.width,
                        "height": args.height,
                        "e2e_seconds": round(wall, 3),
                        "denoise_seconds": _stage_total(stages, "denois"),
                        "decode_seconds": _stage_total(stages, "decod", exclude="postdecode"),
                        "postprocess_seconds": _stage_total(stages, "postdecode"),
                        "peak_memory_mb": _peak_mb(metrics, "peak_allocated_mb"),
                        "peak_reserved_mb": _peak_mb(metrics, "peak_reserved_mb"),
                        "result_peak_memory_mb": result.peak_memory_mb,
                        "stages": stages,
                        "mp4": str(output),
                    }
                    print(json.dumps(row, sort_keys=True), flush=True)
                    if not warmup:
                        times.append(wall)
                print(json.dumps({"prompt_id": prompt_id, "timed_runs": len(times),
                                  "median_e2e_seconds": round(statistics.median(times), 3)},
                                 sort_keys=True), flush=True)
        finally:
            generator.shutdown()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "lingbotworld_examples/00/intrinsics.npy"

??? note "lingbotworld_examples/00/poses.npy"

??? note "lingbotworld_examples/01/intrinsics.npy"

??? note "lingbotworld_examples/01/poses.npy"

??? note "lingbotworld_examples/02/intrinsics.npy"

??? note "lingbotworld_examples/02/poses.npy"

??? note "minimax_h3_external_launcher.yaml"

    ```yaml
    generator:
      model_path: MiniMaxAI/MiniMax-H3
      engine:
        num_gpus: 4
        execution_backend: external_launcher
        use_fsdp_inference: true
        parallelism:
          tp_size: 1
          sp_size: 4
          dist_timeout: 600  # seconds; applies to device and Gloo control groups
        offload:
          dit: false
          dit_layerwise: false
          text_encoder: true
          image_encoder: true
          vae: true
          pin_cpu_memory: false
    request:
      prompt: A cinematic tracking shot of ocean waves at sunset
      negative_prompt: ""
      sampling:
        height: 768
        width: 1344
        num_frames: 124
        fps: 24
        num_inference_steps: 50
        guidance_scale: 1.0
        batch_cfg: false
        seed: 0
      output:
        output_path: outputs/minimax_h3_external_launcher.mp4
        save_video: true
        return_frames: false
    
    ```

??? note "mlx_fasth3.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """End-to-end MiniMax-H3 (FastH3) generation with the Apple Silicon MLX runtime.
    
    Accepts a text prompt and produces an MP4 with H.264 video at 24 fps and
    stereo AAC audio at 32 kHz. One heavyweight model phase is resident at a time.
    
        python examples/inference/basic/mlx_fasth3.py \
          --model-root ~/models/FastH3-Preview-v0.2 \
          --mlx-checkpoint ~/models/FastH3-MLX/int8 \
          --prompt '(S1) A red panda says <d>[English] Fast H3 is amazing.</d>' \
          --height 480 --width 832 --num-frames 124 --seed 2026 \
          --output-path ~/fasth3_outputs/int8.mp4
    
    Conditioning uses the streamed Qwen3-VL text encoder on first use and caches
    the resulting embeddings under --prompt-cache-dir for instant reuse.
    
    ``--fast`` is temporal fast mode. It keeps full-duration audio while
    denoising fewer video frames, then uses MLX RIFE 4.25 to reconstruct the
    requested frame count. A 1280x720 request runs on H3's 1280x736 grid and is
    center-cropped after decode.
    
    ``--fast-spatial`` is spatial fast mode, ``--fast``'s spatial twin. It
    denoises and decodes on the smallest 32px-aligned canvas covering
    height/width divided by ``--fast-spatial-scale``, then resamples the decoded
    frames up to the requested size in pixel space. The two modes compose.
    This trades fine detail for speed: the output carries the reduced canvas's
    detail budget and reads softer than a native-resolution render, so it stays
    off by default.
    
    This entrypoint currently supports text-to-video-with-audio only. It does not
    yet wire FL2VA or two-pass refinement. The four-step preview stays the default.
    FastH3 8-Step V2 uses ``mlx_fasth3_8step.py``; reference-conditioned Ref2VA
    (OmniRef) uses ``mlx_fasth3_omniref.py``.
    
    VSA is off by default; existing dense MLX checkpoints remain supported.
    H3 uses fused MLX RMSNorm, which can change BF16 rounding compared with the
    older explicit normalization path. Convert with ``--include-vsa`` and pass
    ``--vsa`` to enable the sparse path. Attention activations stay BF16; INT6/INT8/INT4 apply only to
    linear weights, including the optional gate projection.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    from pathlib import Path
    
    
    def _dense_layers(value: str) -> tuple[int, ...]:
        layers = tuple(int(part.strip()) for part in value.split(",") if part.strip())
        if any(layer < 0 for layer in layers):
            raise argparse.ArgumentTypeError("dense layer indices must be non-negative")
        return layers
    
    
    def build_parser() -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(description=__doc__,
                                         formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--model-root", type=Path, default=Path.home() / "models/FastH3-Preview-v0.2",
                            help="H3 snapshot root (vae/, audio_vae/, text_encoder/, tokenizer/)")
        parser.add_argument("--mlx-checkpoint", type=Path, required=True,
                            help="pre-quantized MLX DiT directory (int8/int6/int4 mlx_h3_dit format)")
        parser.add_argument(
            "--prompt",
            required=True,
            help="H3 text prompt; use (S1) and <d>[Language] words</d> for explicit dialogue",
        )
        parser.add_argument("--output-path", type=Path, required=True)
        parser.add_argument("--height", type=int, default=480)
        parser.add_argument("--width", type=int, default=832)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--seed", type=int, default=0)
        parser.add_argument("--steps", type=int, default=4, help="denoise steps (trained ladder = 4)")
        parser.add_argument(
            "--fast",
            action=argparse.BooleanOptionalAction,
            default=False,
            help="denoise fewer video frames, then use MLX RIFE to restore the target frame count; audio stays full length",
        )
        parser.add_argument("--fast-factor", type=int, default=2,
                            help="temporal reduction target for --fast (default: 2)")
        parser.add_argument("--fast-sharpen", type=float, default=0.6,
                            help="unsharp strength after RIFE interpolation (0 disables)")
        parser.add_argument(
            "--fast-spatial",
            action=argparse.BooleanOptionalAction,
            default=False,
            help="denoise and decode at height/width // fast-spatial-scale on H3's 32px grid, "
            "then resample the decoded frames up to the requested size; composes with --fast. "
            "Trades fine detail for speed",
        )
        parser.add_argument("--fast-spatial-scale", type=int, default=2,
                            help="spatial reduction factor for --fast-spatial (default: 2)")
        parser.add_argument("--fast-spatial-upsample-mode",
                            choices=("lanczos", "cubic", "bilinear", "nearest"),
                            default="lanczos",
                            help="pixel interpolation kernel for the post-decode upsample")
        parser.add_argument("--fast-spatial-sharpen", type=float, default=0.4,
                            help="unsharp strength after the upsample (0 disables)")
        parser.add_argument("--rife-weights-dir", type=Path, default=None,
                            help="optional local mlx-community/RIFE-4.25 snapshot")
        parser.add_argument("--vae-dtype", choices=("fp32", "fp16", "bf16"), default="fp32")
        parser.add_argument("--video-decode-backend", choices=("h3-vae", "taeh3"), default="h3-vae",
                            help="full H3 VAE or approximate TAEH3 preview decoder; audio is unchanged")
        parser.add_argument("--taeh3-checkpoint", type=Path, default=None,
                            help="local TAEH3 safetensors; otherwise download hash-verified upstream weights")
        parser.add_argument("--taeh3-chunk-size", type=int, default=5,
                            help="latent frames per TAEH3 chunk; causal memory persists across chunks")
        parser.add_argument("--prompt-cache-dir", type=Path, default=None,
                            help="directory for reusable prompt embedding caches")
        parser.add_argument(
            "--tiled-video-decode",
            action=argparse.BooleanOptionalAction,
            default=True,
            help="decode with the reference 256px overlapping VAE tiles (disable only for diagnostics)",
        )
        parser.add_argument(
            "--vsa",
            action=argparse.BooleanOptionalAction,
            default=False,
            help=(
                "enable MiniMax H3 VSA; requires a VSA-capable MLX checkpoint "
                "from --include-vsa"
            ),
        )
        parser.add_argument(
            "--vsa-sparsity",
            type=float,
            default=0.9,
            help="VSA sparsity in [0, 1); 0.9 is the trained FastH3 policy",
        )
        parser.add_argument(
            "--vsa-tile-size",
            type=int,
            default=64,
            choices=(64, 256),
            help="VSA tile size in tokens",
        )
        parser.add_argument(
            "--vsa-prefix-mode",
            choices=("exempt", "compete"),
            default="exempt",
            help=(
                "prefix-key policy: always keep (exempt) or FLOP-matched top-k "
                "(compete)"
            ),
        )
        parser.add_argument(
            "--vsa-dense-first-n-steps",
            type=int,
            default=0,
            help="run the first N denoise steps dense",
        )
        parser.add_argument(
            "--vsa-dense-layers",
            type=_dense_layers,
            default=(),
            help="comma-separated layer indices forced dense",
        )
        parser.add_argument(
            "--vsa-impl",
            choices=("auto", "reference", "simd"),
            default="auto",
            help=(
                "sparse attention implementation; auto uses the SIMD Metal kernel for "
                "128-token tiles and chunked gather+SDPA otherwise (simd is opt-in for tile 64)"
            ),
        )
        parser.add_argument("--vae-tile-height", type=int, default=256,
                            help="overlapping video-VAE tile height in pixels")
        parser.add_argument("--vae-tile-width", type=int, default=256,
                            help="overlapping video-VAE tile width in pixels")
        parser.add_argument("--inter-step-cooldown-s", type=float, default=0.0,
                            help="optional pause between denoise steps")
        return parser
    
    
    def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
        return build_parser().parse_args(argv)
    
    
    def run(args: argparse.Namespace) -> None:
        from fastvideo.mlx_runtime.minimax_h3_pipeline import MiniMaxH3MLXPipeline
    
        pipeline = MiniMaxH3MLXPipeline(
            model_root=args.model_root,
            mlx_dit_checkpoint=args.mlx_checkpoint,
            vae_dtype=args.vae_dtype,
            video_decode_backend=args.video_decode_backend,
            taeh3_checkpoint=args.taeh3_checkpoint,
            taeh3_chunk_size=args.taeh3_chunk_size,
            prompt_cache_dir=args.prompt_cache_dir,
        )
        try:
            result = pipeline.generate(
                args.prompt,
                output_path=args.output_path,
                height=args.height,
                width=args.width,
                num_frames=args.num_frames,
                seed=args.seed,
                num_steps=args.steps,
                tiled_video_decode=args.tiled_video_decode,
                vae_tile_height=args.vae_tile_height,
                vae_tile_width=args.vae_tile_width,
                inter_step_cooldown_s=args.inter_step_cooldown_s,
                fast=args.fast,
                fast_factor=args.fast_factor,
                fast_sharpen=args.fast_sharpen,
                rife_weights_dir=args.rife_weights_dir,
                fast_spatial=args.fast_spatial,
                fast_spatial_scale=args.fast_spatial_scale,
                fast_spatial_upsample_mode=args.fast_spatial_upsample_mode,
                fast_spatial_sharpen=args.fast_spatial_sharpen,
                vsa=args.vsa,
                vsa_sparsity=args.vsa_sparsity,
                vsa_tile_size=args.vsa_tile_size,
                vsa_prefix_mode=args.vsa_prefix_mode,
                vsa_dense_first_n_steps=args.vsa_dense_first_n_steps,
                vsa_dense_layers=args.vsa_dense_layers,
                vsa_impl=args.vsa_impl,
            )
        finally:
            pipeline.close()
        print(json.dumps({
            "video_path": result.video_path,
            "timings_s": {k: round(v, 2) for k, v in result.timings.items()},
            "peak_memory_gib": {k: round(v, 2) for k, v in result.peak_memory_gib.items()},
            "vsa": result.vsa,
            "video_decode_backend": result.video_decode_backend,
            "audio_samples": int(result.waveform.shape[-1]),
        }, indent=2))
    
    
    def main() -> None:
        run(parse_args())
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_fasth3_8step.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Eight-forward FastH3 8-Step V2 generation on Apple Silicon.
    
    ``FastVideo/FastVideo-FastH3-8-Step-V2`` trains eight DMD forwards at video
    shift 10 and audio shift 3, VSA sparsity 0.8, and 64-token tiles. Point
    ``--model-root`` at a snapshot that contains that checkpoint's
    ``fastvideo_inference.json`` plus the shared VAE, audio VAE, text encoder, and
    tokenizer. Point ``--mlx-checkpoint`` at an MLX DiT converted from this
    checkpoint (the AdaLN cache must be the contract ladder, not the four-step
    uniform grid).
    
    ``--steps`` accepts 8 transformer forwards or 9 sigma-grid points. Either
    value runs the trained rungs. The four-step preview entrypoint is unchanged.
    """
    
    from __future__ import annotations
    
    from collections.abc import Sequence
    
    try:
        from . import mlx_fasth3
    except ImportError:
        import mlx_fasth3  # type: ignore[no-redef]
    
    FORWARDS = 8
    GRID_POINTS = FORWARDS + 1
    
    
    def parse_args(argv: Sequence[str] | None = None):
        parser = mlx_fasth3.build_parser()
        parser.set_defaults(steps=FORWARDS, vsa=True, vsa_sparsity=0.8, vsa_tile_size=64)
        args = parser.parse_args(argv)
        if args.steps not in (FORWARDS, GRID_POINTS):
            parser.error(f"--steps must be {FORWARDS} or {GRID_POINTS} for FastH3 8-Step V2")
        return args
    
    
    def main() -> None:
        mlx_fasth3.run(parse_args())
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_fasth3_omniref.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Reference-conditioned FastH3 OmniRef (Ref2VA) generation on Apple Silicon MLX.
    
    A FastH3 OmniRef PDD export carries only what distillation changed:
    ``transformer_ref/``, the two scheduler configs and ``fastvideo_inference.json``.
    The text encoder, tokenizer, processor and both VAEs are base MiniMax-H3's, so
    this script composes the two into one directory of symlinks - the same shape the
    CUDA example builds - and then runs the MLX runtime over it.
    
    There is no FP4 on Apple Silicon, so the DiT converts to INT8 (or INT6/INT4),
    the same formats the text-to-video-audio MLX path uses. The DiT has to be in
    the packed MLX layout first:
    
        python scripts/checkpoint_conversion/convert_minimax_h3_mlx.py \\
          --model-root <composed>/transformer_ref --out ~/models/FastH3-OmniRef-MLX \\
          --formats int8 --include-vsa
    
        python examples/inference/basic/mlx_fasth3_omniref.py \\
          --export ./FastVideo-FastH3-Omni-8-Step-V1 --composed-dir ./FastH3-OmniRef-composed \\
          --base-model-path ./MiniMax-H3 --mlx-checkpoint ~/models/FastH3-OmniRef-MLX/int8 \\
          --image reference.png --audio voice.wav \\
          --prompt "a person on a sofa, lit by a warm lamp, speaking to camera" \\
          --output-path ~/fasth3_outputs/omniref.mp4
    
    References are ordered: pass them in the order the model should read them, with
    ``--image`` / ``--video`` / ``--audio`` (for example ``--video dance.mp4
    --image outfit.png --audio voice.wav``). At least one image or video reference
    is required; audio references only accompany them.
    
    Add ``--compose-only`` to build the composed directory (the conversion above
    needs it) and stop, with no checkpoint, prompt or reference.
    
    The PDD ladder comes from the export's contract, so ``--steps`` is optional:
    without it the trained fused-block count runs.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    from pathlib import Path
    from typing import Any
    
    CONTRACT = "fastvideo_inference.json"
    MANIFESTS = ("modular_model_index.json", "model_index.json")
    EXPORT_COMPONENTS = ("transformer_ref", "scheduler", "audio_scheduler")
    BASE_COMPONENTS = ("text_encoder", "tokenizer", "processor", "vae", "audio_vae")
    
    
    class _AppendReference(argparse.Action):
        """Collect --image/--video/--audio into one list that keeps command-line order."""
    
        def __call__(self, parser, namespace, value, option_string=None):
            references = list(getattr(namespace, self.dest, None) or [])
            references.append((self.const, value))
            setattr(namespace, self.dest, references)
    
    
    def build_parser() -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--export", type=Path,
                            help="FastH3 OmniRef PDD export directory; composes it with --base-model-path")
        parser.add_argument("--base-model-path", type=Path,
                            help="base MiniMax-H3 snapshot (vae/, audio_vae/, text_encoder/, tokenizer/)")
        parser.add_argument("--composed-dir", type=Path, default=Path("outputs/fasth3_omniref_mlx_model"),
                            help="where the composed directory of symlinks is written")
        parser.add_argument("--model-root", type=Path,
                            help="an already-composed directory; skips composing")
        parser.add_argument("--compose-only", action="store_true",
                            help="compose --export with --base-model-path into --composed-dir and exit")
        parser.add_argument("--mlx-checkpoint", type=Path,
                            help="packed MLX checkpoint converted from the composed transformer_ref/")
        for flag in ("image", "video", "audio"):
            parser.add_argument(f"--{flag}", dest="references", action=_AppendReference, const=flag, metavar="PATH",
                                help=f"an ordered {flag} reference (repeatable)")
        parser.add_argument("--prompt")
        parser.add_argument("--output-path", type=Path, default=Path("outputs/mlx_fasth3_omniref.mp4"))
        parser.add_argument("--height", type=int, default=480)
        parser.add_argument("--width", type=int, default=832)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--seed", type=int, default=2026)
        parser.add_argument("--steps", type=int, default=0,
                            help="transformer forwards; 0 uses the export contract's trained count")
        parser.add_argument("--prompt-cache-dir", type=Path)
        parser.add_argument("--metal-wired-limit-gib", type=float,
                            help="keep this much unified memory wired so macOS does not page the DiT out mid-denoise")
        parser.add_argument("--mlx-cache-limit-gib", type=float,
                            help="bound MLX's freed-buffer cache; unbounded by default")
        parser.add_argument("--quant-gemm", choices=("auto", "dequant", "qmm"), default=None,
                            help="INT8/INT6/INT4 linear path: auto (measured default), dequant (dequantize + dense "
                            "GEMM for wide inputs), qmm (mx.quantized_matmul). Unset defers to "
                            "FASTVIDEO_MLX_QUANT_GEMM. Ignored by a bf16 checkpoint.")
        parser.add_argument("--reference-max-pixels", default=None,
                            help="opt-in cap on each image/video reference canvas (down only): a pixel count, or "
                            "'match' for the clip's own area. Faster, but references lose detail versus the trained "
                            "canvas.")
        parser.add_argument("--vae-dtype", default="fp32")
        parser.add_argument("--vae-decoder", type=Path,
                            help="standalone video decoder (FastH3 decoder[-nvfp4].safetensors or a LightVAE decoder) "
                            "replacing the base vae/ decoder")
        parser.add_argument("--vae-encoder", type=Path,
                            help="standalone video encoder (LightVAE) replacing the base vae/ encoder; with both flags "
                            "vae/ only needs config.json")
        parser.add_argument("--vae-decoder-quantization", choices=("nvfp4", "mxfp8", "int8", "int4"),
                            help="quantize the decoder block linears of a dense decoder file as it loads")
        parser.add_argument("--vsa", action=argparse.BooleanOptionalAction, default=None,
                            help="VSA sparse attention (needs a checkpoint converted with --include-vsa). "
                            "On by default when the contract is a VSA contract; --no-vsa runs dense.")
        parser.add_argument("--vsa-sparsity", type=float, default=None,
                            help="generated-video sparsity; default is the contract's trained value")
        parser.add_argument("--vsa-tile-size", type=int, default=None,
                            help="VSA tile: 64, 128 or 256. Must equal the contract's trained tile; "
                            "default is the contract's.")
        parser.add_argument("--vsa-ref-keep-rate", type=float, default=None,
                            help="fraction of each reference video's tiles a query keeps (p2_multi_region); "
                            "default is the contract's trained value")
        parser.add_argument("--vsa-impl", choices=("auto", "reference", "simd", "sdpa", "nax"), default="auto",
                            help="sparse attention backend; auto uses the SIMD Metal kernel for 128-token tiles and "
                            "gather+SDPA otherwise, reference forces gather+SDPA; sdpa shares K/V with a tile mask "
                            "and nax uses M5 TensorOps over selected blocks (both opt-in, incompatible with --reuse-prefix-kv)")
        parser.add_argument("--reuse-prefix-kv", action="store_true",
                            help="opt-in, lossy: record the text/reference rows' per-block K/V on step 1 and run later "
                            "steps on the target audio/video rows only (faster, slightly different output)")
        parser.add_argument("--prefix-kv-refresh-every", type=int, default=0,
                            help="re-record the prefix K/V with a full forward every N steps (0 never)")
        parser.add_argument("--prefix-kv-cache-max-gib", type=float, default=4.0,
                            help="refuse prefix K/V reuse when the estimated cache exceeds this many GiB")
        parser.add_argument("--prefix-kv-storage", choices=("bf16", "fp16", "int8"), default="bf16",
                            help="prefix K/V cache storage dtype (int8 halves the cache)")
        parser.add_argument("--inter-step-cooldown-s", type=float, default=0.0)
        return parser
    
    
    def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
        parser = build_parser()
        args = parser.parse_args(argv)
        if args.compose_only:
            if args.export is None or args.base_model_path is None:
                parser.error("--compose-only needs --export and --base-model-path")
            return args
        if args.mlx_checkpoint is None or args.prompt is None:
            parser.error("--mlx-checkpoint and --prompt are required unless --compose-only is set")
        if not args.references:
            parser.error("pass at least one ordered reference with --image, --video, or --audio")
        if not any(kind != "audio" for kind, _ in args.references):
            parser.error("Ref2VA needs at least one image or video reference")
        if args.model_root is None and (args.export is None or args.base_model_path is None):
            parser.error("give --model-root, or --export together with --base-model-path")
        if args.vsa_impl in ("sdpa", "nax") and args.reuse_prefix_kv:
            parser.error(f"--vsa-impl {args.vsa_impl} does not support --reuse-prefix-kv")
        return args
    
    
    def _link(destination: Path, source: Path) -> None:
        if not source.exists():
            raise FileNotFoundError(f"Missing checkpoint component: {source}")
        source = source.resolve()
        if destination.is_symlink():
            if destination.resolve() == source:
                return
            destination.unlink()
        elif destination.exists():
            raise FileExistsError(f"{destination} exists and is not a symlink; choose another --composed-dir.")
        destination.symlink_to(source, target_is_directory=source.is_dir())
    
    
    def compose_model_dir(export_dir: Path, base_dir: Path, composed_dir: Path) -> Path:
        """One MiniMax-H3 model directory: distilled components from the export, the rest from the base."""
        contract = export_dir / CONTRACT
        if not contract.is_file():
            raise FileNotFoundError(f"{export_dir} has no {CONTRACT}; it is not a FastH3 distilled export.")
        composed_dir.mkdir(parents=True, exist_ok=True)
        for name in (*EXPORT_COMPONENTS, CONTRACT):
            _link(composed_dir / name, export_dir / name)
        for name in MANIFESTS:
            for root in (export_dir, base_dir):
                if (root / name).is_file():
                    _link(composed_dir / name, root / name)
                    break
        for name in BASE_COMPONENTS:
            _link(composed_dir / name, base_dir / name)
        return composed_dir
    
    
    def load_contract(export_dir: Path) -> dict[str, Any]:
        """The export's PDD contract, validated as a Ref2VA one."""
        path = export_dir / CONTRACT
        if not path.is_file():
            raise FileNotFoundError(f"{export_dir} has no {CONTRACT}")
        contract = json.loads(path.read_text(encoding="utf-8"))
        if contract.get("model_type") != "ref2va":
            raise ValueError(f"{path} is not a Ref2VA contract; use the example matching the checkpoint.")
        return contract
    
    
    def resolve_reference_max_pixels(value: str | None, width: int, height: int) -> int | None:
        """``--reference-max-pixels``: unset keeps the trained canvas; 'match' uses the clip's area."""
        if value is None:
            return None
        if value == "match":
            return width * height
        pixels = int(value)
        if pixels <= 0:
            raise ValueError(f"--reference-max-pixels must be positive or 'match', got {value!r}.")
        return pixels
    
    
    def resolve_model_root(args: argparse.Namespace) -> Path:
        if args.model_root is not None:
            return args.model_root
        return compose_model_dir(args.export, args.base_model_path, args.composed_dir)
    
    
    def run(args: argparse.Namespace) -> None:
        if args.compose_only:
            print(f"Composed model directory: {resolve_model_root(args)}")
            return
        from fastvideo.mlx_runtime.minimax_h3_pipeline import MiniMaxH3MLXPipeline
        from fastvideo.mlx_runtime.minimax_h3_reference import MiniMaxH3Reference
    
        model_root = resolve_model_root(args)
        export_dir = args.export if args.export is not None else model_root
        contract = load_contract(export_dir)
        if args.export is not None:
            print(f"Composed model directory: {model_root}")
            print(f"Contract: {contract['num_inference_steps']} fused blocks of a {contract['pdd_steps']}-interval grid, "
                  f"{contract['attention_backend']} with sparsity {contract['vsa_sparsity']}, "
                  f"{contract['vsa_tile_size']}-token tiles")
        references = [MiniMaxH3Reference(source=path, media_type=kind) for kind, path in args.references]
        args.output_path.parent.mkdir(parents=True, exist_ok=True)
    
        pipeline = MiniMaxH3MLXPipeline(
            model_root=model_root,
            mlx_dit_checkpoint=args.mlx_checkpoint,
            vae_dtype=args.vae_dtype,
            vae_decoder_path=args.vae_decoder,
            vae_encoder_path=args.vae_encoder,
            vae_decoder_quantization=args.vae_decoder_quantization,
            prompt_cache_dir=args.prompt_cache_dir,
            metal_wired_limit_gib=args.metal_wired_limit_gib,
            mlx_cache_limit_gib=args.mlx_cache_limit_gib,
            quant_gemm=args.quant_gemm,
        )
        try:
            kwargs: dict[str, Any] = {}
            if args.steps:
                kwargs["num_steps"] = args.steps
            elif "transformer_forwards" in contract:
                # The contract's fused-block count is the ladder the student was distilled on.
                kwargs["num_steps"] = int(contract["transformer_forwards"])
            result = pipeline.generate(
                args.prompt,
                output_path=args.output_path,
                references=references,
                height=args.height,
                width=args.width,
                num_frames=args.num_frames,
                seed=args.seed,
                vsa=args.vsa,
                vsa_sparsity=args.vsa_sparsity,
                vsa_tile_size=args.vsa_tile_size,
                vsa_ref_keep_rate=args.vsa_ref_keep_rate,
                vsa_impl=args.vsa_impl,
                inter_step_cooldown_s=args.inter_step_cooldown_s,
                reuse_prefix_kv=args.reuse_prefix_kv,
                prefix_kv_refresh_every=args.prefix_kv_refresh_every,
                prefix_kv_cache_max_gib=args.prefix_kv_cache_max_gib,
                prefix_kv_storage=args.prefix_kv_storage,
                reference_max_pixels=resolve_reference_max_pixels(args.reference_max_pixels, args.width, args.height),
                **kwargs,
            )
        finally:
            pipeline.close()
        print(json.dumps({
            "video_path": result.video_path,
            "references": [kind for kind, _ in args.references],
            "timings_s": {key: round(value, 2) for key, value in result.timings.items()},
            "peak_memory_gib": {key: round(value, 2) for key, value in result.peak_memory_gib.items()},
            "vsa": result.vsa,
            "prefix_kv": result.prefix_kv,
            "audio_samples": int(result.waveform.shape[-1]),
        }, indent=2))
    
    
    def main() -> None:
        run(parse_args())
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_h3_decode_benchmark.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Compare H3 decoders on saved normalized video rows without rerunning denoise.
    
    The input NPZ must contain a ``video`` array of packed diffusion rows. Geometry
    and the DiT manifest must match the generation that produced those rows.
    """
    from __future__ import annotations
    
    import argparse
    import hashlib
    import json
    import platform
    import resource
    import subprocess
    import time
    from pathlib import Path
    
    import numpy as np
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--latents", type=Path, required=True)
        parser.add_argument("--model-root", type=Path, required=True)
        parser.add_argument("--mlx-checkpoint", type=Path, required=True)
        parser.add_argument("--output-dir", type=Path, required=True)
        parser.add_argument("--height", type=int, default=480)
        parser.add_argument("--width", type=int, default=832)
        parser.add_argument("--num-frames", type=int, default=124)
        parser.add_argument("--backends", nargs="+", choices=("h3-vae", "taeh3"), default=["h3-vae", "taeh3"])
        parser.add_argument("--taeh3-checkpoint", type=Path)
        parser.add_argument("--taeh3-chunk-size", type=int, default=5)
        parser.add_argument("--vae-dtype", choices=("fp32", "fp16", "bf16"), default="fp32")
        parser.add_argument("--repeats", type=int, default=1)
        args = parser.parse_args()
        if args.repeats < 1:
            parser.error("--repeats must be positive")
        if args.output_dir.exists():
            parser.error("--output-dir must be a new directory to preserve previous results")
    
        import mlx.core as mx
        from fastvideo.mlx_runtime.minimax_h3_pipeline import MiniMaxH3MLXPipeline, _cleanup_mlx
        from fastvideo.mlx_runtime.minimax_h3_taeh3 import ensure_taeh3_checkpoint
    
        with np.load(args.latents) as archive:
            rows = archive["video"]
        if not np.isfinite(rows).all():
            raise ValueError("The saved video rows contain non-finite values")
        args.output_dir.mkdir(parents=True)
        checksum = hashlib.sha256()
        with args.latents.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1 << 20), b""):
                checksum.update(chunk)
        checkpoint = ensure_taeh3_checkpoint(args.taeh3_checkpoint) if "taeh3" in args.backends else None
        report = {
            "mlx": mx.__version__,
            "platform": platform.platform(),
            "device": mx.device_info(),
            "latents": str(args.latents.resolve()),
            "latents_sha256": checksum.hexdigest(),
            "geometry": [args.height, args.width, args.num_frames],
            "dtype": args.vae_dtype,
            "chunk_size": args.taeh3_chunk_size,
            "checkpoint_download_excluded": True,
            "decoder_loading_included": True,
            "trials": [],
        }
        for repeat in range(args.repeats):
            # Reverse each paired trial's order to expose warmup/order effects.
            order = args.backends if repeat % 2 == 0 else args.backends[::-1]
            for backend in order:
                pipeline = MiniMaxH3MLXPipeline(model_root=args.model_root,
                                               mlx_dit_checkpoint=args.mlx_checkpoint,
                                               video_decode_backend=backend,
                                               taeh3_checkpoint=checkpoint if backend == "taeh3" else None,
                                               taeh3_chunk_size=args.taeh3_chunk_size,
                                               vae_dtype=args.vae_dtype)
                _cleanup_mlx()
                mx.reset_peak_memory()
                before = subprocess.check_output(["sysctl", "-n", "vm.swapusage"], text=True).strip()
                started = time.perf_counter()
                frames = pipeline.decode_video(rows, height=args.height, width=args.width, num_frames=args.num_frames)
                elapsed = time.perf_counter() - started
                trial = {
                    "repeat": repeat,
                    "backend": backend,
                    "decode_s": elapsed,
                    "shape": list(frames.shape),
                    "peak_active_gib": mx.get_peak_memory() / 2**30,
                    "process_lifetime_rss_peak_gib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**30,
                    "swap_before": before,
                    "swap_after": subprocess.check_output(["sysctl", "-n", "vm.swapusage"], text=True).strip(),
                }
                if repeat == 0:
                    np.save(args.output_dir / f"{backend}_frames.npy", frames)
                report["trials"].append(trial)
                (args.output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n")
                print(json.dumps(trial), flush=True)
                del frames, pipeline
                _cleanup_mlx()
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_rife_smoke_test.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """Tiny MLX RIFE frame-interpolation smoke test."""
    
    from __future__ import annotations
    
    import argparse
    import time
    
    import numpy as np
    
    from fastvideo.mlx_runtime.rife_interp import interpolate, load_model
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(
            description="MLX RIFE 4.25 frame interpolation smoke test."
        )
        parser.add_argument(
            "--self-test",
            action="store_true",
            help="Run a tiny two-frame interpolation test.",
        )
        args = parser.parse_args()
        if not args.self_test:
            raise SystemExit("Nothing to do; pass --self-test")
    
        frame0 = np.zeros((64, 96, 3), dtype=np.uint8)
        frame1 = np.zeros((64, 96, 3), dtype=np.uint8)
        frame1[:, :, 0] = 255
        start = time.perf_counter()
        model = load_model()
        load_s = time.perf_counter() - start
        start = time.perf_counter()
        frames = interpolate([frame0, frame1], factor=2, model=model)
        interp_s = time.perf_counter() - start
        assert len(frames) == 3
        assert frames[1].shape == frame0.shape
        assert frames[1].dtype == np.uint8
        print(
            "MLX RIFE self-test passed: "
            f"load_s={load_s:.3f} interp_s={interp_s:.3f} shape={frames[1].shape}"
        )
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_wan22_generate.py"

    ```py
    # SPDX-License-Identifier: Apache-2.0
    """End-to-end FastMetal-5B-QAD generation on Apple Silicon (MLX DiT + MLX TAEHV).
    
    This is the Wan2.2 TI2V entrypoint. Use FastVideo/FastMetal-5B-QAD:
    
        hf download FastVideo/FastMetal-5B-QAD --local-dir ./FastMetal-5B-QAD
        python examples/inference/basic/mlx_wan22_generate.py \\
          --mlx-checkpoint ./FastMetal-5B-QAD \\
          --text-encoder-root ./FastMetal-5B-QAD \\
          --vae-root ./FastMetal-5B-QAD/vae
    
    Pipeline: torch/MPS UMT5 encode (shared with 1.3B) → MLXWan22DiT 3-step DMD
    (warped schedule, flow_shift=5) → MLX TAEHV decode (taew2_2.pth). Fully MLX
    on the heavy DiT + decode path.
    
    Decoder backends: ``taehv`` (default, MLX, ~seconds), ``taehv-torch`` (parity),
    ``wan-vae`` (full AutoencoderKLWan on MPS, slow).
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import time
    from pathlib import Path
    
    import numpy as np
    
    from fastvideo.mlx_runtime.fast_spatial import DEFAULT_FAST_SPATIAL_SHARPEN
    from fastvideo.mlx_runtime.frame_upsample import DEFAULT_PIXEL_UPSAMPLE_MODE, PIXEL_UPSAMPLE_MODES
    from fastvideo.mlx_runtime.memory import cleanup_mlx
    from fastvideo.mlx_runtime.prompt_cache import (
        fingerprint_digest,
        load_prompt_cache,
        save_prompt_cache,
        text_encoder_fingerprint,
    )
    from fastvideo.mlx_runtime.checkpoint_compat import (
        UnsupportedMLXCheckpointError,
        raise_if_unsupported_mlx_checkpoint,
        resolve_mlx_checkpoint,
    )
    from fastvideo.mlx_runtime.rife_interp import aligned_keyframe_count
    
    FASTWAN21_MODEL_ID = "FastVideo/FastWan2.1-T2V-1.3B-Diffusers"
    FASTWAN22_MODEL_ID = "FastVideo/FastWan2.2-TI2V-5B-FullAttn-Diffusers"
    DEFAULT_HEIGHT = 448
    DEFAULT_WIDTH = 832
    DEFAULT_NUM_FRAMES = 121
    
    def _resolve_model_paths(
        *,
        text_encoder_root: Path | None,
        dit_checkpoint: Path | None,
        dit_config: Path | None,
        vae_root: Path | None,
        mlx_checkpoint: Path | None,
        decode_backend: str,
    ) -> tuple[Path, Path | None, Path | None, Path | None]:
        """Download only the missing assets required by the selected Wan2.2 path."""
        from huggingface_hub import snapshot_download
    
        if text_encoder_root is None:
            text_encoder_root = Path(snapshot_download(
                FASTWAN21_MODEL_ID,
                allow_patterns=["tokenizer/*", "text_encoder/*"],
            ))
        if mlx_checkpoint is None and (dit_checkpoint is None or dit_config is None):
            patterns = []
            if dit_checkpoint is None:
                patterns.append("transformer/diffusion_pytorch_model.safetensors")
            if dit_config is None:
                patterns.append("transformer/config.json")
            model_root = Path(snapshot_download(FASTWAN22_MODEL_ID, allow_patterns=patterns))
            dit_checkpoint = dit_checkpoint or model_root / "transformer/diffusion_pytorch_model.safetensors"
            dit_config = dit_config or model_root / "transformer/config.json"
        if decode_backend == "wan-vae" and vae_root is None:
            model_root = Path(snapshot_download(FASTWAN22_MODEL_ID, allow_patterns=["vae/*"]))
            vae_root = model_root / "vae"
        return text_encoder_root, dit_checkpoint, dit_config, vae_root
    
    
    def _prompt_cache_fingerprint(
        *,
        prompt: str,
        prompt_used: str,
        enhance_prompt: bool,
        enhance_prompt_backend: str,
        text_encoder_root: Path,
        max_sequence_length: int,
        dtype: str,
    ) -> dict[str, object]:
        return {
            "prompt": prompt,
            "prompt_used": prompt_used,
            "enhance_prompt": enhance_prompt,
            "enhance_prompt_backend": enhance_prompt_backend,
            "text_encoder": text_encoder_fingerprint(text_encoder_root),
            "max_sequence_length": max_sequence_length,
            "dtype": dtype,
        }
    
    
    def _default_prompt_cache_path(fingerprint: dict[str, object]) -> Path:
        """Content-addressed default cache file for a prompt fingerprint.
    
        The Wan2.1 entrypoint caches prompt embeddings by default; this one only
        did so when handed an explicit ``--prompt-embeds-cache`` path, so every 5B
        run paid a full UMT5 encode (~45s on an M4 Max) even for a repeat prompt.
        The fingerprint already covers everything that changes the embedding, so
        hash it for the filename.
        """
        digest = fingerprint_digest(fingerprint)[:32]
        return Path.home() / ".cache" / "fastvideo" / "prompt_embeds" / f"wan22_{digest}.npy"
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(
            description="MLX Wan2.2-5B T2V (encode → DiT DMD → TAEHV/VAE decode)"
        )
        parser.add_argument(
            "--prompt",
            default="A red fox trotting through a snowy pine forest at golden hour, cinematic",
        )
        parser.add_argument(
            "--output-path",
            type=Path,
            default=Path("video_samples/demo_5b/fox_5b_mlx.mp4"),
        )
        parser.add_argument(
            "--text-encoder-root",
            type=Path,
            default=None,
            help="Root with text_encoder/ + tokenizer/",
        )
        parser.add_argument(
            "--prompt-embeds-cache",
            type=Path,
            default=None,
            help="Explicit .npy UMT5 embedding cache file. Overrides the automatic "
            "content-addressed cache (--prompt-cache).",
        )
        parser.add_argument(
            "--prompt-cache",
            action=argparse.BooleanOptionalAction,
            default=True,
            help="Cache prompt embeddings under ~/.cache/fastvideo/prompt_embeds so "
            "repeat runs skip the text encoder entirely. Default: on.",
        )
        parser.add_argument(
            "--text-encoder-device",
            choices=("auto", "cpu", "mps"),
            default="cpu",
            help="Device for UMT5 encoding. CPU is safest beside the 5B MLX DiT.",
        )
        parser.add_argument(
            "--enhance-prompt",
            action="store_true",
            help="Apply deterministic local cinematic prompt enrichment before UMT5.",
        )
        parser.add_argument(
            "--enhance-prompt-backend",
            choices=("template",),
            default="template",
            help="Prompt enrichment backend.",
        )
        parser.add_argument(
            "--dit-checkpoint",
            type=Path,
            default=None,
        )
        parser.add_argument("--dit-config", type=Path, default=None)
        parser.add_argument(
            "--mlx-checkpoint",
            type=Path,
            default=None,
            help="Packed FastMetal-5B-QAD MLX DiT directory (mlx_dit.json + mlx_dit.safetensors). "
            "If omitted, a FastMetal directory passed as --text-encoder-root is used when it "
            "already contains those files.",
        )
        parser.add_argument("--vae-root", type=Path, default=None)
        parser.add_argument("--height", type=int, default=DEFAULT_HEIGHT)
        parser.add_argument("--width", type=int, default=DEFAULT_WIDTH)
        parser.add_argument(
            "--num-frames",
            type=int,
            default=DEFAULT_NUM_FRAMES,
            help="Pixel frames (121 at 24fps = 5.04 seconds)",
        )
        parser.add_argument("--seed", type=int, default=1234)
        parser.add_argument("--renoise-seed", type=int, default=0)
        parser.add_argument("--fps", type=int, default=24)
        parser.add_argument("--flow-shift", type=float, default=5.0)
        parser.add_argument("--dmd-denoising-steps", default="1000,757,522")
        parser.add_argument(
            "--no-warp",
            action="store_true",
            help="Disable schedule warping (debug only).",
        )
        parser.add_argument(
            "--fast",
            action="store_true",
            help="Generate fewer frames then RIFE-interpolate to --num-frames.",
        )
        parser.add_argument("--fast-factor", type=int, default=2)
        parser.add_argument("--fast-sharpen", type=float, default=0.6)
        parser.add_argument(
            "--fast-spatial",
            action="store_true",
            help="Denoise and decode at reduced spatial resolution, then resample "
            "the decoded frames up to the target size.",
        )
        parser.add_argument("--fast-spatial-scale", type=int, default=2)
        parser.add_argument(
            "--fast-spatial-upsample-mode",
            choices=PIXEL_UPSAMPLE_MODES,
            default=DEFAULT_PIXEL_UPSAMPLE_MODE,
        )
        parser.add_argument("--fast-spatial-sharpen", type=float, default=DEFAULT_FAST_SPATIAL_SHARPEN)
        parser.add_argument(
            "--refine",
            action="store_true",
            help="Two-pass DMD: coarse denoise, upsample/re-noise, full-res denoise.",
        )
        parser.add_argument("--refine-scale", type=int, default=2)
        parser.add_argument(
            "--refine-upsample-mode",
            choices=("bilinear", "nearest"),
            default="bilinear",
        )
        parser.add_argument("--no-refine-add-noise", action="store_true")
        parser.add_argument(
            "--decode-backend",
            choices=("taehv", "taehv-torch", "wan-vae"),
            default="taehv",
        )
        parser.add_argument("--save-latents", type=Path, default=None)
        parser.add_argument("--metrics-json", type=Path, default=None,
                            help="Write measured run metadata as JSON for reports or galleries.")
        parser.add_argument(
            "--compile",
            action="store_true",
            help="Compile the DiT forward with mx.compile; fallback to eager on failure.",
        )
        args = parser.parse_args()
    
        if args.fast_factor < 2:
            parser.error("--fast-factor must be at least 2")
        # --fast-spatial used to be rejected here because it upsampled the completed
        # 48-channel latent, which is out of distribution for the decoder and gave
        # black or noisy video. The upsample now runs on decoded frames, so the
        # latent never leaves the grid it was denoised on and the mode is usable.
        if args.refine and args.fast_spatial:
            print("[wan22] --refine takes precedence over --fast-spatial")
    
        args.mlx_checkpoint = resolve_mlx_checkpoint(args.mlx_checkpoint, args.text_encoder_root)
        if args.mlx_checkpoint is not None:
            if args.text_encoder_root is None and (args.mlx_checkpoint / "text_encoder").is_dir():
                args.text_encoder_root = args.mlx_checkpoint
            if args.vae_root is None and (args.mlx_checkpoint / "vae").is_dir():
                args.vae_root = args.mlx_checkpoint / "vae"
        try:
            raise_if_unsupported_mlx_checkpoint(args.mlx_checkpoint, args.dit_checkpoint)
        except UnsupportedMLXCheckpointError as exc:
            raise SystemExit(str(exc)) from exc
    
        args.text_encoder_root, args.dit_checkpoint, args.dit_config, args.vae_root = _resolve_model_paths(
            text_encoder_root=args.text_encoder_root,
            dit_checkpoint=args.dit_checkpoint,
            dit_config=args.dit_config,
            vae_root=args.vae_root,
            mlx_checkpoint=args.mlx_checkpoint,
            decode_backend=args.decode_backend,
        )
        target_frames = args.num_frames
        if args.fast:
            args.num_frames = aligned_keyframe_count(target_frames, args.fast_factor)
            print(
                f"[wan22 fast] generating {args.num_frames} frames, "
                f"RIFE {args.fast_factor}x -> {target_frames}"
            )
    
        import mlx.core as mx
        import torch
    
        from examples.inference.basic.mlx_wan_prompt_to_video import (
            _postprocess_video,
            encode_prompt,
            make_rotary_embeddings,
        )
        from fastvideo.mlx_runtime.fast_spatial import plan_fast_spatial
        from fastvideo.mlx_runtime.refine import (
            default_refine_timesteps,
            plan_refine_resolutions,
            prepare_refine_latents,
        )
        from fastvideo.mlx_runtime.wan22 import (
            mlx_wan22_dit_from_diffusers_safetensors,
            mlx_wan22_dit_from_mlx_checkpoint,
        )
        from fastvideo.mlx_runtime.wan22_sample import build_wan22_dmd_schedule, sample_wan22_dmd
        from fastvideo.mlx_runtime.wan_vae import decode_latents_to_video
    
        if args.mlx_checkpoint is not None:
            config = json.loads((args.mlx_checkpoint / "mlx_dit.json").read_text())["config"]
        else:
            config = json.loads(args.dit_config.read_text())
        patch_size = tuple(config.get("patch_size", (1, 2, 2)))
        if args.refine:
            active_plan = plan_refine_resolutions(
                height=args.height, width=args.width, num_frames=args.num_frames,
                spatial_scale=args.refine_scale, vae_spatial_compression=16,
                vae_temporal_compression=4, patch_size=patch_size, enabled=True,
            )
            spatial_mode = "refine"
        elif args.fast_spatial:
            fast_spatial_plan = plan_fast_spatial(
                height=args.height, width=args.width, num_frames=args.num_frames,
                spatial_scale=args.fast_spatial_scale, vae_spatial_compression=16,
                vae_temporal_compression=4, patch_size=patch_size,
                upsample_mode=args.fast_spatial_upsample_mode,
                sharpen=args.fast_spatial_sharpen, enabled=True,
            )
            active_plan = fast_spatial_plan.plan
            spatial_mode = "fast_spatial"
        else:
            active_plan = plan_refine_resolutions(
                height=args.height, width=args.width, num_frames=args.num_frames,
                spatial_scale=1, vae_spatial_compression=16, vae_temporal_compression=4,
                patch_size=patch_size, enabled=False,
            )
            spatial_mode = "off"
        lat_h, lat_w = active_plan.stage1_latent_height, active_plan.stage1_latent_width
        lat_t = active_plan.latent_frames
        in_ch = int(config["in_channels"])
        print(f"[5B] latent {in_ch}x{lat_t}x{lat_h}x{lat_w}", flush=True)
    
        total_start = time.perf_counter()
        prompt_for_encode = args.prompt
        enhance_backend = None
        enhance_elapsed_s = 0.0
        if args.enhance_prompt:
            from fastvideo.mlx_runtime.prompt_enhance import enhance_prompt
    
            enhancement = enhance_prompt(args.prompt, backend=args.enhance_prompt_backend)
            prompt_for_encode = enhancement.enhanced
            enhance_backend = enhancement.backend
            enhance_elapsed_s = enhancement.elapsed_s
            print(f"[enhance] backend={enhance_backend} in {enhance_elapsed_s:.2f}s", flush=True)
            print(f"[enhance] prompt: {prompt_for_encode}", flush=True)
    
        t0 = time.perf_counter()
        prompt_cache_fingerprint = _prompt_cache_fingerprint(
            prompt=args.prompt,
            prompt_used=prompt_for_encode,
            enhance_prompt=args.enhance_prompt,
            enhance_prompt_backend=args.enhance_prompt_backend,
            text_encoder_root=args.text_encoder_root,
            max_sequence_length=512,
            dtype="fp16",
        )
        prompt_cache_path = args.prompt_embeds_cache
        if prompt_cache_path is None and args.prompt_cache:
            prompt_cache_path = _default_prompt_cache_path(prompt_cache_fingerprint)
        cached_embeds = load_prompt_cache(
            prompt_cache_path,
            prompt_cache_fingerprint,
        )
        if cached_embeds is not None:
            embeds = torch.from_numpy(cached_embeds).contiguous()
        else:
            embeds = encode_prompt(
                model_root=args.text_encoder_root,
                prompt=prompt_for_encode,
                max_sequence_length=512,
                device_arg=args.text_encoder_device,
                dtype_arg="fp16",
            )
            save_prompt_cache(
                prompt_cache_path,
                embeds.cpu().numpy(),
                prompt_cache_fingerprint,
            )
        ehs = mx.array(embeds.numpy()).astype(mx.float16)
        prompt_encode_s = time.perf_counter() - t0
        print(f"[5B] prompt encoded {tuple(ehs.shape)} in {prompt_encode_s:.1f}s", flush=True)
    
        t1 = time.perf_counter()
        if args.mlx_checkpoint is not None:
            dit = mlx_wan22_dit_from_mlx_checkpoint(
                args.mlx_checkpoint,
                compile=args.compile,
            )
        else:
            dit = mlx_wan22_dit_from_diffusers_safetensors(
                args.dit_checkpoint,
                args.dit_config,
                dtype="fp16",
                compile=args.compile,
            )
        dit_load_s = time.perf_counter() - t1
        print(f"[5B] DiT loaded in {dit_load_s:.1f}s", flush=True)
    
        freqs = make_rotary_embeddings(config, latent_frames=lat_t, latent_height=lat_h, latent_width=lat_w)
        gen = torch.Generator().manual_seed(args.seed)
        noise = mx.array(
            torch.randn(1, in_ch, lat_t, lat_h, lat_w, generator=gen, dtype=torch.float32).numpy()).astype(mx.float16)
    
        steps = [int(s) for s in args.dmd_denoising_steps.split(",") if s.strip()]
        t2 = time.perf_counter()
        mx.reset_peak_memory()
        latents = sample_wan22_dmd(
            dit,
            ehs,
            noise,
            freqs,
            dmd_denoising_steps=steps,
            flow_shift=args.flow_shift,
            warp_denoising_step=not args.no_warp,
            seed=args.renoise_seed,
        )
        if spatial_mode == "refine":
            schedule, warped_steps = build_wan22_dmd_schedule(
                steps, flow_shift=args.flow_shift, warp_denoising_step=not args.no_warp,
            )
            # The grid opens at sigma == 1, where the hand-off
            # `(1 - sigma) * upsampled + sigma * noise` weights stage 1 at zero and
            # refine silently becomes a plain full-res run. Drop the leading
            # full-noise steps so stage 1 actually reaches stage 2.
            stage2_warped = default_refine_timesteps(schedule, warped_steps)
            stage2_steps = steps[len(warped_steps) - len(stage2_warped):]
            sigma = schedule.sigma_for(stage2_warped[0])
            print(f"[5B refine] stage-2 steps={stage2_steps} sigma={sigma:.4f} "
                  f"(stage-1 weight {1.0 - sigma:.4f})", flush=True)
            latents = prepare_refine_latents(
                latents, scale=args.refine_scale, sigma=sigma,
                add_noise_flag=not args.no_refine_add_noise,
                upsample_mode=args.refine_upsample_mode, seed=args.renoise_seed + 1,
            )
            freqs_stage2 = make_rotary_embeddings(
                config, latent_frames=lat_t,
                latent_height=active_plan.stage2_latent_height,
                latent_width=active_plan.stage2_latent_width,
            )
            latents = sample_wan22_dmd(
                dit, ehs, latents, freqs_stage2, dmd_denoising_steps=stage2_steps,
                flow_shift=args.flow_shift, warp_denoising_step=not args.no_warp,
                seed=args.renoise_seed + 2,
            )
        # spatial_mode == "fast_spatial" leaves the latents on the stage-1 grid;
        # the resample happens after decode, in _postprocess_video.
        denoise_s = time.perf_counter() - t2
        peak = mx.get_peak_memory() / (1024**3)
        print(f"[5B] denoise {len(steps)} steps in {denoise_s:.1f}s, peak {peak:.2f} GiB", flush=True)
    
        latents_np = np.array(latents.astype(mx.float32))
        if args.save_latents is not None:
            args.save_latents.parent.mkdir(parents=True, exist_ok=True)
            np.savez(args.save_latents, latents=latents_np, prompt=args.prompt, seed=args.seed)
            print(f"[5B] wrote latents {args.save_latents}", flush=True)
    
        if spatial_mode == "refine":
            del freqs_stage2
        del dit, latents, ehs, noise, freqs
        cleanup_mlx()
    
        metrics = decode_latents_to_video(
            latents_np,
            args.output_path,
            fps=args.fps,
            backend=args.decode_backend,
            vae_dir=args.vae_root if args.decode_backend == "wan-vae" else None,
            z_dim=in_ch,
        )
        # One h264 round-trip for both post-decode passes (see _postprocess_video).
        rife_s = 0.0
        rife_request = ({
            "factor": args.fast_factor,
            "target_frames": target_frames,
            "sharpen": args.fast_sharpen,
        } if args.fast else None)
        spatial_request = fast_spatial_plan if spatial_mode == "fast_spatial" else None
        if rife_request is not None or spatial_request is not None:
            rife_start = time.perf_counter()
            _postprocess_video(
                video_path=args.output_path, fps=args.fps,
                rife=rife_request, spatial=spatial_request,
            )
            rife_s = time.perf_counter() - rife_start
        print(f"[5B] decoded via {metrics['backend']} in {metrics['decode_s']:.1f}s → {args.output_path}", flush=True)
        summary = {
            "output_path": str(args.output_path.resolve()),
            "prompt": args.prompt,
            "prompt_used": prompt_for_encode,
            "enhance_prompt": args.enhance_prompt,
            "enhance_backend": enhance_backend,
            "enhance_elapsed_s": round(enhance_elapsed_s, 3),
            "height": args.height,
            "width": args.width,
            "fps": args.fps,
            "target_frames": target_frames,
            "generated_frames": args.num_frames,
            "seed": args.seed,
            "renoise_seed": args.renoise_seed,
            "dmd_denoising_steps": steps,
            "flow_shift": args.flow_shift,
            "warp": not args.no_warp,
            "spatial_mode": spatial_mode,
            "fast": args.fast,
            "fast_factor": args.fast_factor if args.fast else None,
            "fast_spatial_scale": args.fast_spatial_scale if args.fast_spatial else None,
            "refine_scale": args.refine_scale if args.refine else None,
            "decode_backend": args.decode_backend,
            "prompt_encode_s": round(prompt_encode_s, 3),
            "dit_load_s": round(dit_load_s, 3),
            "denoise_s": round(denoise_s, 3),
            "decode_s": round(metrics["decode_s"], 3),
            "rife_s": round(rife_s, 3),
            "wall_total_s": round(time.perf_counter() - total_start, 3),
            "peak_gib": round(peak, 3),
            "latent_shape": [in_ch, lat_t, lat_h, lat_w],
            "stage2_latent_shape": [in_ch, lat_t, active_plan.stage2_latent_height, active_plan.stage2_latent_width],
            "mlx_checkpoint": str(args.mlx_checkpoint.resolve()) if args.mlx_checkpoint else None,
        }
        if args.metrics_json is not None:
            args.metrics_json.parent.mkdir(parents=True, exist_ok=True)
            args.metrics_json.write_text(json.dumps(summary, indent=2) + "\n")
            print(f"[5B] wrote metrics {args.metrics_json}", flush=True)
        print(json.dumps(summary, indent=2), flush=True)
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_wan_decode_benchmark.py"

    ```py
    """Compare Wan VAE and TAEHV decode on saved FastWan latents."""
    
    from __future__ import annotations
    
    import argparse
    import json
    import time
    from pathlib import Path
    
    import numpy as np
    
    from examples.inference.basic.mlx_wan_prompt_to_video import DEFAULT_MODEL_ROOT, decode_latents_to_video
    
    
    def _torch_mps_memory() -> dict[str, int | None]:
        """
        Report current and recommended memory usage for the MPS backend.
    
        Returns:
            dict[str, int | None]: Memory metrics in bytes, or `None` values when
                PyTorch or MPS is unavailable.
        """
        try:
            import torch
        except ImportError:
            return {
                "current_allocated_bytes": None,
                "driver_allocated_bytes": None,
                "recommended_max_bytes": None,
            }
        if not torch.backends.mps.is_available():
            return {
                "current_allocated_bytes": None,
                "driver_allocated_bytes": None,
                "recommended_max_bytes": None,
            }
        return {
            "current_allocated_bytes": int(torch.mps.current_allocated_memory()),
            "driver_allocated_bytes": int(torch.mps.driver_allocated_memory()),
            "recommended_max_bytes": int(torch.mps.recommended_max_memory()),
        }
    
    
    def _parse_backends(raw: str) -> list[str]:
        """
        Parse and validate a comma-separated list of decoding backends.
    
        Parameters:
            raw (str): Comma-separated backend names.
    
        Returns:
            list[str]: Trimmed, supported backend names in input order.
    
        Raises:
            ValueError: If the input contains an unsupported backend.
        """
        backends = [backend.strip() for backend in raw.split(",") if backend.strip()]
        allowed = {"wan-vae", "taehv"}
        unknown = sorted(set(backends) - allowed)
        if unknown:
            raise ValueError(f"Unsupported decode backends: {unknown}")
        return backends
    
    
    def main() -> None:
        """
        Benchmark selected Wan latent decoding backends and record their performance metrics.
    
        Loads the specified latent array, decodes it with each selected backend, exports the
        results as MP4 files, and writes per-backend timing and Torch MPS memory metrics to
        `metrics.json`.
        """
        parser = argparse.ArgumentParser(description="Benchmark decode backends on saved Wan/FastWan latents.")
        parser.add_argument("--model-root", type=Path, default=DEFAULT_MODEL_ROOT)
        parser.add_argument("--latents-path", type=Path, required=True)
        parser.add_argument("--output-dir", type=Path, default=Path("video_samples/mlx_decode_benchmark"))
        parser.add_argument("--backends", default="wan-vae,taehv")
        parser.add_argument("--fps", type=int, default=16)
        parser.add_argument("--torch-device", default="auto")
        parser.add_argument("--torch-dtype", choices=("fp16", "fp32"), default="fp16")
        parser.add_argument("--taehv-source-path", type=Path, default=None)
        parser.add_argument("--taehv-checkpoint-path", type=Path, default=None)
        parser.add_argument("--taehv-parallel", action="store_true")
        args = parser.parse_args()
    
        latents = np.load(args.latents_path)
        args.output_dir.mkdir(parents=True, exist_ok=True)
        rows = []
    
        for backend in _parse_backends(args.backends):
            print(f"=== Decode backend: {backend} ===")
            before = _torch_mps_memory()
            start = time.perf_counter()
            output_path = args.output_dir / f"{args.latents_path.stem}_{backend}.mp4"
            decode_latents_to_video(
                model_root=args.model_root,
                latents_np=latents,
                output_path=output_path,
                fps=args.fps,
                device_arg=args.torch_device,
                dtype_arg=args.torch_dtype,
                backend=backend,
                taehv_source_path=args.taehv_source_path,
                taehv_checkpoint_path=args.taehv_checkpoint_path,
                taehv_parallel=args.taehv_parallel,
            )
            elapsed = time.perf_counter() - start
            after = _torch_mps_memory()
            metrics = {
                "backend": backend,
                "latents_path": str(args.latents_path),
                "latents_shape": list(latents.shape),
                "decode_export_s": elapsed,
                "torch_mps_current_before_bytes": before["current_allocated_bytes"],
                "torch_mps_current_after_bytes": after["current_allocated_bytes"],
                "torch_mps_driver_before_bytes": before["driver_allocated_bytes"],
                "torch_mps_driver_after_bytes": after["driver_allocated_bytes"],
                "torch_mps_recommended_max_bytes": after["recommended_max_bytes"],
                "output_path": str(output_path),
            }
            rows.append(metrics)
            print(json.dumps(metrics, indent=2))
    
        metrics_path = args.output_dir / "metrics.json"
        metrics_path.write_text(json.dumps(rows, indent=2))
        print(f"Wrote decode metrics to: {metrics_path}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_wan_prompt_to_video.py"

    ```py
    """Generate a FastMetal text-to-video clip with the Apple Silicon MLX runtime.
    
    This is the supported source-tree entrypoint for FastMetal-QAD (Wan2.1 1.3B
    and 14B). Use ``mlx_wan22_generate.py`` for FastMetal-5B-QAD.
    
    Download FastMetal-QAD and point ``--model-root`` / ``--mlx-checkpoint`` at it:
    
        hf download FastVideo/FastMetal-1.3B-QAD --local-dir ./FastMetal-1.3B-QAD
        python examples/inference/basic/mlx_wan_prompt_to_video.py \\
          --model-root ./FastMetal-1.3B-QAD --mlx-checkpoint ./FastMetal-1.3B-QAD
    
    CUDA FastWan-QAD (``FastVideo/FastWan-QAD-1.3B``, ``FastVideo/FastWan-QAD-FP8-1.3B``)
    is a separate NVIDIA release.
    
    FastMetal-QAD Hugging Face repos ship ``mlx_dit.json`` + ``mlx_dit.safetensors``,
    not a Diffusers ``transformer/`` tree. Do not copy ``transformer/config.json``
    from Wan2.1 or other checkpoints; point ``--mlx-checkpoint`` at the FastMetal
    directory and the example reads the DiT config from ``mlx_dit.json``.
    
    - Hugging Face/torch encodes the prompt with UMT5 (bf16 by default: fp32
      exponent range without fp16 overflow risk, at fp16 memory cost).
    - MLX runs the FastMetal DiT denoising loop (INT8 by default, compiled with
      ``mx.compile`` unless ``--no-mlx-compile``).
    - TAEHV (default, fast/low-memory) or the full Wan VAE (``--decode-backend
      wan-vae``, higher fidelity, bf16) decodes the final latents.
    
    Defaults produce the validated release shape: 480x832, 81 frames, 3-step DMD.
    
    Optional quality / speed levers (compose freely):
    
    * ``--refine`` — H3 / LTX-2 two-pass: denoise at base res, upsample +
      re-noise, re-denoise at target res with the same DiT.
    * ``--fast`` — RIFE temporal fast mode (fewer frames → interpolate).
    * ``--fast-spatial`` — spatial twin of RIFE: denoise *and decode* at half
      res, then resample the decoded frames to the target size (no second
      denoise). Orthogonal to ``--fast``. Attention is O(tokens²), so this is
      the largest single denoise lever available: 86.1s → 10.3s at 1.3B.
    * ``--enhance-prompt`` — local Context-IR-style prompt enrichment
      (template or mlx-lm) before UMT5 encode.
    
    ``--fast`` + ``--refine`` is the B composition: fewer frames at base res,
    then a full-res refine pass. Works for Wan2.1-1.3B/14B and Wan2.2-5B.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import subprocess
    import sys
    import tempfile
    import time
    from dataclasses import replace
    from pathlib import Path
    from typing import TYPE_CHECKING
    
    import numpy as np
    
    from fastvideo.mlx_runtime.fast_spatial import DEFAULT_FAST_SPATIAL_SHARPEN
    from fastvideo.mlx_runtime.frame_upsample import DEFAULT_PIXEL_UPSAMPLE_MODE, PIXEL_UPSAMPLE_MODES
    from fastvideo.mlx_runtime.memory import (
        add_memory_limit_args,
        apply_memory_limits,
        cleanup_mlx,
        cleanup_torch_mps,
    )
    from fastvideo.mlx_runtime.prompt_cache import (
        fingerprint_digest,
        load_prompt_cache,
        save_prompt_cache,
        text_encoder_fingerprint,
    )
    from fastvideo.mlx_runtime.checkpoint_compat import (
        UnsupportedMLXCheckpointError,
        raise_if_unsupported_mlx_checkpoint,
        resolve_mlx_checkpoint,
    )
    from fastvideo.mlx_runtime.rife_interp import aligned_keyframe_count
    
    if TYPE_CHECKING:  # pragma: no cover - typing only
        from fastvideo.mlx_runtime.fast_spatial import FastSpatialPlan
    
    
    DEFAULT_MODEL_ID = "FastVideo/FastMetal-1.3B-QAD"
    
    # Legacy pinned-snapshot location, kept for callers that import it (the MLX
    # benchmark harness). New code should prefer resolve_model_root(None), which
    # resolves whatever snapshot the local HF cache has (downloading if needed).
    DEFAULT_MODEL_ROOT = (
        Path.home()
        / ".cache/huggingface/hub/models--FastVideo--FastWan2.1-T2V-1.3B-Diffusers/"
        "snapshots/25e7ed7f41fd8ce2fdd108688c65e8caf0ce3aef"
    )
    
    
    def resolve_model_root(
        model_root: Path | None,
        *,
        model_id: str = DEFAULT_MODEL_ID,
        include_transformer: bool = True,
    ) -> Path:
        """Return a usable model directory, resolving via the HF cache if unset.
    
        A user-supplied ``model_root`` is returned as-is. Otherwise the model is
        resolved through ``huggingface_hub.snapshot_download``, which reuses the
        local cache when present and downloads the current snapshot when not —
        no hardcoded snapshot hash.
        """
        if model_root is not None:
            return model_root
        from huggingface_hub import snapshot_download
    
        # Always fetch the auxiliary assets. A pre-quantized MLX checkpoint does
        # not need the raw transformer weights; the default Diffusers path does.
        allow_patterns = [
            "model_index.json",
            "scheduler/*",
            "tokenizer/*",
            "text_encoder/*",
            "vae/*",
            "mlx_dit.json",
            "mlx_dit.safetensors",
            "ema/mlx_dit.json",
            "ema/mlx_dit.safetensors",
            "transformer/*" if include_transformer else "transformer/config.json",
        ]
        return Path(snapshot_download(
            model_id,
            allow_patterns=allow_patterns,
        ))
    
    
    def _torch_device(device_arg: str):
        import torch
    
        if device_arg == "auto":
            return torch.device("mps" if torch.backends.mps.is_available() else "cpu")
        return torch.device(device_arg)
    
    
    def _torch_dtype(dtype_arg: str):
        import torch
    
        return {"fp16": torch.float16, "bf16": torch.bfloat16, "fp32": torch.float32}[dtype_arg]
    
    
    def encode_prompt(
        *,
        model_root: Path,
        prompt: str,
        max_sequence_length: int,
        device_arg: str,
        dtype_arg: str,
    ):
        import torch
        from transformers import AutoTokenizer, UMT5EncoderModel
    
        device = _torch_device(device_arg)
        dtype = _torch_dtype(dtype_arg)
        tokenizer = AutoTokenizer.from_pretrained(model_root / "tokenizer", local_files_only=True)
        text_encoder = UMT5EncoderModel.from_pretrained(
            model_root / "text_encoder",
            torch_dtype=dtype,
            low_cpu_mem_usage=True,
            local_files_only=True,
        ).to(device)
        text_encoder.eval()
    
        text_inputs = tokenizer(
            [prompt],
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="pt",
        )
        text_input_ids = text_inputs.input_ids.to(device)
        mask = text_inputs.attention_mask.to(device)
        seq_lens = mask.gt(0).sum(dim=1).long()
    
        with torch.no_grad():
            prompt_embeds = text_encoder(text_input_ids, mask).last_hidden_state
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens, strict=False)]
        prompt_embeds = torch.stack(
            [
                torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))])
                for u in prompt_embeds
            ],
            dim=0,
        )
        if prompt_embeds.dtype == torch.bfloat16:
            # NumPy (and the .npy cache/subprocess transport) has no bfloat16;
            # fp32 is exact for every bf16 value.
            prompt_embeds = prompt_embeds.float()
        prompt_embeds = prompt_embeds.cpu().contiguous()
        del text_encoder, tokenizer, text_inputs, text_input_ids, mask, seq_lens
        cleanup_torch_mps()
        return prompt_embeds
    
    
    def encode_prompt_subprocess(
        *,
        model_root: Path,
        prompt: str,
        max_sequence_length: int,
        device_arg: str,
        dtype_arg: str,
    ):
        import torch
    
        with tempfile.TemporaryDirectory(prefix="fastvideo_prompt_embeds_") as tmpdir:
            output_path = Path(tmpdir) / "prompt_embeds.npy"
            subprocess.run(
                [
                    sys.executable,
                    str(Path(__file__).resolve()),
                    "--model-root",
                    str(model_root),
                    "--prompt",
                    prompt,
                    "--max-sequence-length",
                    str(max_sequence_length),
                    "--torch-device",
                    device_arg,
                    "--text-encoder-dtype",
                    dtype_arg,
                    "--encode-prompt-only",
                    str(output_path),
                ],
                check=True,
            )
            prompt_embeds = np.load(output_path)
        return torch.from_numpy(prompt_embeds).contiguous()
    
    
    def _prompt_cache_fingerprint(
        *,
        model_root: Path,
        prompt: str,
        max_sequence_length: int,
        dtype_arg: str,
    ) -> dict[str, object]:
        return {
            "prompt": prompt,
            "text_encoder": text_encoder_fingerprint(model_root),
            "max_sequence_length": max_sequence_length,
            "dtype": dtype_arg,
        }
    
    
    def _default_prompt_cache_path(
        *,
        model_root: Path,
        prompt: str,
        max_sequence_length: int,
        dtype_arg: str,
    ) -> Path:
        fingerprint = _prompt_cache_fingerprint(
            model_root=model_root,
            prompt=prompt,
            max_sequence_length=max_sequence_length,
            dtype_arg=dtype_arg,
        )
        digest = fingerprint_digest(fingerprint)[:32]
        return Path.home() / ".cache" / "fastvideo" / "prompt_embeds" / f"{digest}.npy"
    
    
    def get_prompt_embeds(
        *,
        model_root: Path,
        prompt: str,
        max_sequence_length: int,
        device_arg: str,
        dtype_arg: str,
        encode_mode: str,
        cache_path: Path | None,
    ):
        import torch
    
        fingerprint = None
        if cache_path is not None:
            fingerprint = _prompt_cache_fingerprint(
                model_root=model_root,
                prompt=prompt,
                max_sequence_length=max_sequence_length,
                dtype_arg=dtype_arg,
            )
            cached = load_prompt_cache(cache_path, fingerprint)
            if cached is not None:
                return torch.from_numpy(cached).contiguous()
    
        if encode_mode == "subprocess":
            prompt_embeds = encode_prompt_subprocess(
                model_root=model_root,
                prompt=prompt,
                max_sequence_length=max_sequence_length,
                device_arg=device_arg,
                dtype_arg=dtype_arg,
            )
        elif encode_mode == "inline":
            prompt_embeds = encode_prompt(
                model_root=model_root,
                prompt=prompt,
                max_sequence_length=max_sequence_length,
                device_arg=device_arg,
                dtype_arg=dtype_arg,
            )
        else:
            raise ValueError(f"Unsupported prompt encode mode: {encode_mode}")
    
        if cache_path is not None and fingerprint is not None:
            save_prompt_cache(cache_path, prompt_embeds.cpu().numpy(), fingerprint)
        return prompt_embeds
    
    
    def make_rotary_embeddings(config: dict, *, latent_frames: int, latent_height: int, latent_width: int):
        import mlx.core as mx
        import torch
    
        from fastvideo.layers.rotary_embedding import get_rotary_pos_embed
    
        num_heads = int(config["num_attention_heads"])
        head_dim = int(config["attention_head_dim"])
        hidden_size = num_heads * head_dim
        patch_size = tuple(config["patch_size"])
        post_patch = (
            latent_frames // patch_size[0],
            latent_height // patch_size[1],
            latent_width // patch_size[2],
        )
        rope_dim_list = [head_dim - 4 * (head_dim // 6), 2 * (head_dim // 6), 2 * (head_dim // 6)]
        freqs_cos, freqs_sin = get_rotary_pos_embed(
            post_patch,
            hidden_size,
            num_heads,
            rope_dim_list,
            dtype=torch.float32,
            rope_theta=10000,
        )
        return (
            mx.array(freqs_cos.numpy()).astype(mx.float32),
            mx.array(freqs_sin.numpy()).astype(mx.float32),
        )
    
    
    def decode_latents_to_video(
        *,
        model_root: Path,
        latents_np: np.ndarray,
        output_path: Path,
        fps: int,
        device_arg: str,
        dtype_arg: str,
        backend: str,
        taehv_source_path: Path | None,
        taehv_checkpoint_path: Path | None,
        taehv_parallel: bool,
    ) -> None:
        if backend == "taehv":
            if taehv_source_path is None:
                from fastvideo.mlx_runtime.wan_vae import decode_latents_to_video as decode_latents_to_video_mlx
    
                decode_latents_to_video_mlx(
                    latents_np,
                    output_path,
                    fps=fps,
                    backend="taehv",
                    z_dim=latents_np.shape[1],
                    taehv_checkpoint=taehv_checkpoint_path,
                    torch_device=device_arg,
                )
                return
    
            device = _torch_device(device_arg)
            dtype = _torch_dtype(dtype_arg)
            from fastvideo.mlx_runtime.taehv_decode import decode_latents_to_video_taehv
    
            decode_latents_to_video_taehv(
                latents_np=latents_np,
                output_path=output_path,
                fps=fps,
                device=device,
                dtype=dtype,
                parallel=taehv_parallel,
                source_path=taehv_source_path,
                checkpoint_path=taehv_checkpoint_path,
            )
            cleanup_torch_mps()
            return
    
        if backend != "wan-vae":
            raise ValueError(f"Unsupported decode backend: {backend}")
    
        import torch
        from diffusers import AutoencoderKLWan
        from diffusers.video_processor import VideoProcessor
        from diffusers.utils import export_to_video
    
        device = _torch_device(device_arg)
        dtype = _torch_dtype(dtype_arg)
        vae = AutoencoderKLWan.from_pretrained(
            model_root / "vae",
            torch_dtype=dtype,
            low_cpu_mem_usage=True,
            local_files_only=True,
        ).to(device)
        vae.eval()
    
        latents = torch.from_numpy(latents_np).to(device=device, dtype=dtype)
        latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(device, dtype)
        latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(device, dtype)
        latents = latents / latents_std + latents_mean
    
        with torch.no_grad():
            video = vae.decode(latents, return_dict=False)[0]
        video = VideoProcessor(vae_scale_factor=vae.config.scale_factor_spatial).postprocess_video(video, output_type="np")
        output_path.parent.mkdir(parents=True, exist_ok=True)
        export_to_video(video[0], str(output_path), fps=fps)
        del vae, latents, latents_mean, latents_std, video
        cleanup_torch_mps()
    
    
    def _unsharp(frame: np.ndarray, amount: float) -> np.ndarray:
        """Light unsharp mask to counter RIFE's optical-flow softening."""
        from fastvideo.mlx_runtime.frame_upsample import unsharp
    
        return unsharp(frame, amount)
    
    
    def _postprocess_video(*, video_path: Path, fps: int, rife: dict | None = None,
                           spatial: "FastSpatialPlan | None" = None) -> None:
        """Apply the post-decode passes to the written mp4 in a single re-encode.
    
        ``--fast`` (RIFE frame interpolation) and ``--fast-spatial`` (pixel-space
        upsample of a reduced-resolution decode) both operate on decoded frames.
        Running them as separate in-place rewrites would put the video through two
        lossy h264 round-trips, so they share one read/write here.
    
        RIFE runs first, at the smaller frame size: optical flow is estimated on
        fewer pixels (cheaper) and the interpolated frames then ride through the
        same upsample as the keyframes, which keeps the clip spatially uniform.
    
        Sharpening is applied once, at the end and at full resolution. Both passes
        soften for the same reason (they synthesise pixels they do not have), so
        stacking two unsharp masks over-crisps; the stronger of the two requested
        amounts is used instead.
        """
        import imageio.v3 as iio
    
        if rife is None and spatial is None:
            return
    
        frames = [frame for frame in iio.imread(video_path)]
        labels = []
        sharpen = 0.0
    
        if rife is not None:
            from fastvideo.mlx_runtime.rife_interp import interpolate as rife_interpolate, load_model
    
            factor, target_frames = rife["factor"], rife["target_frames"]
            frames = rife_interpolate(frames, factor=factor, model=load_model())
            if len(frames) < target_frames:
                raise RuntimeError(f"RIFE produced {len(frames)} frames, fewer than requested {target_frames}")
            frames = frames[:target_frames]
            sharpen = max(sharpen, float(rife["sharpen"] or 0.0))
            labels.append(f"RIFE {factor}x -> {len(frames)} frames")
    
        if spatial is not None and spatial.enabled:
            from fastvideo.mlx_runtime.fast_spatial import apply_fast_spatial_upsample
    
            # The plan's own sharpen is folded into the single pass below.
            frames = apply_fast_spatial_upsample(frames, replace(spatial, sharpen=0.0))
            sharpen = max(sharpen, float(spatial.sharpen))
            labels.append(f"upsample {spatial.scale}x -> {spatial.target_width}x{spatial.target_height} "
                          f"({spatial.upsample_mode})")
    
        if sharpen > 0.0:
            frames = [_unsharp(frame, sharpen) for frame in frames]
            labels.append(f"unsharp {sharpen:.2f}")
    
        iio.imwrite(video_path, np.stack(frames), fps=fps, codec="libx264")
        print(f"[post] {', '.join(labels)} written to {video_path}")
    
    
    def _rife_interpolate_video(*, video_path: Path, target_frames: int, factor: int,
                                sharpen: float, fps: int) -> None:
        """Read the reduced-frame mp4, RIFE-interpolate up to ``target_frames`` on
        Apple Silicon, optionally light-sharpen, and rewrite the file in place."""
        _postprocess_video(
            video_path=video_path,
            fps=fps,
            rife={"factor": factor, "target_frames": target_frames, "sharpen": sharpen},
        )
    
    
    def main() -> None:
        parser = argparse.ArgumentParser(
            description="Prompt-to-video FastMetal-QAD generation using the Apple Silicon MLX runtime")
        parser.add_argument("--model-root", type=Path, default=None,
                            help="FastMetal-QAD directory (tokenizer, UMT5, VAE, packed MLX DiT). "
                            f"Defaults to the local HF cache for {DEFAULT_MODEL_ID} "
                            "(downloading it if missing).")
        parser.add_argument(
            "--prompt",
            default="A bird's-eye view of a misty forest valley at dawn.",
        )
        parser.add_argument("--output-path", type=Path, default=Path("video_samples/mlx_fastwan_prompt_to_video.mp4"))
        parser.add_argument("--height", type=int, default=480)
        parser.add_argument("--width", type=int, default=832)
        parser.add_argument("--num-frames", type=int, default=81)
        parser.add_argument("--num-inference-steps", type=int, default=3)
        parser.add_argument("--dmd-denoising-steps", default="1000,757,522")
        parser.add_argument("--denoising-mode", choices=("dmd", "scheduler"), default="dmd")
        parser.add_argument("--flow-shift", type=float, default=8.0)
        parser.add_argument(
            "--refine",
            action=argparse.BooleanOptionalAction,
            default=False,
            help="Two-pass H3/LTX-2 refine: denoise at height/width // refine-scale, then "
            "upsample latents and re-denoise at the full target resolution with the same "
            "DiT (no new model / no training). DMD mode only.",
        )
        parser.add_argument(
            "--refine-scale",
            type=int,
            default=2,
            help="Spatial upsample factor between stage-1 and stage-2 (default: 2).",
        )
        parser.add_argument(
            "--refine-dmd-denoising-steps",
            default=None,
            help="Optional stage-2 DMD timesteps (comma-separated). Defaults to "
            "--dmd-denoising-steps when unset.",
        )
        parser.add_argument(
            "--refine-sigma",
            type=float,
            default=None,
            help="Override the stage-2 hand-off noise level (0-1). Lower keeps more "
            "of the stage-1 draft. Normally derived from the first stage-2 timestep, "
            "which keeps the noise level and the timestep the DiT is told consistent; "
            "setting this decouples them, so the DiT sees a latent noised differently "
            "than its timestep implies. Experimental — for exploring schedules whose "
            "grid bottoms out too high (see the Wan2.2-5B note in the design doc).",
        )
        parser.add_argument(
            "--refine-add-noise",
            action=argparse.BooleanOptionalAction,
            default=True,
            help="Re-noise upsampled stage-1 latents before the stage-2 denoise "
            "(default: on; disable with --no-refine-add-noise).",
        )
        parser.add_argument(
            "--refine-upsample-mode",
            choices=("bilinear", "nearest"),
            default="bilinear",
            help="Latent spatial upsample mode for the refine hand-off.",
        )
        parser.add_argument(
            "--save-stage1-latents",
            action="store_true",
            help="When --refine is set, also dump stage-1 clean latents next to the output.",
        )
        parser.add_argument(
            "--fast-spatial",
            action=argparse.BooleanOptionalAction,
            default=False,
            help="Spatial fast mode: denoise and decode at height/width // "
            "fast-spatial-scale, then resample the decoded frames up to the target "
            "size (no second denoise — that is --refine). Composes with --fast "
            "(RIFE). If both --fast-spatial and --refine are set, refine wins "
            "(quality path).",
        )
        parser.add_argument(
            "--fast-spatial-scale",
            type=int,
            default=2,
            help="Spatial downsample factor for --fast-spatial (default: 2).",
        )
        parser.add_argument(
            "--fast-spatial-upsample-mode",
            choices=PIXEL_UPSAMPLE_MODES,
            default=DEFAULT_PIXEL_UPSAMPLE_MODE,
            help="Pixel-space interpolation kernel used to resample the decoded "
            f"stage-1 frames (default: {DEFAULT_PIXEL_UPSAMPLE_MODE}).",
        )
        parser.add_argument(
            "--fast-spatial-sharpen",
            type=float,
            default=DEFAULT_FAST_SPATIAL_SHARPEN,
            help="Light unsharp strength to counter resampling softness "
            f"(default: {DEFAULT_FAST_SPATIAL_SHARPEN}; 0 disables).",
        )
        parser.add_argument(
            "--enhance-prompt",
            action=argparse.BooleanOptionalAction,
            default=False,
            help="Local H3 Context-IR-style prompt enrichment before UMT5 encode. "
            "Uses --enhance-prompt-backend (template always available; mlx-lm optional).",
        )
        parser.add_argument(
            "--enhance-prompt-backend",
            choices=("auto", "template", "mlx-lm"),
            default="auto",
            help="auto: try mlx-lm then fall back to template. template: deterministic "
            "cinematic expansion. mlx-lm: require a local instruct model.",
        )
        parser.add_argument(
            "--enhance-prompt-model",
            default=None,
            help="mlx-lm model id/path (default: mlx-community/Qwen2.5-0.5B-Instruct-4bit).",
        )
        parser.add_argument(
            "--enhance-prompt-cache",
            action=argparse.BooleanOptionalAction,
            default=True,
            help="Cache enhanced prompts under ~/.cache/fastvideo/enhanced_prompts (default: on).",
        )
        parser.add_argument("--max-sequence-length", type=int, default=512)
        parser.add_argument("--seed", type=int, default=1024)
        parser.add_argument("--fps", type=int, default=16)
        parser.add_argument("--fast", action=argparse.BooleanOptionalAction, default=False,
                            help="Fast mode: generate 1/factor of the frames, then RIFE-interpolate up "
                            "to --num-frames on Apple Silicon (~2.7x faster denoise, reconstruction "
                            "MS-SSIM ~0.97). Composes with --refine (B: fewer frames at base res, "
                            "full-res refine) and --fast-spatial. Uses the vendored MLX RIFE backend. "
                            "See docs/experiments/rife-speedup-summary.md.")
        parser.add_argument("--fast-factor", type=int, default=2,
                            help="Fast-mode interpolation factor (2 = generate half the frames).")
        parser.add_argument("--fast-sharpen", type=float, default=0.6,
                            help="Light unsharp strength to counter RIFE softness (0 disables).")
        parser.add_argument("--torch-device", default="auto", help="'auto', 'mps', or 'cpu' for text/VAE components.")
        parser.add_argument("--torch-dtype", choices=("fp16", "bf16", "fp32"), default="fp16",
                            help="Dtype for the TAEHV decode path (and legacy callers).")
        parser.add_argument("--text-encoder-dtype", choices=("bf16", "fp16", "fp32"), default="bf16",
                            help="UMT5 prompt-encode dtype. bf16 keeps the fp32 exponent range "
                            "(no fp16 overflow risk in the T5 stack) at fp16 memory cost; the "
                            "reference CUDA pipeline encodes in fp32. Pass fp16 if your "
                            "macOS/torch build lacks bf16 on MPS.")
        parser.add_argument("--vae-decode-dtype", choices=("bf16", "fp16", "fp32"), default="bf16",
                            help="Wan VAE decode dtype (wan-vae backend only). bf16 matches the "
                            "reference pipeline's effectively-lossless decode default.")
        parser.add_argument("--mlx-dtype", choices=("fp16", "bf16", "fp32"), default="fp16")
        parser.add_argument(
            "--mlx-quantization",
            choices=("none", "int8", "int4", "mxfp8", "mxfp4", "nvfp4"),
            default="int8",
        )
        parser.add_argument("--mlx-compile", action=argparse.BooleanOptionalAction, default=True,
                            help="Compile the DiT forward with mx.compile (bit-identical to eager, "
                            "~1.4x faster denoise; falls back to eager if tracing fails). "
                            "Disable with --no-mlx-compile.")
        parser.add_argument("--metrics-json", type=Path, default=None)
        parser.add_argument("--save-latents", action="store_true")
        parser.add_argument("--decode-backend", choices=("wan-vae", "taehv"), default="taehv",
                            help="taehv (default): fast, low-memory tiny decoder. "
                            "wan-vae: full Wan VAE in bf16 — slower and heavier but higher fidelity.")
        parser.add_argument("--taehv-source-path", type=Path, default=None)
        parser.add_argument("--taehv-checkpoint-path", type=Path, default=None)
        parser.add_argument("--taehv-parallel", action="store_true", help="Decode all TAEHV frames at once; faster but higher memory.")
        parser.add_argument("--prompt-encode-mode", choices=("inline", "subprocess"), default="inline")
        parser.add_argument("--prompt-embeds-cache", type=Path, default=None,
                            help="Explicit prompt-embedding cache file. Overrides the "
                            "automatic content-addressed cache (--prompt-cache).")
        parser.add_argument("--prompt-cache", action=argparse.BooleanOptionalAction, default=True,
                            help="Cache prompt embeddings under ~/.cache/fastvideo/prompt_embeds "
                            "keyed by (model, prompt, length, dtype), so repeat runs skip "
                            "the text encoder entirely. Default: on.")
        parser.add_argument("--mlx-checkpoint", type=Path, default=None,
                            help="Packed FastMetal MLX DiT directory (mlx_dit.json + mlx_dit.safetensors). "
                            "Defaults to --model-root when that directory already contains those files.")
        parser.add_argument("--save-mlx-checkpoint", type=Path, default=None,
                            help="After loading the DiT, save it (cast + quantized) as an MLX "
                            "checkpoint directory for fast reloads via --mlx-checkpoint.")
        add_memory_limit_args(parser)
        parser.add_argument("--encode-prompt-only", type=Path, default=None, help=argparse.SUPPRESS)
        args = parser.parse_args()
    
        # Fast mode: generate fewer frames now, RIFE-interpolate back up after decode.
        # Composes with --refine (B): stage-1/2 both see the reduced frame count;
        # RIFE restores the target length after the final decode.
        fast_target_frames = None
        if args.fast:
            if args.fast_factor < 2:
                parser.error("--fast-factor must be >= 2")
            fast_target_frames = args.num_frames
    
        if args.fast_spatial and args.fast_spatial_scale < 2:
            parser.error("--fast-spatial-scale must be >= 2 when --fast-spatial is set")
        if args.refine and args.fast_spatial:
            print("[fast-spatial] note: --refine is set; refine wins (quality path). "
                  "--fast-spatial upsample-only path is skipped.")
    
        runtime_limits = apply_memory_limits(
            mlx_memory_limit_gib=args.mlx_memory_limit_gib,
            mlx_cache_limit_gib=args.mlx_cache_limit_gib,
            mlx_disable_cache=args.mlx_disable_cache,
            mlx_wired_limit_gib=args.mlx_wired_limit_gib,
            torch_mps_high_watermark_ratio=args.torch_mps_high_watermark_ratio,
            torch_mps_low_watermark_ratio=args.torch_mps_low_watermark_ratio,
        ).as_metrics()
    
        model_root = resolve_model_root(
            args.model_root,
            include_transformer=args.mlx_checkpoint is None and args.encode_prompt_only is None,
        )
    
        if args.encode_prompt_only is not None:
            prompt_embeds = encode_prompt(
                model_root=model_root,
                prompt=args.prompt,
                max_sequence_length=args.max_sequence_length,
                device_arg=args.torch_device,
                dtype_arg=args.text_encoder_dtype,
            )
            args.encode_prompt_only.parent.mkdir(parents=True, exist_ok=True)
            np.save(args.encode_prompt_only, prompt_embeds.cpu().numpy())
            return
    
        mlx_checkpoint = resolve_mlx_checkpoint(args.mlx_checkpoint, model_root)
        try:
            raise_if_unsupported_mlx_checkpoint(mlx_checkpoint or model_root)
        except UnsupportedMLXCheckpointError as exc:
            raise SystemExit(str(exc)) from exc
    
        import mlx.core as mx
        import torch
        from diffusers import UniPCMultistepScheduler
    
        from fastvideo.models.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
        from fastvideo.mlx_runtime.fast_spatial import (
            plan_fast_spatial,
            resolve_spatial_mode,
        )
        from fastvideo.mlx_runtime.fastwan import mlx_dit_from_diffusers_safetensors
        from fastvideo.mlx_runtime.prompt_enhance import (
            enhance_result_as_metrics,
            load_or_enhance_prompt,
        )
        from fastvideo.mlx_runtime.refine import plan_refine_resolutions, run_two_pass_dmd
        from fastvideo.mlx_runtime.sampling import MLXDMDSchedule, dmd_step
    
        mx.random.seed(args.seed)
        torch.manual_seed(args.seed)
    
        if args.refine and args.denoising_mode != "dmd":
            raise SystemExit("--refine currently requires --denoising-mode dmd")
        if args.refine and args.refine_scale < 2:
            raise SystemExit("--refine-scale must be >= 2 when --refine is set")
    
        spatial_mode = resolve_spatial_mode(refine=args.refine, fast_spatial=args.fast_spatial)
    
        config_path = model_root / "transformer/config.json"
        checkpoint_path = model_root / "transformer/diffusion_pytorch_model.safetensors"
        # Packed FastMetal checkpoints are the architecture authority. Do not
        # require transformer/config.json when mlx_dit.json is already present.
        if mlx_checkpoint is not None:
            mlx_checkpoint_config = json.loads((mlx_checkpoint / "mlx_dit.json").read_text())
            dit_config = mlx_checkpoint_config.get("config", mlx_checkpoint_config)
            config = dit_config
        else:
            if not config_path.is_file():
                raise SystemExit(
                    f"No packed MLX DiT (mlx_dit.json) and no Diffusers transformer config at {config_path}. "
                    "FastMetal-QAD checkpoints intentionally omit transformer/; download "
                    "FastVideo/FastMetal-1.3B-QAD and pass --model-root / --mlx-checkpoint at that directory."
                )
            config = json.loads(config_path.read_text())
            dit_config = config
        if int(dit_config.get("in_channels", 0)) == 48 and int(dit_config.get("out_channels", 0)) == 48:
            raise SystemExit(
                "Wan2.2-TI2V-5B uses 48-channel, per-token timestep conditioning. "
                "Use examples/inference/basic/mlx_wan22_generate.py instead; this "
                "generic Wan2.1 sampler produces invalid outputs for that checkpoint."
            )
        # Latent geometry follows the model's own VAE: Wan2.1 compresses 4x8x8,
        # the Wan2.2 TI2V VAE (48 channels) compresses 4x16x16. Read the factors
        # from the checkpoint's vae config rather than assuming Wan2.1.
        vae_config_path = model_root / "vae/config.json"
        vae_config = json.loads(vae_config_path.read_text()) if vae_config_path.is_file() else {}
        # Wan2.1 uses 16 latent channels with 4x8x8 compression.  Do not inherit
        # the 4x16x16 VAE geometry merely because the asset root belongs to a
        # Wan2.2 checkpoint.
        is_wan21 = int(dit_config.get("in_channels", 0)) == 16
        vae_temporal_factor = 4 if is_wan21 else int(vae_config.get("scale_factor_temporal", 4))
        vae_spatial_factor = 8 if is_wan21 else int(vae_config.get("scale_factor_spatial", 8))
        patch_size = tuple(dit_config.get("patch_size", (1, 2, 2)))
        if fast_target_frames is not None:
            args.num_frames = aligned_keyframe_count(
                fast_target_frames,
                args.fast_factor,
                temporal_compression=vae_temporal_factor,
            )
            print(f"[fast] generating {args.num_frames} frames, RIFE {args.fast_factor}x -> {fast_target_frames}")
    
        # Spatial plan: refine (quality two-pass) or fast-spatial (upsample-only).
        # Both reuse the same resolution splitter; only the post-denoise path differs.
        refine_plan = plan_refine_resolutions(
            height=args.height,
            width=args.width,
            num_frames=args.num_frames,
            spatial_scale=args.refine_scale if spatial_mode == "refine" else 1,
            vae_spatial_compression=vae_spatial_factor,
            vae_temporal_compression=vae_temporal_factor,
            patch_size=patch_size,
            enabled=(spatial_mode == "refine"),
        )
        fast_spatial_plan = plan_fast_spatial(
            height=args.height,
            width=args.width,
            num_frames=args.num_frames,
            spatial_scale=args.fast_spatial_scale,
            vae_spatial_compression=vae_spatial_factor,
            vae_temporal_compression=vae_temporal_factor,
            patch_size=patch_size,
            upsample_mode=args.fast_spatial_upsample_mode,
            sharpen=args.fast_spatial_sharpen,
            enabled=(spatial_mode == "fast_spatial"),
        )
        active_plan = refine_plan if spatial_mode == "refine" else fast_spatial_plan.plan
        # Stage-1 geometry drives the first denoise (and the only denoise when
        # refine is off). Stage-2 / target geometry is used after the hand-off.
        latent_frames = active_plan.latent_frames
        latent_height = active_plan.stage1_latent_height
        latent_width = active_plan.stage1_latent_width
        mx_dtype = {"fp16": mx.float16, "bf16": mx.bfloat16, "fp32": mx.float32}[args.mlx_dtype]
        quantization = None if args.mlx_quantization == "none" else args.mlx_quantization
    
        total_start = time.perf_counter()
    
        # C: optional local prompt enrichment (template or mlx-lm) before UMT5.
        enhance_result = None
        enhance_time = 0.0
        prompt_for_encode = args.prompt
        if args.enhance_prompt:
            enhance_start = time.perf_counter()
            enhance_result = load_or_enhance_prompt(
                args.prompt,
                backend=args.enhance_prompt_backend,
                model=args.enhance_prompt_model,
                cache=args.enhance_prompt_cache,
            )
            enhance_time = time.perf_counter() - enhance_start
            prompt_for_encode = enhance_result.enhanced
            print(
                f"[enhance] backend={enhance_result.backend} "
                f"({enhance_result.elapsed_s:.2f}s cached={enhance_result.backend == 'cache'})"
            )
            print(f"[enhance] original: {enhance_result.original}")
            print(f"[enhance] enhanced: {enhance_result.enhanced}")
            if args.enhance_prompt_backend != "template":
                cleanup_mlx()
    
        prompt_start = time.perf_counter()
        prompt_embeds = get_prompt_embeds(
            model_root=model_root,
            prompt=prompt_for_encode,
            max_sequence_length=args.max_sequence_length,
            device_arg=args.torch_device,
            dtype_arg=args.text_encoder_dtype,
            encode_mode=args.prompt_encode_mode,
            cache_path=args.prompt_embeds_cache
            or (_default_prompt_cache_path(
                model_root=model_root,
                prompt=prompt_for_encode,
                max_sequence_length=args.max_sequence_length,
                dtype_arg=args.text_encoder_dtype,
            ) if args.prompt_cache else None),
        )
        prompt_time = time.perf_counter() - prompt_start
    
        load_start = time.perf_counter()
        mx.clear_cache()
        mx.reset_peak_memory()
        if mlx_checkpoint is not None:
            from fastvideo.mlx_runtime.checkpoint import load_mlx_dit_checkpoint
    
            dit = load_mlx_dit_checkpoint(mlx_checkpoint, compile=args.mlx_compile)
            config = dit.config
        else:
            dit = mlx_dit_from_diffusers_safetensors(
                checkpoint_path,
                config_path,
                dtype=args.mlx_dtype,
                quantization=quantization,
                compile=args.mlx_compile,
            )
        load_time = time.perf_counter() - load_start
        load_peak_memory = mx.get_peak_memory()
    
        if args.save_mlx_checkpoint is not None:
            from fastvideo.mlx_runtime.checkpoint import save_mlx_dit_checkpoint
    
            save_mlx_dit_checkpoint(dit, args.save_mlx_checkpoint)
    
        if args.denoising_mode == "dmd":
            scheduler = FlowMatchEulerDiscreteScheduler(shift=args.flow_shift)
            denoising_steps = [int(step.strip()) for step in args.dmd_denoising_steps.split(",") if step.strip()]
            timesteps = torch.tensor(denoising_steps, dtype=torch.long)
        else:
            scheduler = UniPCMultistepScheduler.from_pretrained(model_root / "scheduler", local_files_only=True)
            scheduler.set_timesteps(args.num_inference_steps, device="cpu")
            scheduler.set_begin_index(0)
            timesteps = scheduler.timesteps
    
        generator = torch.Generator(device="cpu").manual_seed(args.seed)
        latents_torch = torch.randn(
            (1, int(config["in_channels"]), latent_frames, latent_height, latent_width),
            generator=generator,
            dtype=torch.float32,
        )
        latents = mx.array(latents_torch.numpy()).astype(mx_dtype)
        encoder_hidden_states = mx.array(prompt_embeds.numpy()).astype(mx_dtype)
        freqs_cis = make_rotary_embeddings(
            config,
            latent_frames=latent_frames,
            latent_height=latent_height,
            latent_width=latent_width,
        )
    
        # DMD keeps the whole update on the MLX device via the native sampler. Only
        # the (non-distilled) diffusers scheduler path still round-trips to torch.
        dmd_schedule = MLXDMDSchedule.from_torch_scheduler(scheduler) if args.denoising_mode == "dmd" else None
    
        denoise_start = time.perf_counter()
        mx.reset_peak_memory()
        stage1_latents_np = None
        refine_sigma = None
        if args.refine:
            assert dmd_schedule is not None  # guarded above
            # Left unset, the stage-2 grid is derived from the stage-1 one with the
            # leading full-noise step dropped. Reusing --dmd-denoising-steps
            # verbatim would start stage 2 at sigma=1 and discard stage 1.
            refine_steps = None
            if args.refine_dmd_denoising_steps:
                refine_steps = [
                    float(step.strip()) for step in args.refine_dmd_denoising_steps.split(",") if step.strip()
                ]
            freqs_cis_stage2 = make_rotary_embeddings(
                config,
                latent_frames=latent_frames,
                latent_height=refine_plan.stage2_latent_height,
                latent_width=refine_plan.stage2_latent_width,
            )
            print(
                f"[refine] stage1={refine_plan.stage1_width}x{refine_plan.stage1_height} "
                f"-> stage2={refine_plan.target_width}x{refine_plan.target_height} "
                f"(scale={refine_plan.spatial_scale}x, mode={args.refine_upsample_mode})"
            )
            two_pass = run_two_pass_dmd(
                dit=dit,
                encoder_hidden_states=encoder_hidden_states,
                noise_latents_stage1=latents,
                freqs_cis_stage1=freqs_cis,
                freqs_cis_stage2=freqs_cis_stage2,
                plan=refine_plan,
                schedule=dmd_schedule,
                timesteps=[float(t.item()) for t in timesteps],
                refine_timesteps=refine_steps,
                mx_dtype=mx_dtype,
                seed=args.seed,
                add_noise_flag=args.refine_add_noise,
                upsample_mode=args.refine_upsample_mode,
                refine_sigma=args.refine_sigma,
            )
            latents = two_pass.latents
            stage1_latents_np = np.array(two_pass.stage1_latents.astype(mx.float32))
            refine_sigma = two_pass.refine_sigma
            print(f"[refine] stage-2 hand-off sigma={refine_sigma:.4f} "
                  f"(stage-1 weight {1.0 - refine_sigma:.4f})")
            del two_pass, freqs_cis_stage2
        else:
            for step_index, timestep in enumerate(timesteps):
                noise_input_latent = latents
                timestep_mx = mx.array([float(timestep.item())]).astype(mx.float32)
                noise_pred = dit(latents.astype(mx_dtype), encoder_hidden_states, timestep_mx, freqs_cis)
    
                if args.denoising_mode == "dmd":
                    # On-device DMD update: no per-step MLX->torch->MLX round-trip. The
                    # affine math runs in fp32 to match the torch reference precision,
                    # then casts back to the runtime dtype. Re-noise is drawn with MLX's
                    # RNG (seeded above) instead of the torch CPU generator.
                    ts_val = float(timestep.item())
                    noise_input_f32 = noise_input_latent.astype(mx.float32)
                    pred_noise_f32 = noise_pred.astype(mx.float32)
                    if step_index < len(timesteps) - 1:
                        next_ts: float | None = float(timesteps[step_index + 1].item())
                        renoise = mx.random.normal(noise_input_f32.shape).astype(mx.float32)
                    else:
                        next_ts, renoise = None, None
                    latents = dmd_step(
                        latents=noise_input_f32,
                        noise_input_latent=noise_input_f32,
                        pred_noise=pred_noise_f32,
                        schedule=dmd_schedule,
                        timestep=ts_val,
                        next_timestep=next_ts,
                        noise=renoise,
                    ).astype(mx_dtype)
                else:
                    mx.eval(noise_pred)
                    noise_pred_torch = torch.from_numpy(np.array(noise_pred.astype(mx.float32)))
                    latents_torch = torch.from_numpy(np.array(latents.astype(mx.float32)))
                    latents_torch = scheduler.step(noise_pred_torch, timestep, latents_torch, return_dict=False)[0]
                    latents = mx.array(latents_torch.numpy()).astype(mx_dtype)
    
                mx.eval(latents)
                print(f"denoise step {step_index + 1}/{len(timesteps)} complete")
                if args.denoising_mode == "dmd":
                    del noise_input_f32, pred_noise_f32, renoise
                else:
                    del noise_pred_torch, latents_torch
                del noise_input_latent, noise_pred, timestep_mx
    
        # A: spatial fast mode leaves the latents alone. They stay on the stage-1
        # grid through decode, and the resample to the target size happens on the
        # decoded frames in _postprocess_video — interpolating a Wan latent puts it
        # off the decoder's manifold and returns a blurred veil.
        denoise_time = time.perf_counter() - denoise_start
        denoise_peak_memory = mx.get_peak_memory()
        active_memory = mx.get_active_memory()
    
        latents_np = np.array(latents.astype(mx.float32))
        if args.save_latents:
            latent_path = args.output_path.with_suffix(".latents.npy")
            latent_path.parent.mkdir(parents=True, exist_ok=True)
            np.save(latent_path, latents_np)
            print(f"Saved latents to: {latent_path}")
        if args.save_stage1_latents and stage1_latents_np is not None:
            stage1_path = args.output_path.with_name(args.output_path.stem + ".stage1.latents.npy")
            stage1_path.parent.mkdir(parents=True, exist_ok=True)
            np.save(stage1_path, stage1_latents_np)
            print(f"Saved stage-1 latents to: {stage1_path}")
    
        del dit, latents, encoder_hidden_states, freqs_cis
        cleanup_mlx()
    
        decode_start = time.perf_counter()
        decode_latents_to_video(
            model_root=model_root,
            latents_np=latents_np,
            output_path=args.output_path,
            fps=args.fps,
            device_arg=args.torch_device,
            dtype_arg=(args.vae_decode_dtype if args.decode_backend == "wan-vae" else args.torch_dtype),
            backend=args.decode_backend,
            taehv_source_path=args.taehv_source_path,
            taehv_checkpoint_path=args.taehv_checkpoint_path,
            taehv_parallel=args.taehv_parallel,
        )
        decode_time = time.perf_counter() - decode_start
    
        # Post-decode passes share one read/write so the clip takes a single h264
        # round-trip even when --fast and --fast-spatial are combined.
        postprocess_time = 0.0
        rife_request = None
        if fast_target_frames is not None:
            rife_request = {
                "factor": args.fast_factor,
                "target_frames": fast_target_frames,
                "sharpen": args.fast_sharpen,
            }
        spatial_request = fast_spatial_plan if spatial_mode == "fast_spatial" else None
        if rife_request is not None or spatial_request is not None:
            postprocess_start = time.perf_counter()
            _postprocess_video(
                video_path=args.output_path,
                fps=args.fps,
                rife=rife_request,
                spatial=spatial_request,
            )
            postprocess_time = time.perf_counter() - postprocess_start
            print(f"Post-decode (RIFE/upsample) time: {postprocess_time:.2f}s")
        rife_time = postprocess_time
    
        total_time = time.perf_counter() - total_start
    
        if enhance_result is not None:
            print(f"Prompt enhance time: {enhance_time:.2f}s ({enhance_result.backend})")
        print(f"Prompt encode time: {prompt_time:.2f}s")
        print(f"MLX DiT load time: {load_time:.2f}s")
        print(f"MLX denoise time: {denoise_time:.2f}s")
        print(f"Decode/export time: {decode_time:.2f}s")
        if postprocess_time:
            print(f"Post-decode time: {postprocess_time:.2f}s")
        print(f"Total prompt-to-video time: {total_time:.2f}s")
        print(f"MLX load peak memory: {load_peak_memory / (1024 ** 3):.2f} GiB")
        print(f"MLX denoise peak memory: {denoise_peak_memory / (1024 ** 3):.2f} GiB")
        print(f"MLX active memory after denoise: {active_memory / (1024 ** 3):.2f} GiB")
        print(f"Spatial mode: {spatial_mode}")
        print(f"Output written to: {args.output_path}")
    
        if args.metrics_json is not None:
            metrics = {
                "prompt": prompt_for_encode,
                "prompt_user": args.prompt,
                "height": args.height,
                "width": args.width,
                "num_frames": args.num_frames,
                "num_frames_target": fast_target_frames if fast_target_frames is not None else args.num_frames,
                "denoising_mode": args.denoising_mode,
                "dmd_denoising_steps": [int(step.strip()) for step in args.dmd_denoising_steps.split(",") if step.strip()],
                "spatial_mode": spatial_mode,
                "fast": bool(args.fast),
                "fast_factor": args.fast_factor if args.fast else None,
                "fast_spatial": spatial_mode == "fast_spatial",
                "fast_spatial_scale": fast_spatial_plan.scale if spatial_mode == "fast_spatial" else 1,
                "fast_spatial_stage1_height": fast_spatial_plan.stage1_height if spatial_mode == "fast_spatial" else None,
                "fast_spatial_stage1_width": fast_spatial_plan.stage1_width if spatial_mode == "fast_spatial" else None,
                "fast_spatial_upsample_mode": fast_spatial_plan.upsample_mode if spatial_mode == "fast_spatial" else None,
                "fast_spatial_sharpen": fast_spatial_plan.sharpen if spatial_mode == "fast_spatial" else None,
                "refine": spatial_mode == "refine",
                "refine_scale": refine_plan.spatial_scale if spatial_mode == "refine" else 1,
                "refine_stage1_height": refine_plan.stage1_height if spatial_mode == "refine" else None,
                "refine_stage1_width": refine_plan.stage1_width if spatial_mode == "refine" else None,
                "refine_sigma": refine_sigma,
                "refine_upsample_mode": args.refine_upsample_mode if spatial_mode == "refine" else None,
                "refine_add_noise": args.refine_add_noise if spatial_mode == "refine" else None,
                "mlx_dtype": args.mlx_dtype,
                "mlx_quantization": args.mlx_quantization,
                "mlx_compile": args.mlx_compile,
                "text_encoder_dtype": args.text_encoder_dtype,
                "vae_decode_dtype": args.vae_decode_dtype if args.decode_backend == "wan-vae" else None,
                "model_root": str(model_root),
                "decode_backend": args.decode_backend,
                "taehv_parallel": args.taehv_parallel if args.decode_backend == "taehv" else None,
                "prompt_encode_mode": args.prompt_encode_mode,
                "prompt_embeds_cache": str(args.prompt_embeds_cache) if args.prompt_embeds_cache else None,
                "prompt_enhance_s": enhance_time,
                "prompt_encode_s": prompt_time,
                "mlx_dit_load_s": load_time,
                "mlx_denoise_s": denoise_time,
                "vae_decode_export_s": decode_time,
                "decode_export_s": decode_time,
                "rife_interpolate_s": rife_time,
                "postprocess_s": postprocess_time,
                "total_s": total_time,
                **enhance_result_as_metrics(enhance_result),
                "mlx_load_peak_bytes": int(load_peak_memory),
                "mlx_denoise_peak_bytes": int(denoise_peak_memory),
                "mlx_active_after_denoise_bytes": int(active_memory),
                "output_path": str(args.output_path),
                **runtime_limits,
            }
            args.metrics_json.parent.mkdir(parents=True, exist_ok=True)
            args.metrics_json.write_text(json.dumps(metrics, indent=2))
            print(f"Metrics written to: {args.metrics_json}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_wan_quant_benchmark.py"

    ```py
    """Benchmark MLX FastWan quantization modes with one shared prompt encode."""
    
    from __future__ import annotations
    
    import argparse
    import json
    import time
    from pathlib import Path
    from typing import cast
    
    import numpy as np
    
    from examples.inference.basic.mlx_wan_prompt_to_video import (
        DEFAULT_MODEL_ROOT,
        decode_latents_to_video,
        encode_prompt,
        make_rotary_embeddings,
    )
    from fastvideo.mlx_runtime.memory import cleanup_mlx
    
    
    def _parse_modes(raw: str) -> list[str]:
        """
        Parse and validate a comma-separated list of quantization modes.
    
        Parameters:
            raw (str): Comma-separated mode names.
    
        Returns:
            list[str]: Normalized, whitespace-trimmed mode names.
    
        Raises:
            ValueError: If any mode is unsupported.
        """
        modes = [mode.strip() for mode in raw.split(",") if mode.strip()]
        allowed = {"none", "int8", "int4", "mxfp8", "mxfp4", "nvfp4"}
        unknown = sorted(set(modes) - allowed)
        if unknown:
            raise ValueError(f"Unsupported modes: {unknown}")
        return modes
    
    
    def _latent_delta_metrics(candidate: np.ndarray, baseline: np.ndarray) -> dict[str, float]:
        """
        Compare candidate and baseline latent arrays using error and signal-quality metrics.
    
        Parameters:
            candidate (np.ndarray): Latent array to evaluate.
            baseline (np.ndarray): Reference latent array for comparison.
    
        Returns:
            dict[str, float]: Mean squared error, mean absolute error, maximum absolute
            error, and signal-to-noise ratio in decibels between the arrays.
        """
        diff = candidate.astype(np.float32) - baseline.astype(np.float32)
        mse = float(np.mean(np.square(diff)))
        mae = float(np.mean(np.abs(diff)))
        max_abs = float(np.max(np.abs(diff)))
        signal = float(np.mean(np.square(baseline.astype(np.float32))))
        return {
            "latent_mse_vs_fp16": mse,
            "latent_mae_vs_fp16": mae,
            "latent_max_abs_vs_fp16": max_abs,
            "latent_snr_db_vs_fp16": float(10.0 * np.log10(signal / mse)) if mse > 0 else float("inf"),
        }
    
    
    def _torch_mps_memory() -> dict[str, int | None]:
        """
        Report PyTorch MPS memory statistics when PyTorch MPS is available.
    
        Returns:
            dict[str, int | None]: A mapping of MPS memory metric names to byte counts, or `None` values when PyTorch or MPS is unavailable.
        """
        try:
            import torch
        except ImportError:
            return {
                "torch_mps_current_allocated_bytes": None,
                "torch_mps_driver_allocated_bytes": None,
                "torch_mps_recommended_max_bytes": None,
            }
        if not torch.backends.mps.is_available():
            return {
                "torch_mps_current_allocated_bytes": None,
                "torch_mps_driver_allocated_bytes": None,
                "torch_mps_recommended_max_bytes": None,
            }
        return {
            "torch_mps_current_allocated_bytes": int(torch.mps.current_allocated_memory()),
            "torch_mps_driver_allocated_bytes": int(torch.mps.driver_allocated_memory()),
            "torch_mps_recommended_max_bytes": int(torch.mps.recommended_max_memory()),
        }
    
    
    def _decode_with_metrics(*, args, latents: np.ndarray, output_path: Path) -> dict[str, float | int | None | str]:
        """
        Decode latents to a video and collect export timing and PyTorch MPS memory metrics.
    
        Parameters:
            args: Configuration values for decoding and video export.
            latents (np.ndarray): Latent representation to decode.
            output_path (Path): Destination path for the exported video.
    
        Returns:
            dict[str, float | int | None | str]: Video export duration and PyTorch MPS memory measurements.
        """
        before = _torch_mps_memory()
        decode_start = time.perf_counter()
        decode_latents_to_video(
            model_root=args.model_root,
            latents_np=latents,
            output_path=output_path,
            fps=args.fps,
            device_arg=args.torch_device,
            dtype_arg=args.torch_dtype,
            backend=args.decode_backend,
            taehv_source_path=args.taehv_source_path,
            taehv_checkpoint_path=args.taehv_checkpoint_path,
            taehv_parallel=args.taehv_parallel,
        )
        decode_time = time.perf_counter() - decode_start
        after = _torch_mps_memory()
        return {
            "decode_export_s": decode_time,
            "decode_torch_mps_current_before_bytes": before["torch_mps_current_allocated_bytes"],
            "decode_torch_mps_current_after_bytes": after["torch_mps_current_allocated_bytes"],
            "decode_torch_mps_driver_before_bytes": before["torch_mps_driver_allocated_bytes"],
            "decode_torch_mps_driver_after_bytes": after["torch_mps_driver_allocated_bytes"],
            "decode_torch_mps_recommended_max_bytes": after["torch_mps_recommended_max_bytes"],
        }
    
    
    def _run_one_mode(
        *,
        mode: str,
        args,
        config: dict,
        checkpoint_path: Path,
        config_path: Path,
        prompt_embeds,
        freqs_cis,
    ):
        """
        Run denoising for one quantization mode and collect performance and memory metrics.
    
        Parameters:
            mode (str): Quantization mode to benchmark.
            args: Benchmark configuration, including dtype, dimensions, seed, scheduler, and denoising settings.
            config (dict): Model configuration containing the input channel count.
            checkpoint_path (Path): Path to the transformer checkpoint.
            config_path (Path): Path to the transformer configuration.
            prompt_embeds: Encoded prompt embeddings shared across benchmark modes.
            freqs_cis: Rotary positional embeddings used during denoising.
    
        Returns:
            dict: The mode name, generated latent array, and metrics for model loading,
            denoising, step timing, and MLX memory usage.
        """
        import mlx.core as mx
        import torch
    
        from fastvideo.benchmarks.mlx_fastwan_bench import denoise_dmd_on_device
        from fastvideo.models.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
        from fastvideo.mlx_runtime.fastwan import mlx_dit_from_diffusers_safetensors
        from fastvideo.mlx_runtime.sampling import MLXDMDSchedule, dmd_step
    
        mx_dtype = mx.float16 if args.mlx_dtype == "fp16" else mx.float32
        quantization = None if mode == "none" else mode
        latent_frames = (args.num_frames - 1) // 4 + 1
        latent_height = args.height // 8
        latent_width = args.width // 8
    
        load_start = time.perf_counter()
        mx.clear_cache()
        mx.reset_peak_memory()
        dit = mlx_dit_from_diffusers_safetensors(
            checkpoint_path,
            config_path,
            dtype=args.mlx_dtype,
            quantization=quantization,
        )
        load_time = time.perf_counter() - load_start
        load_peak_memory = mx.get_peak_memory()
    
        scheduler = FlowMatchEulerDiscreteScheduler(shift=args.flow_shift)
        schedule = MLXDMDSchedule.from_torch_scheduler(scheduler)
        timesteps = [int(step.strip()) for step in args.dmd_denoising_steps.split(",") if step.strip()]
        # Same torch generator sequence as the original host-round-trip loop
        # (initial latents first, then one re-noise draw per intermediate step),
        # so every mode still shares identical stochasticity.
        generator = torch.Generator(device="cpu").manual_seed(args.seed)
        latents_seed = torch.randn(
            (1, int(config["in_channels"]), latent_frames, latent_height, latent_width),
            generator=generator,
            dtype=torch.float32,
        ).numpy()
        renoise_by_step = [
            torch.randn(latents_seed.shape, generator=generator, dtype=torch.float32).numpy()
            for _ in range(max(0, len(timesteps) - 1))
        ]
        latents = mx.array(latents_seed).astype(mx_dtype)
        encoder_hidden_states = mx.array(prompt_embeds.numpy()).astype(mx_dtype)
    
        denoise_start = time.perf_counter()
        mx.reset_peak_memory()
        latents_np, step_times = denoise_dmd_on_device(
            mx=mx,
            dit=dit,
            latents=latents,
            encoder_hidden_states=encoder_hidden_states,
            freqs_cis=freqs_cis,
            timesteps=timesteps,
            renoise_by_step=renoise_by_step,
            schedule=schedule,
            dmd_step=dmd_step,
            mx_dtype=mx_dtype,
        )
        denoise_time = time.perf_counter() - denoise_start
        denoise_peak_memory = mx.get_peak_memory()
        active_memory = mx.get_active_memory()
        return {
            "mode": mode,
            "latents": latents_np,
            "metrics": {
                "mlx_dit_load_s": load_time,
                "mlx_denoise_s": denoise_time,
                "mlx_denoise_first_step_s": step_times[0] if step_times else None,
                "mlx_load_peak_bytes": int(load_peak_memory),
                "mlx_denoise_peak_bytes": int(denoise_peak_memory),
                "mlx_active_after_denoise_bytes": int(active_memory),
            },
        }
    
    
    def main() -> None:
        """
        Run the MLX FastWan quantization benchmark for the selected modes and write latency, memory, output, and latent-difference metrics to the output directory.
        """
        parser = argparse.ArgumentParser(description="Benchmark MLX FastWan quantization modes.")
        parser.add_argument("--model-root", type=Path, default=DEFAULT_MODEL_ROOT)
        parser.add_argument("--prompt", default="A snow leopard walks across a windy mountain ridge.")
        parser.add_argument("--height", type=int, default=192)
        parser.add_argument("--width", type=int, default=320)
        parser.add_argument("--num-frames", type=int, default=17)
        parser.add_argument("--dmd-denoising-steps", default="1000,757,522")
        parser.add_argument("--flow-shift", type=float, default=8.0)
        parser.add_argument("--max-sequence-length", type=int, default=256)
        parser.add_argument("--seed", type=int, default=1024)
        parser.add_argument("--fps", type=int, default=16)
        parser.add_argument("--torch-device", default="auto")
        parser.add_argument("--torch-dtype", choices=("fp16", "fp32"), default="fp16")
        parser.add_argument("--mlx-dtype", choices=("fp16", "fp32"), default="fp16")
        parser.add_argument("--modes", default="none,int8,int4,mxfp8,mxfp4,nvfp4")
        parser.add_argument("--output-dir", type=Path, default=Path("video_samples/mlx_quant_benchmark"))
        parser.add_argument("--decode-backend", choices=("none", "wan-vae", "taehv"), default="taehv")
        parser.add_argument("--taehv-source-path", type=Path, default=None)
        parser.add_argument("--taehv-checkpoint-path", type=Path, default=None)
        parser.add_argument("--taehv-parallel", action="store_true")
        args = parser.parse_args()
    
        import mlx.core as mx
        import torch
    
        mx.random.seed(args.seed)
        torch.manual_seed(args.seed)
        args.output_dir.mkdir(parents=True, exist_ok=True)
    
        config_path = args.model_root / "transformer/config.json"
        checkpoint_path = args.model_root / "transformer/diffusion_pytorch_model.safetensors"
        config = json.loads(config_path.read_text())
        latent_frames = (args.num_frames - 1) // 4 + 1
        latent_height = args.height // 8
        latent_width = args.width // 8
    
        prompt_start = time.perf_counter()
        prompt_embeds = encode_prompt(
            model_root=args.model_root,
            prompt=args.prompt,
            max_sequence_length=args.max_sequence_length,
            device_arg=args.torch_device,
            dtype_arg=args.torch_dtype,
        )
        prompt_time = time.perf_counter() - prompt_start
        freqs_cis = make_rotary_embeddings(
            config,
            latent_frames=latent_frames,
            latent_height=latent_height,
            latent_width=latent_width,
        )
    
        from fastvideo.mlx_runtime.fastwan import UnsupportedMLXQuantizationError
    
        baseline_latents = None
        rows = []
        for mode in _parse_modes(args.modes):
            print(f"=== MLX quant mode: {mode} ===")
            mode_start = time.perf_counter()
            try:
                result = _run_one_mode(
                    mode=mode,
                    args=args,
                    config=config,
                    checkpoint_path=checkpoint_path,
                    config_path=config_path,
                    prompt_embeds=prompt_embeds,
                    freqs_cis=freqs_cis,
                )
            except UnsupportedMLXQuantizationError as exc:
                print(f"skipping mode (unsupported by this MLX build): {exc}")
                rows.append({"mode": mode, "status": "unsupported_by_mlx", "error": str(exc)})
                continue
            cleanup_mlx(mx)
            latents = result["latents"]
            if baseline_latents is None:
                baseline_latents = latents
            latent_path = args.output_dir / f"latents_{mode}.npy"
            np.save(latent_path, latents)
    
            decode_time = 0.0
            decode_metrics = {}
            output_path = None
            if args.decode_backend != "none":
                output_path = args.output_dir / f"video_{mode}_{args.decode_backend}_{args.height}x{args.width}x{args.num_frames}.mp4"
                decode_metrics = _decode_with_metrics(args=args, latents=latents, output_path=output_path)
                decode_time = cast(float, decode_metrics["decode_export_s"])
    
            mode_total = time.perf_counter() - mode_start
            mlx_denoise_peak_bytes = int(result["metrics"]["mlx_denoise_peak_bytes"])
            mlx_active_bytes = int(result["metrics"]["mlx_active_after_denoise_bytes"])
            metrics = {
                "mode": mode,
                "status": "ok",
                "prompt_encode_shared_s": prompt_time,
                "height": args.height,
                "width": args.width,
                "num_frames": args.num_frames,
                "decode_backend": args.decode_backend,
                "decode_export_s": decode_time,
                "mode_total_excluding_shared_prompt_s": mode_total,
                "mode_total_including_shared_prompt_s": mode_total + prompt_time,
                "latents_path": str(latent_path),
                "output_path": str(output_path) if output_path else None,
                "mlx_denoise_peak_gib": mlx_denoise_peak_bytes / (1024**3),
                "mlx_active_after_denoise_gib": mlx_active_bytes / (1024**3),
                "mlx_dit_peak_under_16gb": mlx_denoise_peak_bytes < 16 * 1024**3,
                "mlx_dit_active_under_16gb": mlx_active_bytes < 16 * 1024**3,
                "mac_16gb_status": (
                    "dit_memory_fits_16gb_measured_decode_separately"
                    if mlx_denoise_peak_bytes < 16 * 1024**3 else "dit_memory_exceeds_16gb"
                ),
                **result["metrics"],
                **decode_metrics,
                **_latent_delta_metrics(latents, baseline_latents),
            }
            rows.append(metrics)
            print(json.dumps(metrics, indent=2))
    
        metrics_path = args.output_dir / "metrics.json"
        metrics_path.write_text(json.dumps(rows, indent=2))
        print(f"Wrote benchmark metrics to: {metrics_path}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "mlx_wan_video_quality.py"

    ```py
    """Compare generated MP4s against a reference MP4 with simple pixel metrics."""
    
    from __future__ import annotations
    
    import argparse
    import json
    from pathlib import Path
    
    import numpy as np
    
    
    def _read_video(path: Path) -> np.ndarray:
        """
        Read all frames from a video file as an RGB NumPy array.
    
        Parameters:
            path (Path): Path to the video file.
    
        Returns:
            np.ndarray: Video frames stacked along the first axis.
    
        Raises:
            ValueError: If the video contains no readable frames.
        """
        import cv2
    
        cap = cv2.VideoCapture(str(path))
        frames = []
        try:
            while True:
                ok, frame_bgr = cap.read()
                if not ok:
                    break
                frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
                frames.append(frame_rgb)
        finally:
            cap.release()
        if not frames:
            raise ValueError(f"No frames read from {path}")
        return np.stack(frames, axis=0)
    
    
    def _metrics(candidate: np.ndarray, reference: np.ndarray) -> dict[str, float | int | list[int]]:
        """
        Compute pixel-level comparison metrics between candidate and reference video frames.
    
        Parameters:
            candidate (np.ndarray): Candidate video frames in frame, height, width, and channel order.
            reference (np.ndarray): Reference video frames with the same shape as the candidate.
    
        Returns:
            dict[str, float | int | list[int]]: Frame dimensions and pixel comparison metrics, including MSE, MAE, maximum absolute difference, and PSNR in decibels.
    
        Raises:
            ValueError: If the candidate and reference arrays have different shapes.
        """
        if candidate.shape != reference.shape:
            raise ValueError(f"Shape mismatch: candidate={candidate.shape}, reference={reference.shape}")
        candidate_f = candidate.astype(np.float32)
        reference_f = reference.astype(np.float32)
        diff = candidate_f - reference_f
        mse = float(np.mean(np.square(diff)))
        mae = float(np.mean(np.abs(diff)))
        max_abs = float(np.max(np.abs(diff)))
        psnr = float(20.0 * np.log10(255.0 / np.sqrt(mse))) if mse > 0 else float("inf")
        return {
            "frames": int(candidate.shape[0]),
            "height": int(candidate.shape[1]),
            "width": int(candidate.shape[2]),
            "channels": int(candidate.shape[3]),
            "mse_vs_reference": mse,
            "mae_vs_reference": mae,
            "max_abs_vs_reference": max_abs,
            "psnr_db_vs_reference": psnr,
        }
    
    
    def main() -> None:
        """Compare candidate MP4 videos with a reference and write pixel-level metrics to a JSON file."""
        parser = argparse.ArgumentParser(description="Compare MP4s against a reference MP4.")
        parser.add_argument("--reference", type=Path, required=True)
        parser.add_argument("--candidates", type=Path, nargs="+", required=True)
        parser.add_argument("--metrics-json", type=Path, required=True)
        args = parser.parse_args()
    
        reference = _read_video(args.reference)
        rows = []
        for candidate_path in args.candidates:
            candidate = _read_video(candidate_path)
            row = {
                "reference_path": str(args.reference),
                "candidate_path": str(candidate_path),
                **_metrics(candidate, reference),
            }
            rows.append(row)
            print(json.dumps(row, indent=2))
    
        args.metrics_json.parent.mkdir(parents=True, exist_ok=True)
        args.metrics_json.write_text(json.dumps(rows, indent=2))
        print(f"Wrote video quality metrics to: {args.metrics_json}")
    
    
    if __name__ == "__main__":
        main()
    
    ```

??? note "qwen_image21_edit.yaml"

    ```yaml
    # Replace source.png and mask.png with your own images. The mask is an ordered
    # reference interpreted by the model, not a hard pixel-preservation constraint.
    generator:
      model_path: Qwen/Qwen-Image-2.1
      engine:
        num_gpus: 1
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: true
          dit_layerwise: true
          text_encoder: true
          vae: true
          lazy_module_load: true
      pipeline:
        workload_type: i2i
        experimental:
          reference_resolution: 1024
          use_kv_cache: true
    request:
      prompt: In image 1, turn the object highlighted by the mask in image 2 blue.
      inputs:
        references:
          - source.png
          - mask.png
      sampling:
        height: 1024
        width: 1024
        num_frames: 1
        fps: 1
        num_inference_steps: 40
        guidance_scale: 1.0
        true_cfg_scale: 1.0
        seed: 42
      output:
        output_path: outputs/qwen_image21/edit.png
        save_video: true
        return_frames: false
    
    ```

??? note "qwen_image21_t2i.yaml"

    ```yaml
    # Run on an allocated CUDA GPU after installing FastVideo and providing weights.
    # fastvideo generate --config examples/inference/basic/qwen_image21_t2i.yaml
    generator:
      model_path: Qwen/Qwen-Image-2.1
      engine:
        num_gpus: 1
        compile:
          enabled: false
          backend: inductor
          fullgraph: false
        parallelism:
          tp_size: 1
          sp_size: 1
        offload:
          dit: true
          dit_layerwise: true
          text_encoder: true
          vae: true
          lazy_module_load: true
      pipeline:
        workload_type: t2i
        experimental:
          kv_cache_device: cuda
          reference_resolution: 1024
          use_kv_cache: true
    request:
      prompt: A red ceramic teapot, isolated on a transparent background.
      sampling:
        height: 1024
        width: 1024
        num_frames: 1
        fps: 1
        num_inference_steps: 40
        guidance_scale: 1.0
        true_cfg_scale: 1.0
        seed: 42
      output:
        output_path: outputs/qwen_image21/teapot.png
        save_video: true
        return_frames: false
    
    ```

??? note "run_fasth3_lora_preview_dense_datafree.sh"

    ```sh
    #!/usr/bin/env bash
    set -euo pipefail
    
    repo="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA"
    adapter="dense-datafree/adapter_model.safetensors"
    adapter_path="$(hf download "$repo" "$adapter")"
    
    python examples/inference/basic/basic_fasth3_lora_preview.py \
      --lora-path "$adapter_path" \
      --lora-strength "${FASTH3_LORA_STRENGTH:-1.0}" \
      --output "${FASTH3_LORA_OUTPUT:-outputs/fasth3_lora_preview/dense-datafree}" \
      "$@" \
      --no-vsa
    
    ```

??? note "run_fasth3_lora_preview_vsa_datafree.sh"

    ```sh
    #!/usr/bin/env bash
    set -euo pipefail
    
    repo="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA"
    adapter="vsa-datafree/adapter_model.safetensors"
    adapter_path="$(hf download "$repo" "$adapter")"
    
    python examples/inference/basic/basic_fasth3_lora_preview.py \
      --lora-path "$adapter_path" \
      --lora-strength "${FASTH3_LORA_STRENGTH:-1.0}" \
      --output "${FASTH3_LORA_OUTPUT:-outputs/fasth3_lora_preview/vsa-datafree}" \
      "$@" \
      --vsa
    
    ```

??? note "run_fasth3_lora_preview_vsa_synthetic_step1300.sh"

    ```sh
    #!/usr/bin/env bash
    set -euo pipefail
    
    repo="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA"
    adapter="vsa-synthetic-step1300/adapter_model.safetensors"
    adapter_path="$(hf download "$repo" "$adapter")"
    
    python examples/inference/basic/basic_fasth3_lora_preview.py \
      --lora-path "$adapter_path" \
      --lora-strength "${FASTH3_LORA_STRENGTH:-1.0}" \
      --output "${FASTH3_LORA_OUTPUT:-outputs/fasth3_lora_preview/vsa-synthetic-step1300}" \
      "$@" \
      --vsa
    
    ```

??? note "run_fasth3_lora_preview_vsa_synthetic_step1900.sh"

    ```sh
    #!/usr/bin/env bash
    set -euo pipefail
    
    repo="FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA"
    adapter="vsa-synthetic-step1900/adapter_model.safetensors"
    adapter_path="$(hf download "$repo" "$adapter")"
    
    python examples/inference/basic/basic_fasth3_lora_preview.py \
      --lora-path "$adapter_path" \
      --lora-strength "${FASTH3_LORA_STRENGTH:-1.0}" \
      --output "${FASTH3_LORA_OUTPUT:-outputs/fasth3_lora_preview/vsa-synthetic-step1900}" \
      "$@" \
      --vsa
    
    ```


