---
title: "Video generation"
canonical: https://docs.qvac.tether.io/sdk/v0.23/ai-capabilities/video-generation/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# Video generation (/sdk/v0.23/ai-capabilities/video-generation)



## Overview

Video generation runs on a **customized Diffusion engine** ([`qvac-ext-stable-diffusion.cpp`](https://github.com/tetherto/qvac-ext-stable-diffusion.cpp)). Load a supported model using `modelType: "diffusion"` with `modelConfig.mode: "video"`. Then call `video()` with a `mode` and `prompt`.

It supports two modes — `txt2vid` (from a text prompt) and `img2vid` (animate a still image) — across the WAN 2.1, Wan 2.2, LTX-2, and MiniMax-H3 model families. `video()` returns `{ progressStream, outputs, stats }`: `outputs` resolves to the generated video(s) as `Uint8Array` buffers (AVI), `progressStream` streams step-by-step progress, and `stats` carries per-run metadata.

<Callout type="warn">
  Video generation is hardware-intensive: it requires at least **16 GB of video
  memory** or **20 GB of unified memory**.
</Callout>

## Functions

Use the following sequence of function calls:

1. [`loadModel()`](/sdk/v0.23/reference/api#loadmodel)
2. [`video()`](/sdk/v0.23/reference/api#video)
3. [`unloadModel()`](/sdk/v0.23/reference/api#unloadmodel)

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

### `video()`

Generates a video from a `prompt` in one of two modes:

#### Modes

* **`txt2vid`** — generate a video from a text prompt alone. Supported by all families.
* **`img2vid`** — animate a still image. Supported by WAN (load the model with `clipVisionModelSrc`, an OpenCLIP ViT-H/14 encoder), LTX-2, and MiniMax-H3. LTX-2 and H3 condition through their video VAEs and need no CLIP-vision encoder.

`img2vid` takes a source frame and, where supported, a denoise strength:

* `init_image` — PNG or JPEG bytes (`Uint8Array`) of the first frame. Required.
* `strength` — a value in `0–1` for WAN and LTX-2. Use higher values when you want the output to diverge more from the first frame. MiniMax-H3 uses its native keyframe conditioning and rejects this field.

#### Generation knobs

Common to all families:

* `video_frames` — number of frames to generate. Wan models use `4k + 1` (e.g. `17`, `33`, `49`, `81`). LTX-2 uses `8k + 1` (e.g. `25`, `121`, `241`). MiniMax-H3 uses `17k + 5` (e.g. `5`, `22`, `39`, `56`, `73`, `90`, `107`, `124`).
* `fps` — output frame rate.
* `cfg_scale` — classifier-free guidance strength. Higher values follow the prompt more closely.
* `flow_shift` — flow-matching shift. For Wan 2.1 T2V, use `3.0`; higher values can produce near-static frames.

LTX-2 adds:

* `temporal_tiling` — set to `true` to cap peak VRAM on HD or long clips. No effect on WAN.

#### LTX-2 reference conditioning (IC-LoRA)

Available in `txt2vid` only. Pass a composite reference sheet together with an Ingredients LoRA so the generated video inherits a specific character or style:

* `scheduler` — set to `'ltx2'`.
* `reference_images` — one composite reference sheet as a `Uint8Array`. Required to enable reference conditioning.
* `lora` — worker-local absolute path to an Ingredients LoRA adapter. Required alongside `reference_images`.
* `lora_strength` — controls how strongly the LoRA steers appearance.
* `reference_attention_strength` — controls how closely the video follows the reference.
* `stg_scale`, `stg_block` — optional; tune them to refine output.
* `reference_downscale_factor` — must be `1`.

#### Wan 2.2 A14B dual-expert knobs

Wan 2.2 A14B routes a second set of knobs to its high-noise expert. They require a model loaded with `modelConfig.highNoiseDiffusionModelSrc` and are rejected on single-expert layouts (Wan 2.1, Wan 2.2 TI2V-5B) with `PluginRequestValidationFailedError`:

* `high_noise_steps` — steps for the high-noise expert.
* `high_noise_sample_method` — sampling method for the high-noise expert.
* `high_noise_scheduler` — scheduler for the high-noise expert.
* `high_noise_cfg_scale` — classifier-free guidance strength for the high-noise expert.
* `high_noise_flow_shift` — flow-matching shift for the high-noise expert.
* `moe_boundary` — boundary at which sampling switches from the high-noise expert to the low-noise expert.

<Callout type="warn">
  Size and frame constraints:

  * `width` and `height` must be positive multiples of **16**.
  * On **LTX-2** and **Wan 2.2 TI2V-5B**, `width` and `height` must be multiples of **32**.
  * On **LTX-2**, `video_frames` must satisfy `8*k + 1` (e.g. `25`, `121`, `241`), with a maximum of **257**.
  * On **LTX-2** with `reference_images`, the minimum `video_frames` rises to **121**.
  * On **MiniMax-H3**, `width` and `height` must be multiples of **32**, `video_frames` must satisfy `17*k + 5`, and `fps` must be **24**. Loading `audioVaeModelSrc` adds synchronized audio at **32 kHz**; omit it for silent video.
</Callout>

The returned `stats` includes `hasAudio` (`true` when the output AVI carries a muxed audio track) and `audioSampleRate` (Hz of that track, `0` when there is no audio).

## Models

Four model families are supported — **WAN 2.1**, **Wan 2.2**, **LTX-2**, and **MiniMax-H3** — and the file layout is auto-selected at load time from the model sources you provide:

* **WAN 2.1 T2V** (txt2vid): split layout — diffusion model + UMT5-XXL text encoder (via `t5XxlModelSrc`) + VAE (via `vaeModelSrc`). Available constants: `WAN2_1_T2V_1_3B_FP16`, `UMT5_XXL_FP16`, `WAN_2_1_COMFYUI_REPACKAGED_VAE`.
* **WAN 2.1 I2V** (img2vid): same split layout as T2V, plus an OpenCLIP ViT-H/14 vision encoder (via `clipVisionModelSrc`). Available constants: `WAN2_1_I2V_14B_Q4_K_M`, `CLIP_VISION_H`, `UMT5_XXL_FP16`, `WAN_2_1_COMFYUI_REPACKAGED_VAE`.
* **Wan 2.2 TI2V-5B** (txt2vid, single-expert): split layout — diffusion model + UMT5-XXL text encoder (via `t5XxlModelSrc`) + Wan 2.2 VAE (via `vaeModelSrc`). The Wan 2.2 VAE's 16× spatial compression is what gives TI2V its 32-pixel grid; the Wan 2.1 VAE is not interchangeable. The UMT5-XXL text encoder is byte-identical to the Wan 2.1 repackage, so both generations share the one registry entry. Available constants: `WAN2_2_TI2V_5B_Q5_K_S`, `UMT5_XXL_FP16`, `WAN_2_2_COMFYUI_REPACKAGED_VAE`.
* **Wan 2.2 A14B** (txt2vid, dual-expert / mixture-of-experts): split layout — low-noise diffusion model + high-noise diffusion model (via `highNoiseDiffusionModelSrc`, whose presence selects this layout) + UMT5-XXL text encoder + Wan 2.2 VAE. The A14B-only `high_noise_*` and `moe_boundary` request fields route to the high-noise expert and are rejected on single-expert layouts.
* **LTX-2** (txt2vid and img2vid): split layout — diffusion model + Gemma text encoder (via `llmModelSrc`) + video VAE (via `vaeModelSrc`) + text-embedding connectors (via `embeddingsConnectorsModelSrc`, whose presence selects this layout), plus an optional audio VAE (via `audioVaeModelSrc`) for the synchronized 48 kHz audio track. Its img2vid path needs no CLIP-vision encoder.
* **MiniMax-H3** (txt2vid and img2vid): split layout — diffusion model + Qwen3-VL text encoder (via `llmModelSrc`) + video VAE (via `vaeModelSrc`), plus an optional audio VAE (via `audioVaeModelSrc`) for synchronized 32 kHz audio. H3 uses a 32-pixel spatial grid and `17*k + 5` frames at 24 FPS. Its img2vid path conditions through the video VAE and needs no CLIP-vision encoder; Wan's T5 encoder and CLIP companions are unsupported.

<Callout type="warn">
  LTX-2 is large (\~21B) — budget at least **20 GB** of video / unified memory.
</Callout>

For models available as constants, see [SDK — Models](/sdk/v0.23/#models).

## Examples

### Text-to-video (WAN 2.1)

The following script shows text-to-video generation using Wan 2.1 T2V 1.3B with its split-layout model (separate diffusion model, UMT5-XXL text encoder, and VAE):

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-txt2vid.js title="diffusion-txt2vid.js" lineNumbers
      import { loadModel, unloadModel, video, WAN2_1_T2V_1_3B_FP16, UMT5_XXL_FP16, WAN_2_1_COMFYUI_REPACKAGED_VAE } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Text-to-video with Wan 2.1 T2V 1.3B. Wan uses a split layout:
      // a diffusion model + a UMT5-XXL text encoder + a VAE.
      // This example needs powerful hardware: at least 16 GB of video memory or
      // 20 GB of unified memory.
      const diffusionModelSrc = process.argv[2] || WAN2_1_T2V_1_3B_FP16;
      const t5XxlModelSrc = process.argv[3] || UMT5_XXL_FP16;
      const vaeModelSrc = process.argv[4] || WAN_2_1_COMFYUI_REPACKAGED_VAE;
      // Prompt tip: Wan 1.3B is small and has weak temporal priors. Use motion-
      // explicit verbs and avoid static framing words like "standing", "still",
      // or "portrait" in the positive prompt.
      const prompt = process.argv[5] || 'a colorful bird flapping its wings';
      const outputDir = process.argv[6] || '.';
      try {
          console.log('▸ Loading Wan 2.1 T2V model (diffusion + UMT5-XXL + VAE)...');
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  t5XxlModelSrc,
                  vaeModelSrc,
                  diffusion_fa: true,
                  offload_to_cpu: true,
                  params_backend: 'vae=cpu',
                  vae_tiling: true
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log(`\n▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'txt2vid',
              prompt,
              negative_prompt: 'blurry, low quality, static, jittery, watermark',
              width: 480,
              height: 832,
              // Frame count must satisfy (4*k + 1), k >= 1. Common values at 16 fps:
              // 17 frames ~= 1.06s (very fast, ~6 min on M3 Ultra Metal)
              // 33 frames ~= 2.06s (default in this example, ~11 min)
              // 49 frames ~= 3.06s (~17 min)
              // 65 frames ~= 4.06s (~22 min)
              // 81 frames ~= 5.06s (Wan 1.3B native training length, best motion
              // quality, ~28 min)
              // Going beyond 81 can degrade quality because it exceeds the model's
              // positional embeddings.
              video_frames: 33,
              fps: 16,
              steps: 30,
              cfg_scale: 6.0,
              // Wan 2.1 T2V needs flow_shift=3.0 for visible motion. Higher values can
              // make consecutive frames near-identical, which looks like a frozen video.
              flow_shift: 3.0,
              seed: 42,
              vae_tiling: true
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `wan_t2v_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('\n▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          console.log('▸ Done.');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-txt2vid.ts title="diffusion-txt2vid.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        video,
        WAN2_1_T2V_1_3B_FP16,
        UMT5_XXL_FP16,
        WAN_2_1_COMFYUI_REPACKAGED_VAE
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Text-to-video with Wan 2.1 T2V 1.3B. Wan uses a split layout:
      // a diffusion model + a UMT5-XXL text encoder + a VAE.
      // This example needs powerful hardware: at least 16 GB of video memory or
      // 20 GB of unified memory.
      const diffusionModelSrc = process.argv[2] || WAN2_1_T2V_1_3B_FP16
      const t5XxlModelSrc = process.argv[3] || UMT5_XXL_FP16
      const vaeModelSrc = process.argv[4] || WAN_2_1_COMFYUI_REPACKAGED_VAE

      // Prompt tip: Wan 1.3B is small and has weak temporal priors. Use motion-
      // explicit verbs and avoid static framing words like "standing", "still",
      // or "portrait" in the positive prompt.
      const prompt = process.argv[5] || 'a colorful bird flapping its wings'
      const outputDir = process.argv[6] || '.'

      try {
        console.log('▸ Loading Wan 2.1 T2V model (diffusion + UMT5-XXL + VAE)...')
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            t5XxlModelSrc,
            vaeModelSrc,
            diffusion_fa: true,
            offload_to_cpu: true,
            params_backend: 'vae=cpu',
            vae_tiling: true
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        console.log(`\n▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'txt2vid',
          prompt,
          negative_prompt: 'blurry, low quality, static, jittery, watermark',
          width: 480,
          height: 832,
          // Frame count must satisfy (4*k + 1), k >= 1. Common values at 16 fps:
          // 17 frames ~= 1.06s (very fast, ~6 min on M3 Ultra Metal)
          // 33 frames ~= 2.06s (default in this example, ~11 min)
          // 49 frames ~= 3.06s (~17 min)
          // 65 frames ~= 4.06s (~22 min)
          // 81 frames ~= 5.06s (Wan 1.3B native training length, best motion
          // quality, ~28 min)
          // Going beyond 81 can degrade quality because it exceeds the model's
          // positional embeddings.
          video_frames: 33,
          fps: 16,
          steps: 30,
          cfg_scale: 6.0,
          // Wan 2.1 T2V needs flow_shift=3.0 for visible motion. Higher values can
          // make consecutive frames near-identical, which looks like a frozen video.
          flow_shift: 3.0,
          seed: 42,
          vae_tiling: true
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `wan_t2v_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

        console.log('\n▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        console.log('▸ Done.')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_txt2vid.py title="diffusion_txt2vid.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-txt2vid.ts.

      Text-to-video with Wan 2.1 T2V 1.3B, which uses a split layout: the diffusion
      model, a UMT5-XXL text encoder and a VAE are three separate files handed to one
      `load_model` call.

      This example needs powerful hardware: at least 16 GB of video memory or 20 GB
      of unified memory.

      TypeScript's `video()` hands back three channels -- `progressStream`, `outputs`
      and `stats`. Python exposes one async iterator instead, and each `video_stream`
      response carries whichever of those three it is: `step` with `total_steps`
      while denoising, base64 `data` for a finished clip, and `done` with `stats` at
      the end. The loop below therefore demultiplexes what TypeScript receives
      pre-split, the same way `diffusion_flux2_klein.py` does for images.

      RUN: python examples/diffusion_txt2vid.py [diffusion-src] [t5-src] [vae-src] [prompt] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          UMT5_XXL_FP16,
          WAN2_1_T2V_1_3B_FP16,
          WAN_2_1_COMFYUI_REPACKAGED_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          # Wan 2.1 uses a split layout: diffusion model + UMT5-XXL text encoder + VAE
          diffusion_model_src = sys.argv[1] if len(sys.argv) > 1 else WAN2_1_T2V_1_3B_FP16
          t5_xxl_model_src = sys.argv[2] if len(sys.argv) > 2 else UMT5_XXL_FP16
          vae_model_src = sys.argv[3] if len(sys.argv) > 3 else WAN_2_1_COMFYUI_REPACKAGED_VAE
          # Prompt tip: Wan 1.3B is small and has weak temporal priors. Use motion-
          # explicit verbs and avoid static framing words like "standing", "still",
          # or "portrait" in the positive prompt.
          prompt = sys.argv[4] if len(sys.argv) > 4 else "a colorful bird flapping its wings"
          output_dir = Path(sys.argv[5]) if len(sys.argv) > 5 else Path(".")

          print("▸ Loading Wan 2.1 T2V model (diffusion + UMT5-XXL + VAE)...")

          async with Client() as client:
              t = client.transport

              model_id = await load_model(
                  t,
                  model_src=diffusion_model_src,
                  model_type="sdcpp-generation",
                  model_config={
                      "mode": "video",
                      "device": "gpu",
                      "threads": 4,
                      "t5XxlModelSrc": t5_xxl_model_src,
                      "vaeModelSrc": vae_model_src,
                      "diffusion_fa": True,
                      "offload_to_cpu": True,
                      "params_backend": "vae=cpu",
                      "vae_tiling": True,
                  },
                  on_progress=print_progress,
              )
              print(f"▸ Model loaded: {model_id}")

              print(f'\n▸ Generating video for: "{prompt}"')

              request = VideoStreamRequest.model_validate(
                  {
                      "type": "videoStream",
                      "modelId": model_id,
                      "mode": "txt2vid",
                      "prompt": prompt,
                      "negative_prompt": "blurry, low quality, static, jittery, watermark",
                      "width": 480,
                      "height": 832,
                      # Frame count must satisfy (4*k + 1), k >= 1. Common values at
                      # 16 fps:
                      # 17 frames ~= 1.06s (very fast, ~6 min on M3 Ultra Metal)
                      # 33 frames ~= 2.06s (default in this example, ~11 min)
                      # 49 frames ~= 3.06s (~17 min)
                      # 65 frames ~= 4.06s (~22 min)
                      # 81 frames ~= 5.06s (Wan 1.3B native training length, best
                      # motion quality, ~28 min)
                      # Going beyond 81 can degrade quality because it exceeds the
                      # model's positional embeddings.
                      "video_frames": 33,
                      "fps": 16,
                      "steps": 30,
                      "cfg_scale": 6.0,
                      # Wan 2.1 T2V needs flow_shift=3.0 for visible motion. Higher
                      # values can make consecutive frames near-identical, which
                      # looks like a frozen video.
                      "flow_shift": 3.0,
                      "seed": 42,
                      "vae_tiling": True,
                  }
              )

              clips: list[bytes] = []
              stats = None
              async for response in video_stream(t, request):
                  if response.step is not None and response.total_steps is not None:
                      print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                  if response.data is not None:
                      clips.append(base64.b64decode(response.data))
                  if response.done:
                      stats = response.stats

              for index, clip in enumerate(clips):
                  output_path = output_dir / f"wan_t2v_{index}.avi"
                  output_path.write_bytes(clip)
                  print(f"▸ Saved {output_path}")

              print("\n▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

              await unload_model(t, model_id)

          print("▸ Done")
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionTxt2vid.kt title="DiffusionTxt2vid.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-txt2vid.ts.
      //
      // Text-to-video with Wan 2.1 T2V 1.3B, which uses a split layout: the diffusion
      // model, a UMT5-XXL text encoder and a VAE are three separate files handed to
      // one load call through `modelConfig`.
      //
      // This example needs powerful hardware: at least 16 GB of video memory or 20 GB
      // of unified memory.
      //
      // `client.media.video()` returns a `QvacMediaRun`, the same split TypeScript
      // gets: `events` is a `Flow` of typed `VideoStreamResponse` frames (per-step
      // progress), and `final` is a `Deferred` with every base64 clip plus the
      // closing stats. The typed `VideoStreamRequest` carries the fields the
      // convenience overload lacks (negative prompt, fps, flow shift...), and `mode`
      // is the generated `VideoStreamRequestMode` enum.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionTxt2vid --args="[diffusion-src] [t5-src] [vae-src] [prompt] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          // Wan 2.1 uses a split layout: diffusion model + UMT5-XXL text encoder + VAE
          val diffusionModelSrc = args.getOrNull(0) ?: Models.WAN2_1_T2V_1_3B_FP16.src
          val t5XxlModelSrc = args.getOrNull(1) ?: Models.UMT5_XXL_FP16.src
          val vaeModelSrc = args.getOrNull(2) ?: Models.WAN_2_1_COMFYUI_REPACKAGED_VAE.src
          // Prompt tip: Wan 1.3B is small and has weak temporal priors. Use motion-
          // explicit verbs and avoid static framing words like "standing", "still",
          // or "portrait" in the positive prompt.
          val prompt = args.getOrNull(3) ?: "a colorful bird flapping its wings"
          val outputDir = Path.of(args.getOrNull(4) ?: ".")

          println("▸ Loading Wan 2.1 T2V model (diffusion + UMT5-XXL + VAE)...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      put("t5XxlModelSrc", t5XxlModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("diffusion_fa", true)
                      put("offload_to_cpu", true)
                      put("params_backend", "vae=cpu")
                      put("vae_tiling", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              println("\n▸ Generating video for: \"$prompt\"")

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.TXT2VID,
                      prompt = prompt,
                      negative_prompt = "blurry, low quality, static, jittery, watermark",
                      width = 480,
                      height = 832,
                      // Frame count must satisfy (4*k + 1), k >= 1. Common values at
                      // 16 fps:
                      // 17 frames ~= 1.06s (very fast, ~6 min on M3 Ultra Metal)
                      // 33 frames ~= 2.06s (default in this example, ~11 min)
                      // 49 frames ~= 3.06s (~17 min)
                      // 65 frames ~= 4.06s (~22 min)
                      // 81 frames ~= 5.06s (Wan 1.3B native training length, best
                      // motion quality, ~28 min)
                      // Going beyond 81 can degrade quality because it exceeds the
                      // model's positional embeddings.
                      video_frames = 33,
                      fps = 16.0,
                      steps = 30,
                      cfg_scale = 6.0,
                      // Wan 2.1 T2V needs flow_shift=3.0 for visible motion. Higher
                      // values can make consecutive frames near-identical, which
                      // looks like a frozen video.
                      flow_shift = 3.0,
                      seed = 42,
                      vae_tiling = true,
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("wan_t2v_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath")
              }

              println("\n▸ Stats: ${result.stats}")

              client.models.unload(modelId)
          } finally {
              client.close()
          }

          println("▸ Done")
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Image-to-video (WAN 2.1)

The following script shows image-to-video generation using Wan 2.1 I2V with its split-layout model (separate diffusion model, UMT5-XXL text encoder, VAE, and CLIP vision encoder). It animates a first-frame `init_image` guided by a motion prompt:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-img2vid.js title="diffusion-img2vid.js" lineNumbers
      import { loadModel, unloadModel, video, WAN2_1_I2V_14B_Q4_K_M, CLIP_VISION_H, UMT5_XXL_FP16, WAN_2_1_COMFYUI_REPACKAGED_VAE } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Image-to-video with Wan 2.1 I2V. Requires a Wan I2V diffusion checkpoint (GGUF
      // recommended), plus UMT5-XXL, Wan VAE, and CLIP vision weights. The model
      // sources default to the bundled registry constants, so the common case is just
      // an init image path.
      const initImagePath = process.argv[2];
      const prompt = process.argv[3] || 'the subject slowly turns and smiles, soft natural lighting, cinematic';
      const outputDir = process.argv[4] || '.';
      const diffusionModelSrc = process.argv[5] || WAN2_1_I2V_14B_Q4_K_M;
      const t5XxlModelSrc = process.argv[6] || UMT5_XXL_FP16;
      const vaeModelSrc = process.argv[7] || WAN_2_1_COMFYUI_REPACKAGED_VAE;
      const clipVisionModelSrc = process.argv[8] || CLIP_VISION_H;
      if (!initImagePath) {
          console.error('✖ init image path is required');
          console.error('Usage: node dist/examples/diffusion-img2vid.js ' +
              '<initImagePath> [prompt] [outputDir] ' +
              '[i2vModelSrc] [t5XxlModelSrc] [vaeModelSrc] [clipVisionModelSrc]');
          process.exit(1);
      }
      try {
          console.log('▸ Loading Wan 2.1 I2V model (diffusion + UMT5-XXL + VAE + CLIP vision)...');
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  t5XxlModelSrc,
                  vaeModelSrc,
                  clipVisionModelSrc,
                  diffusion_fa: true,
                  offload_to_cpu: true,
                  params_backend: 'vae=cpu',
                  vae_tiling: true
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          const init_image = new Uint8Array(fs.readFileSync(initImagePath));
          console.log(`▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'img2vid',
              prompt,
              init_image,
              negative_prompt: 'blurry, distorted, low quality, jittery, static, frozen',
              strength: 0.85,
              flow_shift: 3.0,
              video_frames: 33,
              fps: 16,
              steps: 30,
              cfg_scale: 6.0,
              seed: 42,
              vae_tiling: true
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `wan_i2v_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          console.log('▸ Done');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-img2vid.ts title="diffusion-img2vid.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        video,
        WAN2_1_I2V_14B_Q4_K_M,
        CLIP_VISION_H,
        UMT5_XXL_FP16,
        WAN_2_1_COMFYUI_REPACKAGED_VAE
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Image-to-video with Wan 2.1 I2V. Requires a Wan I2V diffusion checkpoint (GGUF
      // recommended), plus UMT5-XXL, Wan VAE, and CLIP vision weights. The model
      // sources default to the bundled registry constants, so the common case is just
      // an init image path.
      const initImagePath = process.argv[2]
      const prompt =
        process.argv[3] || 'the subject slowly turns and smiles, soft natural lighting, cinematic'
      const outputDir = process.argv[4] || '.'
      const diffusionModelSrc = process.argv[5] || WAN2_1_I2V_14B_Q4_K_M
      const t5XxlModelSrc = process.argv[6] || UMT5_XXL_FP16
      const vaeModelSrc = process.argv[7] || WAN_2_1_COMFYUI_REPACKAGED_VAE
      const clipVisionModelSrc = process.argv[8] || CLIP_VISION_H

      if (!initImagePath) {
        console.error('✖ init image path is required')
        console.error(
          'Usage: node dist/examples/diffusion-img2vid.js ' +
            '<initImagePath> [prompt] [outputDir] ' +
            '[i2vModelSrc] [t5XxlModelSrc] [vaeModelSrc] [clipVisionModelSrc]'
        )
        process.exit(1)
      }

      try {
        console.log('▸ Loading Wan 2.1 I2V model (diffusion + UMT5-XXL + VAE + CLIP vision)...')
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            t5XxlModelSrc,
            vaeModelSrc,
            clipVisionModelSrc,
            diffusion_fa: true,
            offload_to_cpu: true,
            params_backend: 'vae=cpu',
            vae_tiling: true
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        const init_image = new Uint8Array(fs.readFileSync(initImagePath))
        console.log(`▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'img2vid',
          prompt,
          init_image,
          negative_prompt: 'blurry, distorted, low quality, jittery, static, frozen',
          strength: 0.85,
          flow_shift: 3.0,
          video_frames: 33,
          fps: 16,
          steps: 30,
          cfg_scale: 6.0,
          seed: 42,
          vae_tiling: true
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `wan_i2v_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

        console.log('▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        console.log('▸ Done')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_img2vid.py title="diffusion_img2vid.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-img2vid.ts.

      Image-to-video with Wan 2.1 I2V: a first-frame `init_image` animated by a
      motion prompt. The model uses a split layout of four files -- the I2V diffusion
      checkpoint plus UMT5-XXL, the Wan VAE and CLIP vision weights -- all handed to
      one `load_model` call. The sources default to the registry constants, so the
      common case is just an init image path.

      TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes them
      on the way to the worker. Python calls the worker directly through
      `video_stream`, where `init_image` is already the encoded string, so the
      example encodes the file itself. The same iterator then carries progress, the
      finished clips and the closing stats, which TypeScript receives as three
      separate channels.

      RUN: python examples/diffusion_img2vid.py <init-image> [prompt] [output-dir] [i2v-src] [t5-src] [vae-src] [clip-vision-src]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          CLIP_VISION_H,
          UMT5_XXL_FP16,
          WAN2_1_I2V_14B_Q4_K_M,
          WAN_2_1_COMFYUI_REPACKAGED_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          init_image_path = sys.argv[1] if len(sys.argv) > 1 else None
          prompt = (
              sys.argv[2]
              if len(sys.argv) > 2
              else "the subject slowly turns and smiles, soft natural lighting, cinematic"
          )
          output_dir = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(".")
          diffusion_model_src = sys.argv[4] if len(sys.argv) > 4 else WAN2_1_I2V_14B_Q4_K_M
          t5_xxl_model_src = sys.argv[5] if len(sys.argv) > 5 else UMT5_XXL_FP16
          vae_model_src = sys.argv[6] if len(sys.argv) > 6 else WAN_2_1_COMFYUI_REPACKAGED_VAE
          clip_vision_model_src = sys.argv[7] if len(sys.argv) > 7 else CLIP_VISION_H

          if not init_image_path:
              print("✖ init image path is required", file=sys.stderr)
              print(
                  "Usage: python examples/diffusion_img2vid.py <initImagePath> "
                  "[prompt] [outputDir] [i2vModelSrc] [t5XxlModelSrc] [vaeModelSrc] "
                  "[clipVisionModelSrc]",
                  file=sys.stderr,
              )
              return 1

          print("▸ Loading Wan 2.1 I2V model (diffusion + UMT5-XXL + VAE + CLIP vision)...")

          try:
              async with Client() as client:
                  t = client.transport

                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "mode": "video",
                          "device": "gpu",
                          "threads": 4,
                          "t5XxlModelSrc": t5_xxl_model_src,
                          "vaeModelSrc": vae_model_src,
                          "clipVisionModelSrc": clip_vision_model_src,
                          "diffusion_fa": True,
                          "offload_to_cpu": True,
                          "params_backend": "vae=cpu",
                          "vae_tiling": True,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  init_image = base64.b64encode(Path(init_image_path).read_bytes()).decode(
                      "ascii"
                  )
                  print(f'▸ Generating video for: "{prompt}"')

                  request = VideoStreamRequest.model_validate(
                      {
                          "type": "videoStream",
                          "modelId": model_id,
                          "mode": "img2vid",
                          "prompt": prompt,
                          "init_image": init_image,
                          "negative_prompt": (
                              "blurry, distorted, low quality, jittery, static, frozen"
                          ),
                          "strength": 0.85,
                          "flow_shift": 3.0,
                          "video_frames": 33,
                          "fps": 16,
                          "steps": 30,
                          "cfg_scale": 6.0,
                          "seed": 42,
                          "vae_tiling": True,
                      }
                  )

                  clips: list[bytes] = []
                  stats = None
                  async for response in video_stream(t, request):
                      if response.step is not None and response.total_steps is not None:
                          print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                      if response.data is not None:
                          clips.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, clip in enumerate(clips):
                      output_path = output_dir / f"wan_i2v_{index}.avi"
                      output_path.write_bytes(clip)
                      print(f"▸ Saved {output_path}")

                  print("▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

                  await unload_model(t, model_id)
                  print("▸ Done")
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionImg2vid.kt title="DiffusionImg2vid.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-img2vid.ts.
      //
      // Image-to-video with Wan 2.1 I2V: a first-frame `init_image` animated by a
      // motion prompt. The model uses a split layout of four files -- the I2V
      // diffusion checkpoint plus UMT5-XXL, the Wan VAE and CLIP vision weights --
      // all handed to one load call through `modelConfig`. The sources default to
      // the registry constants, so the common case is just an init image path.
      //
      // TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes
      // them on the way to the worker. The typed `VideoStreamRequest` carries the
      // encoded string, so the example encodes the file with `java.util.Base64`. The
      // returned `QvacMediaRun` splits progress (`events` Flow) from the clips and
      // stats (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionImg2vid --args="<init-image> [prompt] [output-dir] [i2v-src] [t5-src] [vae-src] [clip-vision-src]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val initImagePath = args.getOrNull(0)
          val prompt = args.getOrNull(1) ?: "the subject slowly turns and smiles, soft natural lighting, cinematic"
          val outputDir = Path.of(args.getOrNull(2) ?: ".")
          val diffusionModelSrc = args.getOrNull(3) ?: Models.WAN2_1_I2V_14B_Q4_K_M.src
          val t5XxlModelSrc = args.getOrNull(4) ?: Models.UMT5_XXL_FP16.src
          val vaeModelSrc = args.getOrNull(5) ?: Models.WAN_2_1_COMFYUI_REPACKAGED_VAE.src
          val clipVisionModelSrc = args.getOrNull(6) ?: Models.CLIP_VISION_H.src

          if (initImagePath.isNullOrEmpty()) {
              System.err.println("✖ init image path is required")
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionImg2vid --args=\"<initImagePath> " +
                      "[prompt] [outputDir] [i2vModelSrc] [t5XxlModelSrc] [vaeModelSrc] [clipVisionModelSrc]\"",
              )
              exitProcess(1)
          }

          println("▸ Loading Wan 2.1 I2V model (diffusion + UMT5-XXL + VAE + CLIP vision)...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      put("t5XxlModelSrc", t5XxlModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("clipVisionModelSrc", clipVisionModelSrc)
                      put("diffusion_fa", true)
                      put("offload_to_cpu", true)
                      put("params_backend", "vae=cpu")
                      put("vae_tiling", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              val initImage = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(initImagePath)))
              println("▸ Generating video for: \"$prompt\"")

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.IMG2VID,
                      prompt = prompt,
                      init_image = initImage,
                      negative_prompt = "blurry, distorted, low quality, jittery, static, frozen",
                      strength = 0.85,
                      flow_shift = 3.0,
                      video_frames = 33,
                      fps = 16.0,
                      steps = 30,
                      cfg_scale = 6.0,
                      seed = 42,
                      vae_tiling = true,
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("wan_i2v_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath")
              }

              println("▸ Stats: ${result.stats}")

              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Text-to-video (Wan 2.2 TI2V-5B)

The following script shows text-to-video generation with Wan 2.2 TI2V-5B Turbo (single-expert). It loads the same split layout as Wan 2.1 T2V — diffusion model + UMT5-XXL text encoder + VAE — but with the Wan 2.2 VAE, whose 16× spatial compression enforces the TI2V 32-pixel grid. `high_noise_*` and `moe_boundary` are A14B-only and therefore omitted here:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-txt2vid-wan22.js title="diffusion-txt2vid-wan22.js" lineNumbers
      import { loadModel, unloadModel, video, WAN2_2_TI2V_5B_Q5_K_S, UMT5_XXL_FP16, WAN_2_2_COMFYUI_REPACKAGED_VAE } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Text-to-video with Wan 2.2 TI2V-5B Turbo (Q5_K_S). Like Wan 2.1 this is a
      // split layout — diffusion model + UMT5-XXL text encoder + VAE — but it needs
      // the Wan 2.2 VAE specifically: its 16x spatial compression is what gives
      // TI2V its 32-pixel grid, and the Wan 2.1 VAE is not interchangeable.
      //
      // TI2V-5B is a single-expert model. The high_noise_* / moe_boundary fields
      // belong to the two-expert Wan 2.2 A14B layout and are rejected here.
      //
      // Budget at least 16 GB of video memory or 20 GB of unified memory. The
      // artifacts total roughly 16.4 GB, dominated by the fp16 text encoder.
      //
      // The text encoder is byte-identical to the Wan 2.1 repackage, so both
      // generations share the one UMT5_XXL_FP16 registry entry.
      const diffusionModelSrc = process.argv[2] || WAN2_2_TI2V_5B_Q5_K_S;
      const t5XxlModelSrc = process.argv[3] || UMT5_XXL_FP16;
      const vaeModelSrc = process.argv[4] || WAN_2_2_COMFYUI_REPACKAGED_VAE;
      // Prompt tip: Turbo responds well to explicit camera and lighting direction.
      // Describe continuous motion rather than a pose, or the clip reads as a still.
      const prompt = process.argv[5] ||
          'A single white porcelain espresso cup on a dark walnut table beside a sunlit window, ' +
              'delicate steam curling upward, slow circular camera move, warm morning light, ' +
              'sharp ceramic texture, realistic continuous motion';
      const outputDir = process.argv[6] || '.';
      try {
          console.log('▸ Loading Wan 2.2 TI2V-5B Turbo model (diffusion + UMT5-XXL + Wan 2.2 VAE)...');
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  t5XxlModelSrc,
                  vaeModelSrc,
                  diffusion_fa: true,
                  offload_to_cpu: true,
                  vae_tiling: true
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log(`\n▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'txt2vid',
              prompt,
              negative_prompt: 'flickering, temporal jitter, morphing, duplicated subject, warped geometry, ' +
                  'distorted anatomy, blurry details, low resolution, text, watermark, logo',
              // TI2V-5B requires width and height to be multiples of 32 — stricter than
              // the multiple of 16 the schema enforces for Wan generally. Native
              // validation derives this from the loaded GGUF, so a non-conforming size
              // fails at generation time rather than at load.
              // Turbo was trained on this 720p, 24 fps, five-second shape; 640x352 with
              // 49 frames is a much cheaper way to smoke-test the pipeline.
              width: 1280,
              height: 704,
              // Frame count must satisfy (4*k + 1), k >= 1. At 24 fps: 49 ≈ 2s,
              // 121 ≈ 5s (the trained length).
              video_frames: 121,
              fps: 24,
              // Turbo is distilled for very short schedules: 4 steps with guidance
              // effectively disabled. The non-distilled TI2V-5B wants steps >= 30 and
              // cfg ~5.0 instead.
              steps: 4,
              cfg_scale: 1.0,
              flow_shift: 5.0,
              seed: 42,
              vae_tiling: true
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `wan22_ti2v_t2v_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('\n▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          console.log('▸ Done.');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-txt2vid-wan22.ts title="diffusion-txt2vid-wan22.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        video,
        WAN2_2_TI2V_5B_Q5_K_S,
        UMT5_XXL_FP16,
        WAN_2_2_COMFYUI_REPACKAGED_VAE
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Text-to-video with Wan 2.2 TI2V-5B Turbo (Q5_K_S). Like Wan 2.1 this is a
      // split layout — diffusion model + UMT5-XXL text encoder + VAE — but it needs
      // the Wan 2.2 VAE specifically: its 16x spatial compression is what gives
      // TI2V its 32-pixel grid, and the Wan 2.1 VAE is not interchangeable.
      //
      // TI2V-5B is a single-expert model. The high_noise_* / moe_boundary fields
      // belong to the two-expert Wan 2.2 A14B layout and are rejected here.
      //
      // Budget at least 16 GB of video memory or 20 GB of unified memory. The
      // artifacts total roughly 16.4 GB, dominated by the fp16 text encoder.
      //
      // The text encoder is byte-identical to the Wan 2.1 repackage, so both
      // generations share the one UMT5_XXL_FP16 registry entry.
      const diffusionModelSrc = process.argv[2] || WAN2_2_TI2V_5B_Q5_K_S
      const t5XxlModelSrc = process.argv[3] || UMT5_XXL_FP16
      const vaeModelSrc = process.argv[4] || WAN_2_2_COMFYUI_REPACKAGED_VAE

      // Prompt tip: Turbo responds well to explicit camera and lighting direction.
      // Describe continuous motion rather than a pose, or the clip reads as a still.
      const prompt =
        process.argv[5] ||
        'A single white porcelain espresso cup on a dark walnut table beside a sunlit window, ' +
          'delicate steam curling upward, slow circular camera move, warm morning light, ' +
          'sharp ceramic texture, realistic continuous motion'
      const outputDir = process.argv[6] || '.'

      try {
        console.log('▸ Loading Wan 2.2 TI2V-5B Turbo model (diffusion + UMT5-XXL + Wan 2.2 VAE)...')
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            t5XxlModelSrc,
            vaeModelSrc,
            diffusion_fa: true,
            offload_to_cpu: true,
            vae_tiling: true
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        console.log(`\n▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'txt2vid',
          prompt,
          negative_prompt:
            'flickering, temporal jitter, morphing, duplicated subject, warped geometry, ' +
            'distorted anatomy, blurry details, low resolution, text, watermark, logo',
          // TI2V-5B requires width and height to be multiples of 32 — stricter than
          // the multiple of 16 the schema enforces for Wan generally. Native
          // validation derives this from the loaded GGUF, so a non-conforming size
          // fails at generation time rather than at load.
          // Turbo was trained on this 720p, 24 fps, five-second shape; 640x352 with
          // 49 frames is a much cheaper way to smoke-test the pipeline.
          width: 1280,
          height: 704,
          // Frame count must satisfy (4*k + 1), k >= 1. At 24 fps: 49 ≈ 2s,
          // 121 ≈ 5s (the trained length).
          video_frames: 121,
          fps: 24,
          // Turbo is distilled for very short schedules: 4 steps with guidance
          // effectively disabled. The non-distilled TI2V-5B wants steps >= 30 and
          // cfg ~5.0 instead.
          steps: 4,
          cfg_scale: 1.0,
          flow_shift: 5.0,
          seed: 42,
          vae_tiling: true
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `wan22_ti2v_t2v_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

        console.log('\n▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        console.log('▸ Done.')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_txt2vid_wan22.py title="diffusion_txt2vid_wan22.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-txt2vid-wan22.ts.

      Text-to-video with Wan 2.2 TI2V-5B Turbo (Q5_K_S). Like Wan 2.1 this is a
      split layout -- diffusion model + UMT5-XXL text encoder + VAE -- but it needs
      the Wan 2.2 VAE specifically: its 16x spatial compression is what gives TI2V
      its 32-pixel grid, and the Wan 2.1 VAE is not interchangeable.

      TI2V-5B is a single-expert model. The high_noise_* / moe_boundary fields
      belong to the two-expert Wan 2.2 A14B layout and are rejected here.

      Budget at least 16 GB of video memory or 20 GB of unified memory. The
      artifacts total roughly 16.4 GB, dominated by the fp16 text encoder.

      The text encoder is byte-identical to the Wan 2.1 repackage, so both
      generations share the one UMT5_XXL_FP16 registry entry.

      TypeScript's `video()` hands back three channels -- `progressStream`, `outputs`
      and `stats`. Python exposes one async iterator instead, and each `video_stream`
      response carries whichever of those three it is: `step` with `total_steps`
      while denoising, base64 `data` for a finished clip, and `done` with `stats` at
      the end.

      RUN: python examples/diffusion_txt2vid_wan22.py [diffusion-src] [t5-src] [vae-src] [prompt] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          UMT5_XXL_FP16,
          WAN2_2_TI2V_5B_Q5_K_S,
          WAN_2_2_COMFYUI_REPACKAGED_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          diffusion_model_src = sys.argv[1] if len(sys.argv) > 1 else WAN2_2_TI2V_5B_Q5_K_S
          t5_xxl_model_src = sys.argv[2] if len(sys.argv) > 2 else UMT5_XXL_FP16
          vae_model_src = sys.argv[3] if len(sys.argv) > 3 else WAN_2_2_COMFYUI_REPACKAGED_VAE
          # Prompt tip: Turbo responds well to explicit camera and lighting direction.
          # Describe continuous motion rather than a pose, or the clip reads as a
          # still.
          prompt = (
              sys.argv[4]
              if len(sys.argv) > 4
              else (
                  "A single white porcelain espresso cup on a dark walnut table beside "
                  "a sunlit window, delicate steam curling upward, slow circular camera "
                  "move, warm morning light, sharp ceramic texture, realistic continuous "
                  "motion"
              )
          )
          output_dir = Path(sys.argv[5]) if len(sys.argv) > 5 else Path(".")

          print(
              "▸ Loading Wan 2.2 TI2V-5B Turbo model "
              "(diffusion + UMT5-XXL + Wan 2.2 VAE)..."
          )

          try:
              async with Client() as client:
                  t = client.transport

                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "mode": "video",
                          "device": "gpu",
                          "threads": 4,
                          "t5XxlModelSrc": t5_xxl_model_src,
                          "vaeModelSrc": vae_model_src,
                          "diffusion_fa": True,
                          "offload_to_cpu": True,
                          "vae_tiling": True,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print(f'\n▸ Generating video for: "{prompt}"')

                  request = VideoStreamRequest.model_validate(
                      {
                          "type": "videoStream",
                          "modelId": model_id,
                          "mode": "txt2vid",
                          "prompt": prompt,
                          "negative_prompt": (
                              "flickering, temporal jitter, morphing, duplicated subject, "
                              "warped geometry, distorted anatomy, blurry details, low "
                              "resolution, text, watermark, logo"
                          ),
                          # TI2V-5B requires width and height to be multiples of 32 --
                          # stricter than the multiple of 16 the schema enforces for Wan
                          # generally. Native validation derives this from the loaded
                          # GGUF, so a non-conforming size fails at generation time
                          # rather than at load.
                          # Turbo was trained on this 720p, 24 fps, five-second shape;
                          # 640x352 with 49 frames is a much cheaper way to smoke-test
                          # the pipeline.
                          "width": 1280,
                          "height": 704,
                          # Frame count must satisfy (4*k + 1), k >= 1. At 24 fps:
                          # 49 ~= 2s, 121 ~= 5s (the trained length).
                          "video_frames": 121,
                          "fps": 24,
                          # Turbo is distilled for very short schedules: 4 steps with
                          # guidance effectively disabled. The non-distilled TI2V-5B
                          # wants steps >= 30 and cfg ~5.0 instead.
                          "steps": 4,
                          "cfg_scale": 1.0,
                          "flow_shift": 5.0,
                          "seed": 42,
                          "vae_tiling": True,
                      }
                  )

                  clips: list[bytes] = []
                  stats = None
                  async for response in video_stream(t, request):
                      if response.step is not None and response.total_steps is not None:
                          print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                      if response.data is not None:
                          clips.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, clip in enumerate(clips):
                      output_path = output_dir / f"wan22_ti2v_t2v_{index}.avi"
                      output_path.write_bytes(clip)
                      print(f"▸ Saved {output_path}")

                  print("\n▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

                  await unload_model(t, model_id)
                  print("▸ Done")
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionTxt2vidWan22.kt title="DiffusionTxt2vidWan22.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-txt2vid-wan22.ts.
      //
      // Text-to-video with Wan 2.2 TI2V-5B Turbo (Q5_K_S). Like Wan 2.1 this is a
      // split layout -- diffusion model + UMT5-XXL text encoder + VAE -- but it needs
      // the Wan 2.2 VAE specifically: its 16x spatial compression is what gives TI2V
      // its 32-pixel grid, and the Wan 2.1 VAE is not interchangeable.
      //
      // TI2V-5B is a single-expert model. The high_noise_* / moe_boundary fields
      // belong to the two-expert Wan 2.2 A14B layout and are rejected here.
      //
      // Budget at least 16 GB of video memory or 20 GB of unified memory. The
      // artifacts total roughly 16.4 GB, dominated by the fp16 text encoder.
      //
      // The text encoder is byte-identical to the Wan 2.1 repackage, so both
      // generations share the one UMT5_XXL_FP16 registry entry.
      //
      // `client.media.video()` returns a `QvacMediaRun`: progress arrives on the
      // `events` Flow, and the clips and stats on the `final` Deferred, as TypeScript
      // splits them.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionTxt2vidWan22 --args="[diffusion-src] [t5-src] [vae-src] [prompt] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val diffusionModelSrc = args.getOrNull(0) ?: Models.WAN2_2_TI2V_5B_Q5_K_S.src
          val t5XxlModelSrc = args.getOrNull(1) ?: Models.UMT5_XXL_FP16.src
          val vaeModelSrc = args.getOrNull(2) ?: Models.WAN_2_2_COMFYUI_REPACKAGED_VAE.src
          // Prompt tip: Turbo responds well to explicit camera and lighting direction.
          // Describe continuous motion rather than a pose, or the clip reads as a
          // still.
          val prompt = args.getOrNull(3)
              ?: ("A single white porcelain espresso cup on a dark walnut table beside " +
                  "a sunlit window, delicate steam curling upward, slow circular camera " +
                  "move, warm morning light, sharp ceramic texture, realistic continuous " +
                  "motion")
          val outputDir = Path.of(args.getOrNull(4) ?: ".")

          println("▸ Loading Wan 2.2 TI2V-5B Turbo model (diffusion + UMT5-XXL + Wan 2.2 VAE)...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      put("t5XxlModelSrc", t5XxlModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("diffusion_fa", true)
                      put("offload_to_cpu", true)
                      put("vae_tiling", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              println("\n▸ Generating video for: \"$prompt\"")

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.TXT2VID,
                      prompt = prompt,
                      negative_prompt = "flickering, temporal jitter, morphing, duplicated subject, " +
                          "warped geometry, distorted anatomy, blurry details, low " +
                          "resolution, text, watermark, logo",
                      // TI2V-5B requires width and height to be multiples of 32 --
                      // stricter than the multiple of 16 the schema enforces for Wan
                      // generally. Native validation derives this from the loaded
                      // GGUF, so a non-conforming size fails at generation time
                      // rather than at load.
                      // Turbo was trained on this 720p, 24 fps, five-second shape;
                      // 640x352 with 49 frames is a much cheaper way to smoke-test
                      // the pipeline.
                      width = 1280,
                      height = 704,
                      // Frame count must satisfy (4*k + 1), k >= 1. At 24 fps:
                      // 49 ~= 2s, 121 ~= 5s (the trained length).
                      video_frames = 121,
                      fps = 24.0,
                      // Turbo is distilled for very short schedules: 4 steps with
                      // guidance effectively disabled. The non-distilled TI2V-5B
                      // wants steps >= 30 and cfg ~5.0 instead.
                      steps = 4,
                      cfg_scale = 1.0,
                      flow_shift = 5.0,
                      seed = 42,
                      vae_tiling = true,
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("wan22_ti2v_t2v_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath")
              }

              println("\n▸ Stats: ${result.stats}")

              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Text-to-video with audio (LTX-2)

The following script loads LTX-2 with its split layout (diffusion model + Gemma text encoder + video VAE + embedding connectors + optional audio VAE) and generates a clip with a synchronized 48 kHz audio track. It uses the LTX-2 dimension/frame constraints (multiples of 32, `8*k + 1` frames) and enables `temporal_tiling` to cap peak VRAM:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-txt2vid-ltx.js title="diffusion-txt2vid-ltx.js" lineNumbers
      import { GEMMA_3_12B_Q4_K_XL, loadModel, LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS, LTX_2_3_22B_Q5_K_M, LTX_2_3_AUDIO_VAE, LTX_2_3_VIDEO_VAE, unloadModel, video } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Text-to-video (+ synchronized audio) with LTX-2. Unlike Wan, LTX-2 uses a
      // Gemma text encoder (llmModelSrc), a video VAE (vaeModelSrc), a set of
      // text-embedding connectors (embeddingsConnectorsModelSrc — this is what
      // selects the LTX-2 layout), and an optional audio VAE (audioVaeModelSrc)
      // that produces a 48 kHz audio track muxed into the output AVI.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via argv to override any of the five sources.
      const diffusionModelSrc = process.argv[2] || LTX_2_3_22B_Q5_K_M;
      const llmModelSrc = process.argv[3] || GEMMA_3_12B_Q4_K_XL;
      const vaeModelSrc = process.argv[4] || LTX_2_3_VIDEO_VAE;
      const audioVaeModelSrc = process.argv[5] || LTX_2_3_AUDIO_VAE;
      const embeddingsConnectorsModelSrc = process.argv[6] || LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS;
      const prompt = process.argv[7] || 'a claymation cat playing jazz on a piano';
      const outputDir = process.argv[8] || '.';
      try {
          console.log('▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...');
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  // Supplying embeddingsConnectorsModelSrc selects the LTX-2 layout.
                  llmModelSrc,
                  vaeModelSrc,
                  audioVaeModelSrc,
                  embeddingsConnectorsModelSrc,
                  diffusion_fa: true,
                  vae_tiling: true
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log(`\n▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'txt2vid',
              prompt,
              negative_prompt: 'blurry, low quality, static, jittery, watermark, distorted audio',
              // LTX-2 requires width/height as multiples of 32.
              width: 512,
              height: 320,
              // LTX-2 requires (8*k + 1) frames, max 257. At 24 fps: 25≈1s, 121≈5s, 241≈10s.
              video_frames: 121,
              fps: 24,
              // Distilled variants run in 4-8 steps with cfg ~1.0; the full --dev model
              // wants steps >= 20 and cfg ~7.0.
              steps: 10,
              cfg_scale: 1.0,
              seed: 42,
              // Tile the video VAE decode along the time axis to cap peak VRAM on long
              // / HD clips (LTX-2 only).
              temporal_tiling: true
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `ltx_t2v_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath} (play in VLC to hear the muxed audio track)`);
          }
          console.log('\n▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          console.log('▸ Done.');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-txt2vid-ltx.ts title="diffusion-txt2vid-ltx.ts" lineNumbers
      import {
        GEMMA_3_12B_Q4_K_XL,
        loadModel,
        LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
        LTX_2_3_22B_Q5_K_M,
        LTX_2_3_AUDIO_VAE,
        LTX_2_3_VIDEO_VAE,
        unloadModel,
        video
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Text-to-video (+ synchronized audio) with LTX-2. Unlike Wan, LTX-2 uses a
      // Gemma text encoder (llmModelSrc), a video VAE (vaeModelSrc), a set of
      // text-embedding connectors (embeddingsConnectorsModelSrc — this is what
      // selects the LTX-2 layout), and an optional audio VAE (audioVaeModelSrc)
      // that produces a 48 kHz audio track muxed into the output AVI.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via argv to override any of the five sources.
      const diffusionModelSrc = process.argv[2] || LTX_2_3_22B_Q5_K_M
      const llmModelSrc = process.argv[3] || GEMMA_3_12B_Q4_K_XL
      const vaeModelSrc = process.argv[4] || LTX_2_3_VIDEO_VAE
      const audioVaeModelSrc = process.argv[5] || LTX_2_3_AUDIO_VAE
      const embeddingsConnectorsModelSrc = process.argv[6] || LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS

      const prompt = process.argv[7] || 'a claymation cat playing jazz on a piano'
      const outputDir = process.argv[8] || '.'

      try {
        console.log('▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...')
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            // Supplying embeddingsConnectorsModelSrc selects the LTX-2 layout.
            llmModelSrc,
            vaeModelSrc,
            audioVaeModelSrc,
            embeddingsConnectorsModelSrc,
            diffusion_fa: true,
            vae_tiling: true
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        console.log(`\n▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'txt2vid',
          prompt,
          negative_prompt: 'blurry, low quality, static, jittery, watermark, distorted audio',
          // LTX-2 requires width/height as multiples of 32.
          width: 512,
          height: 320,
          // LTX-2 requires (8*k + 1) frames, max 257. At 24 fps: 25≈1s, 121≈5s, 241≈10s.
          video_frames: 121,
          fps: 24,
          // Distilled variants run in 4-8 steps with cfg ~1.0; the full --dev model
          // wants steps >= 20 and cfg ~7.0.
          steps: 10,
          cfg_scale: 1.0,
          seed: 42,
          // Tile the video VAE decode along the time axis to cap peak VRAM on long
          // / HD clips (LTX-2 only).
          temporal_tiling: true
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `ltx_t2v_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath} (play in VLC to hear the muxed audio track)`)
        }

        console.log('\n▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        console.log('▸ Done.')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_txt2vid_ltx.py title="diffusion_txt2vid_ltx.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-txt2vid-ltx.ts.

      Text-to-video (+ synchronized audio) with LTX-2. Unlike Wan, LTX-2 uses a
      Gemma text encoder (llmModelSrc), a video VAE (vaeModelSrc), a set of
      text-embedding connectors (embeddingsConnectorsModelSrc -- this is what selects
      the LTX-2 layout), and an optional audio VAE (audioVaeModelSrc) that produces a
      48 kHz audio track muxed into the output AVI.

      This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at least
      20+ GB of video / unified memory.

      Pass your own paths / URLs via argv to override any of the five sources.

      TypeScript's `video()` hands back three channels -- `progressStream`, `outputs`
      and `stats`. Python exposes one async iterator instead, and each `video_stream`
      response carries whichever of those three it is: `step` with `total_steps`
      while denoising, base64 `data` for a finished clip, and `done` with `stats` at
      the end.

      RUN: python examples/diffusion_txt2vid_ltx.py [diffusion-src] [llm-src] [vae-src] [audio-vae-src] [connectors-src] [prompt] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          GEMMA_3_12B_Q4_K_XL,
          LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
          LTX_2_3_22B_Q5_K_M,
          LTX_2_3_AUDIO_VAE,
          LTX_2_3_VIDEO_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          diffusion_model_src = sys.argv[1] if len(sys.argv) > 1 else LTX_2_3_22B_Q5_K_M
          llm_model_src = sys.argv[2] if len(sys.argv) > 2 else GEMMA_3_12B_Q4_K_XL
          vae_model_src = sys.argv[3] if len(sys.argv) > 3 else LTX_2_3_VIDEO_VAE
          audio_vae_model_src = sys.argv[4] if len(sys.argv) > 4 else LTX_2_3_AUDIO_VAE
          embeddings_connectors_model_src = (
              sys.argv[5]
              if len(sys.argv) > 5
              else LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS
          )

          prompt = (
              sys.argv[6] if len(sys.argv) > 6 else "a claymation cat playing jazz on a piano"
          )
          output_dir = Path(sys.argv[7]) if len(sys.argv) > 7 else Path(".")

          print(
              "▸ Loading LTX-2 model "
              "(diffusion + Gemma + video VAE + audio VAE + connectors)..."
          )

          try:
              async with Client() as client:
                  t = client.transport

                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "mode": "video",
                          "device": "gpu",
                          "threads": 4,
                          # Supplying embeddingsConnectorsModelSrc selects the LTX-2
                          # layout.
                          "llmModelSrc": llm_model_src,
                          "vaeModelSrc": vae_model_src,
                          "audioVaeModelSrc": audio_vae_model_src,
                          "embeddingsConnectorsModelSrc": embeddings_connectors_model_src,
                          "diffusion_fa": True,
                          "vae_tiling": True,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print(f'\n▸ Generating video for: "{prompt}"')

                  request = VideoStreamRequest.model_validate(
                      {
                          "type": "videoStream",
                          "modelId": model_id,
                          "mode": "txt2vid",
                          "prompt": prompt,
                          "negative_prompt": (
                              "blurry, low quality, static, jittery, watermark, "
                              "distorted audio"
                          ),
                          # LTX-2 requires width/height as multiples of 32.
                          "width": 512,
                          "height": 320,
                          # LTX-2 requires (8*k + 1) frames, max 257. At 24 fps:
                          # 25~=1s, 121~=5s, 241~=10s.
                          "video_frames": 121,
                          "fps": 24,
                          # Distilled variants run in 4-8 steps with cfg ~1.0; the
                          # full --dev model wants steps >= 20 and cfg ~7.0.
                          "steps": 10,
                          "cfg_scale": 1.0,
                          "seed": 42,
                          # Tile the video VAE decode along the time axis to cap peak
                          # VRAM on long / HD clips (LTX-2 only).
                          "temporal_tiling": True,
                      }
                  )

                  clips: list[bytes] = []
                  stats = None
                  async for response in video_stream(t, request):
                      if response.step is not None and response.total_steps is not None:
                          print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                      if response.data is not None:
                          clips.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, clip in enumerate(clips):
                      output_path = output_dir / f"ltx_t2v_{index}.avi"
                      output_path.write_bytes(clip)
                      print(
                          f"▸ Saved {output_path} "
                          "(play in VLC to hear the muxed audio track)"
                      )

                  print("\n▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

                  await unload_model(t, model_id)
                  print("▸ Done")
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionTxt2vidLtx.kt title="DiffusionTxt2vidLtx.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-txt2vid-ltx.ts.
      //
      // Text-to-video (+ synchronized audio) with LTX-2. Unlike Wan, LTX-2 uses a
      // Gemma text encoder (llmModelSrc), a video VAE (vaeModelSrc), a set of
      // text-embedding connectors (embeddingsConnectorsModelSrc -- this is what
      // selects the LTX-2 layout), and an optional audio VAE (audioVaeModelSrc) that
      // produces a 48 kHz audio track muxed into the output AVI.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via args to override any of the five sources.
      //
      // `client.media.video()` returns a `QvacMediaRun`: progress arrives on the
      // `events` Flow, and the clips and stats on the `final` Deferred, as TypeScript
      // splits them.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionTxt2vidLtx --args="[diffusion-src] [llm-src] [vae-src] [audio-vae-src] [connectors-src] [prompt] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val diffusionModelSrc = args.getOrNull(0) ?: Models.LTX_2_3_22B_Q5_K_M.src
          val llmModelSrc = args.getOrNull(1) ?: Models.GEMMA_3_12B_Q4_K_XL.src
          val vaeModelSrc = args.getOrNull(2) ?: Models.LTX_2_3_VIDEO_VAE.src
          val audioVaeModelSrc = args.getOrNull(3) ?: Models.LTX_2_3_AUDIO_VAE.src
          val embeddingsConnectorsModelSrc = args.getOrNull(4) ?: Models.LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS.src

          val prompt = args.getOrNull(5) ?: "a claymation cat playing jazz on a piano"
          val outputDir = Path.of(args.getOrNull(6) ?: ".")

          println("▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      // Supplying embeddingsConnectorsModelSrc selects the LTX-2
                      // layout.
                      put("llmModelSrc", llmModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("audioVaeModelSrc", audioVaeModelSrc)
                      put("embeddingsConnectorsModelSrc", embeddingsConnectorsModelSrc)
                      put("diffusion_fa", true)
                      put("vae_tiling", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              println("\n▸ Generating video for: \"$prompt\"")

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.TXT2VID,
                      prompt = prompt,
                      negative_prompt = "blurry, low quality, static, jittery, watermark, distorted audio",
                      // LTX-2 requires width/height as multiples of 32.
                      width = 512,
                      height = 320,
                      // LTX-2 requires (8*k + 1) frames, max 257. At 24 fps:
                      // 25~=1s, 121~=5s, 241~=10s.
                      video_frames = 121,
                      fps = 24.0,
                      // Distilled variants run in 4-8 steps with cfg ~1.0; the
                      // full --dev model wants steps >= 20 and cfg ~7.0.
                      steps = 10,
                      cfg_scale = 1.0,
                      seed = 42,
                      // Tile the video VAE decode along the time axis to cap peak
                      // VRAM on long / HD clips (LTX-2 only).
                      temporal_tiling = true,
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("ltx_t2v_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath (play in VLC to hear the muxed audio track)")
              }

              println("\n▸ Stats: ${result.stats}")

              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Image-to-video (LTX-2)

The following script animates a first-frame `init_image` with LTX-2. Unlike WAN I2V, the LTX-2 img2vid path needs no CLIP-vision encoder:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-img2vid-ltx.js title="diffusion-img2vid-ltx.js" lineNumbers
      import { GEMMA_3_12B_Q4_K_XL, loadModel, LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS, LTX_2_3_22B_Q5_K_M, LTX_2_3_AUDIO_VAE, LTX_2_3_VIDEO_VAE, unloadModel, video } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Image-to-video (+ synchronized audio) with LTX-2. Unlike Wan I2V, LTX-2
      // conditions on the first frame through its video VAE, so it needs NO CLIP
      // vision weights (clipVisionModelSrc) — the same LTX-2 layout used for
      // txt2vid works for img2vid, you just add an init_image at generation time.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via argv to override any of the five sources.
      const initImagePath = process.argv[2];
      const prompt = process.argv[3] || 'the subject slowly turns and smiles, soft natural lighting, cinematic';
      const outputDir = process.argv[4] || '.';
      const diffusionModelSrc = process.argv[5] || LTX_2_3_22B_Q5_K_M;
      const llmModelSrc = process.argv[6] || GEMMA_3_12B_Q4_K_XL;
      const vaeModelSrc = process.argv[7] || LTX_2_3_VIDEO_VAE;
      const audioVaeModelSrc = process.argv[8] || LTX_2_3_AUDIO_VAE;
      const embeddingsConnectorsModelSrc = process.argv[9] || LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS;
      if (!initImagePath) {
          console.error('✖ init image path is required');
          console.error('Usage: node dist/examples/diffusion-img2vid-ltx.js ' +
              '<initImagePath> [prompt] [outputDir] ' +
              '[diffusionModelSrc] [llmModelSrc] [vaeModelSrc] [audioVaeModelSrc] [embeddingsConnectorsModelSrc]');
          process.exit(1);
      }
      try {
          console.log('▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...');
          // no clipVisionModelSrc — LTX-2 img2vid does not use CLIP vision.
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  // Supplying embeddingsConnectorsModelSrc selects the LTX-2 layout.
                  llmModelSrc,
                  vaeModelSrc,
                  audioVaeModelSrc,
                  embeddingsConnectorsModelSrc,
                  diffusion_fa: true,
                  vae_tiling: true
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          const init_image = new Uint8Array(fs.readFileSync(initImagePath));
          console.log(`▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'img2vid',
              prompt,
              init_image,
              negative_prompt: 'blurry, distorted, low quality, jittery, static, frozen, distorted audio',
              strength: 0.85,
              // LTX-2 requires width/height as multiples of 32 and (8*k + 1) frames (max 257).
              width: 512,
              height: 320,
              video_frames: 121,
              fps: 24,
              steps: 10,
              cfg_scale: 1.0,
              seed: 42,
              temporal_tiling: true
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `ltx_i2v_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath} (play in VLC to hear the muxed audio track)`);
          }
          console.log('▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          console.log('▸ Done');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-img2vid-ltx.ts title="diffusion-img2vid-ltx.ts" lineNumbers
      import {
        GEMMA_3_12B_Q4_K_XL,
        loadModel,
        LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
        LTX_2_3_22B_Q5_K_M,
        LTX_2_3_AUDIO_VAE,
        LTX_2_3_VIDEO_VAE,
        unloadModel,
        video
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Image-to-video (+ synchronized audio) with LTX-2. Unlike Wan I2V, LTX-2
      // conditions on the first frame through its video VAE, so it needs NO CLIP
      // vision weights (clipVisionModelSrc) — the same LTX-2 layout used for
      // txt2vid works for img2vid, you just add an init_image at generation time.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via argv to override any of the five sources.
      const initImagePath = process.argv[2]
      const prompt =
        process.argv[3] || 'the subject slowly turns and smiles, soft natural lighting, cinematic'
      const outputDir = process.argv[4] || '.'
      const diffusionModelSrc = process.argv[5] || LTX_2_3_22B_Q5_K_M
      const llmModelSrc = process.argv[6] || GEMMA_3_12B_Q4_K_XL
      const vaeModelSrc = process.argv[7] || LTX_2_3_VIDEO_VAE
      const audioVaeModelSrc = process.argv[8] || LTX_2_3_AUDIO_VAE
      const embeddingsConnectorsModelSrc = process.argv[9] || LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS

      if (!initImagePath) {
        console.error('✖ init image path is required')
        console.error(
          'Usage: node dist/examples/diffusion-img2vid-ltx.js ' +
            '<initImagePath> [prompt] [outputDir] ' +
            '[diffusionModelSrc] [llmModelSrc] [vaeModelSrc] [audioVaeModelSrc] [embeddingsConnectorsModelSrc]'
        )
        process.exit(1)
      }

      try {
        console.log('▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...')
        // no clipVisionModelSrc — LTX-2 img2vid does not use CLIP vision.
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            // Supplying embeddingsConnectorsModelSrc selects the LTX-2 layout.
            llmModelSrc,
            vaeModelSrc,
            audioVaeModelSrc,
            embeddingsConnectorsModelSrc,
            diffusion_fa: true,
            vae_tiling: true
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        const init_image = new Uint8Array(fs.readFileSync(initImagePath))
        console.log(`▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'img2vid',
          prompt,
          init_image,
          negative_prompt: 'blurry, distorted, low quality, jittery, static, frozen, distorted audio',
          strength: 0.85,
          // LTX-2 requires width/height as multiples of 32 and (8*k + 1) frames (max 257).
          width: 512,
          height: 320,
          video_frames: 121,
          fps: 24,
          steps: 10,
          cfg_scale: 1.0,
          seed: 42,
          temporal_tiling: true
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `ltx_i2v_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath} (play in VLC to hear the muxed audio track)`)
        }

        console.log('▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        console.log('▸ Done')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_img2vid_ltx.py title="diffusion_img2vid_ltx.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-img2vid-ltx.ts.

      Image-to-video (+ synchronized audio) with LTX-2. Unlike Wan I2V, LTX-2
      conditions on the first frame through its video VAE, so it needs NO CLIP vision
      weights (clipVisionModelSrc) -- the same LTX-2 layout used for txt2vid works
      for img2vid, you just add an init_image at generation time.

      This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at least
      20+ GB of video / unified memory.

      Pass your own paths / URLs via argv to override any of the five sources.

      TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes them
      on the way to the worker. Python calls the worker directly through
      `video_stream`, where `init_image` is already the encoded string, so the
      example encodes the file itself. The same iterator then carries progress, the
      finished clips and the closing stats, which TypeScript receives as three
      separate channels.

      RUN: python examples/diffusion_img2vid_ltx.py <init-image> [prompt] [output-dir] [diffusion-src] [llm-src] [vae-src] [audio-vae-src] [connectors-src]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          GEMMA_3_12B_Q4_K_XL,
          LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
          LTX_2_3_22B_Q5_K_M,
          LTX_2_3_AUDIO_VAE,
          LTX_2_3_VIDEO_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          init_image_path = sys.argv[1] if len(sys.argv) > 1 else None
          prompt = (
              sys.argv[2]
              if len(sys.argv) > 2
              else "the subject slowly turns and smiles, soft natural lighting, cinematic"
          )
          output_dir = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(".")
          diffusion_model_src = sys.argv[4] if len(sys.argv) > 4 else LTX_2_3_22B_Q5_K_M
          llm_model_src = sys.argv[5] if len(sys.argv) > 5 else GEMMA_3_12B_Q4_K_XL
          vae_model_src = sys.argv[6] if len(sys.argv) > 6 else LTX_2_3_VIDEO_VAE
          audio_vae_model_src = sys.argv[7] if len(sys.argv) > 7 else LTX_2_3_AUDIO_VAE
          embeddings_connectors_model_src = (
              sys.argv[8]
              if len(sys.argv) > 8
              else LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS
          )

          if not init_image_path:
              print("✖ init image path is required", file=sys.stderr)
              print(
                  "Usage: python examples/diffusion_img2vid_ltx.py <initImagePath> "
                  "[prompt] [outputDir] [diffusionModelSrc] [llmModelSrc] "
                  "[vaeModelSrc] [audioVaeModelSrc] [embeddingsConnectorsModelSrc]",
                  file=sys.stderr,
              )
              return 1

          print(
              "▸ Loading LTX-2 model "
              "(diffusion + Gemma + video VAE + audio VAE + connectors)..."
          )

          try:
              async with Client() as client:
                  t = client.transport

                  # no clipVisionModelSrc -- LTX-2 img2vid does not use CLIP vision.
                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "mode": "video",
                          "device": "gpu",
                          "threads": 4,
                          # Supplying embeddingsConnectorsModelSrc selects the LTX-2
                          # layout.
                          "llmModelSrc": llm_model_src,
                          "vaeModelSrc": vae_model_src,
                          "audioVaeModelSrc": audio_vae_model_src,
                          "embeddingsConnectorsModelSrc": embeddings_connectors_model_src,
                          "diffusion_fa": True,
                          "vae_tiling": True,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  init_image = base64.b64encode(Path(init_image_path).read_bytes()).decode(
                      "ascii"
                  )
                  print(f'▸ Generating video for: "{prompt}"')

                  request = VideoStreamRequest.model_validate(
                      {
                          "type": "videoStream",
                          "modelId": model_id,
                          "mode": "img2vid",
                          "prompt": prompt,
                          "init_image": init_image,
                          "negative_prompt": (
                              "blurry, distorted, low quality, jittery, static, frozen, "
                              "distorted audio"
                          ),
                          "strength": 0.85,
                          # LTX-2 requires width/height as multiples of 32 and
                          # (8*k + 1) frames (max 257).
                          "width": 512,
                          "height": 320,
                          "video_frames": 121,
                          "fps": 24,
                          "steps": 10,
                          "cfg_scale": 1.0,
                          "seed": 42,
                          "temporal_tiling": True,
                      }
                  )

                  clips: list[bytes] = []
                  stats = None
                  async for response in video_stream(t, request):
                      if response.step is not None and response.total_steps is not None:
                          print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                      if response.data is not None:
                          clips.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, clip in enumerate(clips):
                      output_path = output_dir / f"ltx_i2v_{index}.avi"
                      output_path.write_bytes(clip)
                      print(
                          f"▸ Saved {output_path} "
                          "(play in VLC to hear the muxed audio track)"
                      )

                  print("▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

                  await unload_model(t, model_id)
                  print("▸ Done")
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionImg2vidLtx.kt title="DiffusionImg2vidLtx.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-img2vid-ltx.ts.
      //
      // Image-to-video (+ synchronized audio) with LTX-2. Unlike Wan I2V, LTX-2
      // conditions on the first frame through its video VAE, so it needs NO CLIP
      // vision weights (clipVisionModelSrc) -- the same LTX-2 layout used for
      // txt2vid works for img2vid, you just add an init_image at generation time.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // Pass your own paths / URLs via args to override any of the five sources.
      //
      // TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes
      // them on the way to the worker. The typed `VideoStreamRequest` carries the
      // encoded string, so the example encodes the file with `java.util.Base64`. The
      // returned `QvacMediaRun` splits progress (`events` Flow) from the clips and
      // stats (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionImg2vidLtx --args="<init-image> [prompt] [output-dir] [diffusion-src] [llm-src] [vae-src] [audio-vae-src] [connectors-src]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val initImagePath = args.getOrNull(0)
          val prompt = args.getOrNull(1) ?: "the subject slowly turns and smiles, soft natural lighting, cinematic"
          val outputDir = Path.of(args.getOrNull(2) ?: ".")
          val diffusionModelSrc = args.getOrNull(3) ?: Models.LTX_2_3_22B_Q5_K_M.src
          val llmModelSrc = args.getOrNull(4) ?: Models.GEMMA_3_12B_Q4_K_XL.src
          val vaeModelSrc = args.getOrNull(5) ?: Models.LTX_2_3_VIDEO_VAE.src
          val audioVaeModelSrc = args.getOrNull(6) ?: Models.LTX_2_3_AUDIO_VAE.src
          val embeddingsConnectorsModelSrc = args.getOrNull(7) ?: Models.LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS.src

          if (initImagePath.isNullOrEmpty()) {
              System.err.println("✖ init image path is required")
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionImg2vidLtx --args=\"<initImagePath> " +
                      "[prompt] [outputDir] [diffusionModelSrc] [llmModelSrc] " +
                      "[vaeModelSrc] [audioVaeModelSrc] [embeddingsConnectorsModelSrc]\"",
              )
              exitProcess(1)
          }

          println("▸ Loading LTX-2 model (diffusion + Gemma + video VAE + audio VAE + connectors)...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              // No clipVisionModelSrc -- LTX-2 img2vid does not use CLIP vision.
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      // Supplying embeddingsConnectorsModelSrc selects the LTX-2
                      // layout.
                      put("llmModelSrc", llmModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("audioVaeModelSrc", audioVaeModelSrc)
                      put("embeddingsConnectorsModelSrc", embeddingsConnectorsModelSrc)
                      put("diffusion_fa", true)
                      put("vae_tiling", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              val initImage = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(initImagePath)))
              println("▸ Generating video for: \"$prompt\"")

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.IMG2VID,
                      prompt = prompt,
                      init_image = initImage,
                      negative_prompt = "blurry, distorted, low quality, jittery, static, frozen, distorted audio",
                      strength = 0.85,
                      // LTX-2 requires width/height as multiples of 32 and
                      // (8*k + 1) frames (max 257).
                      width = 512,
                      height = 320,
                      video_frames = 121,
                      fps = 24.0,
                      steps = 10,
                      cfg_scale = 1.0,
                      seed = 42,
                      temporal_tiling = true,
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("ltx_i2v_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath (play in VLC to hear the muxed audio track)")
              }

              println("▸ Stats: ${result.stats}")

              client.models.unload(modelId)
              println("▸ Done")
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Reference-conditioned text-to-video (LTX-2 IC-LoRA)

The following script conditions LTX-2 on a composite reference sheet so the generated video inherits a specific character or style. Load LTX-2 with `lora_apply_mode: 'at_runtime'`, then pass the reference sheet in `reference_images` alongside an Ingredients LoRA in `lora`. Reference conditioning requires at least **121** frames, so `video_frames` is set to `217`:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-ic-lora-ltx.js title="diffusion-ic-lora-ltx.js" lineNumbers
      import { GEMMA_3_12B_Q4_K_XL, loadModel, LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS, LTX_2_3_22B_Q5_K_M, LTX_2_3_AUDIO_VAE, LTX_2_3_VIDEO_VAE, unloadModel, video } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      const loraPath = process.argv[2];
      const referencePath = process.argv[3];
      const prompt = process.argv[4] ||
          'Reference sheet: a red-haired explorer in a blue parka. Generated video: the explorer crosses a snowy ridge at sunrise.';
      const outputDir = process.argv[5] || '.';
      if (!loraPath || !referencePath) {
          console.error('Usage: bare:example examples/diffusion-ic-lora-ltx.ts <absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]');
          process.exit(1);
      }
      if (!path.isAbsolute(loraPath)) {
          console.error('The LoRA adapter path must be absolute on the inference worker.');
          process.exit(1);
      }
      const referenceSheet = fs.readFileSync(referencePath);
      try {
          const modelId = await loadModel({
              modelSrc: LTX_2_3_22B_Q5_K_M,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  mode: 'video',
                  device: 'gpu',
                  threads: 4,
                  llmModelSrc: GEMMA_3_12B_Q4_K_XL,
                  vaeModelSrc: LTX_2_3_VIDEO_VAE,
                  audioVaeModelSrc: LTX_2_3_AUDIO_VAE,
                  embeddingsConnectorsModelSrc: LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
                  diffusion_fa: true,
                  offload_to_cpu: true,
                  vae_tiling: true,
                  lora_apply_mode: 'at_runtime'
              }
          });
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'txt2vid',
              prompt,
              negative_prompt: 'blurry, low quality, static, jittery, watermark',
              width: 768,
              height: 448,
              video_frames: 217,
              fps: 24,
              steps: 8,
              scheduler: 'ltx2',
              cfg_scale: 1,
              seed: 84,
              lora: loraPath,
              lora_strength: 1.37,
              stg_scale: 1,
              stg_block: 29,
              reference_images: [referenceSheet],
              reference_attention_strength: 1,
              reference_downscale_factor: 1,
              temporal_tiling: true,
              vae_tile_size: 4
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          fs.mkdirSync(outputDir, { recursive: true });
          const buffers = await outputs;
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `ltx_ic_lora_${i}.avi`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-ic-lora-ltx.ts title="diffusion-ic-lora-ltx.ts" lineNumbers
      import {
        GEMMA_3_12B_Q4_K_XL,
        loadModel,
        LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
        LTX_2_3_22B_Q5_K_M,
        LTX_2_3_AUDIO_VAE,
        LTX_2_3_VIDEO_VAE,
        unloadModel,
        video
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      const loraPath = process.argv[2]
      const referencePath = process.argv[3]
      const prompt =
        process.argv[4] ||
        'Reference sheet: a red-haired explorer in a blue parka. Generated video: the explorer crosses a snowy ridge at sunrise.'
      const outputDir = process.argv[5] || '.'

      if (!loraPath || !referencePath) {
        console.error(
          'Usage: bare:example examples/diffusion-ic-lora-ltx.ts <absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]'
        )
        process.exit(1)
      }
      if (!path.isAbsolute(loraPath)) {
        console.error('The LoRA adapter path must be absolute on the inference worker.')
        process.exit(1)
      }

      const referenceSheet = fs.readFileSync(referencePath)

      try {
        const modelId = await loadModel({
          modelSrc: LTX_2_3_22B_Q5_K_M,
          modelType: 'sdcpp-generation',
          modelConfig: {
            mode: 'video',
            device: 'gpu',
            threads: 4,
            llmModelSrc: GEMMA_3_12B_Q4_K_XL,
            vaeModelSrc: LTX_2_3_VIDEO_VAE,
            audioVaeModelSrc: LTX_2_3_AUDIO_VAE,
            embeddingsConnectorsModelSrc: LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
            diffusion_fa: true,
            offload_to_cpu: true,
            vae_tiling: true,
            lora_apply_mode: 'at_runtime'
          }
        })

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'txt2vid',
          prompt,
          negative_prompt: 'blurry, low quality, static, jittery, watermark',
          width: 768,
          height: 448,
          video_frames: 217,
          fps: 24,
          steps: 8,
          scheduler: 'ltx2',
          cfg_scale: 1,
          seed: 84,
          lora: loraPath,
          lora_strength: 1.37,
          stg_scale: 1,
          stg_block: 29,
          reference_images: [referenceSheet],
          reference_attention_strength: 1,
          reference_downscale_factor: 1,
          temporal_tiling: true,
          vae_tile_size: 4
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        fs.mkdirSync(outputDir, { recursive: true })
        const buffers = await outputs
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `ltx_ic_lora_${i}.avi`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

        console.log('▸ Stats:', await stats)
        await unloadModel({ modelId, clearStorage: false })
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_ic_lora_ltx.py title="diffusion_ic_lora_ltx.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-ic-lora-ltx.ts.

      Reference-conditioned text-to-video with LTX-2 and an Ingredients (IC) LoRA.
      The LoRA is applied at runtime (`lora_apply_mode: 'at_runtime'`), and a
      composite reference sheet is handed to generation in `reference_images` so the
      clip inherits the character / style it shows. Reference conditioning needs at
      least 121 frames, hence `video_frames: 217`.

      This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at least
      20+ GB of video / unified memory.

      TypeScript's `video()` takes `reference_images` as raw bytes and base64-encodes
      them on the way to the worker. Python calls the worker directly through
      `video_stream`, where each entry is already the encoded string, so the example
      encodes the file itself. The same iterator then carries progress, the finished
      clips and the closing stats, which TypeScript receives as three separate
      channels.

      RUN: python examples/diffusion_ic_lora_ltx.py <absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )
      from tetherto.qvac_sdk.models import (
          GEMMA_3_12B_Q4_K_XL,
          LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS,
          LTX_2_3_22B_Q5_K_M,
          LTX_2_3_AUDIO_VAE,
          LTX_2_3_VIDEO_VAE,
      )


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          lora_path = sys.argv[1] if len(sys.argv) > 1 else None
          reference_path = sys.argv[2] if len(sys.argv) > 2 else None
          prompt = (
              sys.argv[3]
              if len(sys.argv) > 3
              else (
                  "Reference sheet: a red-haired explorer in a blue parka. Generated "
                  "video: the explorer crosses a snowy ridge at sunrise."
              )
          )
          output_dir = Path(sys.argv[4]) if len(sys.argv) > 4 else Path(".")

          if not lora_path or not reference_path:
              print(
                  "Usage: python examples/diffusion_ic_lora_ltx.py "
                  "<absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]",
                  file=sys.stderr,
              )
              return 1
          if not Path(lora_path).is_absolute():
              print(
                  "✖ The LoRA adapter path must be absolute on the inference worker.",
                  file=sys.stderr,
              )
              return 1

          reference_sheet = base64.b64encode(Path(reference_path).read_bytes()).decode(
              "ascii"
          )

          try:
              async with Client() as client:
                  t = client.transport

                  model_id = await load_model(
                      t,
                      model_src=LTX_2_3_22B_Q5_K_M,
                      model_type="sdcpp-generation",
                      model_config={
                          "mode": "video",
                          "device": "gpu",
                          "threads": 4,
                          "llmModelSrc": GEMMA_3_12B_Q4_K_XL,
                          "vaeModelSrc": LTX_2_3_VIDEO_VAE,
                          "audioVaeModelSrc": LTX_2_3_AUDIO_VAE,
                          "embeddingsConnectorsModelSrc": (
                              LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS
                          ),
                          "diffusion_fa": True,
                          "offload_to_cpu": True,
                          "vae_tiling": True,
                          # Keep the LoRA out of the loaded weights so it can be
                          # swapped per request.
                          "lora_apply_mode": "at_runtime",
                      },
                      on_progress=print_progress,
                  )

                  request = VideoStreamRequest.model_validate(
                      {
                          "type": "videoStream",
                          "modelId": model_id,
                          "mode": "txt2vid",
                          "prompt": prompt,
                          "negative_prompt": (
                              "blurry, low quality, static, jittery, watermark"
                          ),
                          "width": 768,
                          "height": 448,
                          # Reference conditioning requires at least 121 frames.
                          "video_frames": 217,
                          "fps": 24,
                          "steps": 8,
                          "scheduler": "ltx2",
                          "cfg_scale": 1,
                          "seed": 84,
                          "lora": lora_path,
                          "lora_strength": 1.37,
                          "stg_scale": 1,
                          "stg_block": 29,
                          "reference_images": [reference_sheet],
                          "reference_attention_strength": 1,
                          "reference_downscale_factor": 1,
                          "temporal_tiling": True,
                          "vae_tile_size": 4,
                      }
                  )

                  clips: list[bytes] = []
                  stats = None
                  async for response in video_stream(t, request):
                      if response.step is not None and response.total_steps is not None:
                          print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                      if response.data is not None:
                          clips.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  output_dir.mkdir(parents=True, exist_ok=True)
                  for index, clip in enumerate(clips):
                      output_path = output_dir / f"ltx_ic_lora_{index}.avi"
                      output_path.write_bytes(clip)
                      print(f"▸ Saved {output_path}")

                  print("▸ Stats:", stats.model_dump(exclude_none=True) if stats else None)

                  await unload_model(t, model_id, clear_storage=False)
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionIcLoraLtx.kt title="DiffusionIcLoraLtx.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-ic-lora-ltx.ts.
      //
      // Reference-conditioned text-to-video with LTX-2 and an Ingredients (IC) LoRA.
      // The LoRA is applied at runtime (`lora_apply_mode: "at_runtime"`), and a
      // composite reference sheet is handed to generation in `reference_images` so
      // the clip inherits the character / style it shows. Reference conditioning
      // needs at least 121 frames, hence `video_frames = 217`.
      //
      // This example needs powerful hardware: LTX-2.3 is a ~21B model, budget at
      // least 20+ GB of video / unified memory.
      //
      // TypeScript's `video()` takes `reference_images` as raw bytes and
      // base64-encodes them on the way to the worker. The typed `VideoStreamRequest`
      // carries the encoded strings, so the example encodes the file with
      // `java.util.Base64`. `scheduler` is a generated enum and `vae_tile_size` a
      // generated number-or-string union (`Variant1` holds the number). The returned
      // `QvacMediaRun` splits progress (`events` Flow) from the clips and stats
      // (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionIcLoraLtx --args="<absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestScheduler
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestVae_tile_size
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val loraPath = args.getOrNull(0)
          val referencePath = args.getOrNull(1)
          val prompt = args.getOrNull(2)
              ?: ("Reference sheet: a red-haired explorer in a blue parka. Generated " +
                  "video: the explorer crosses a snowy ridge at sunrise.")
          val outputDir = Path.of(args.getOrNull(3) ?: ".")

          if (loraPath.isNullOrEmpty() || referencePath.isNullOrEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionIcLoraLtx " +
                      "--args=\"<absolute-lora-path> <reference-sheet-path> [prompt] [output-dir]\"",
              )
              exitProcess(1)
          }
          if (!Path.of(loraPath).isAbsolute) {
              System.err.println("✖ The LoRA adapter path must be absolute on the inference worker.")
              exitProcess(1)
          }

          val referenceSheet = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(referencePath)))

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = Models.LTX_2_3_22B_Q5_K_M.src,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("mode", "video")
                      put("device", "gpu")
                      put("threads", 4)
                      put("llmModelSrc", Models.GEMMA_3_12B_Q4_K_XL.src)
                      put("vaeModelSrc", Models.LTX_2_3_VIDEO_VAE.src)
                      put("audioVaeModelSrc", Models.LTX_2_3_AUDIO_VAE.src)
                      put("embeddingsConnectorsModelSrc", Models.LTX_2_3_22B_DISTILLED_EMBEDDINGS_CONNECTORS.src)
                      put("diffusion_fa", true)
                      put("offload_to_cpu", true)
                      put("vae_tiling", true)
                      // Keep the LoRA out of the loaded weights so it can be swapped
                      // per request.
                      put("lora_apply_mode", "at_runtime")
                  },
              )

              val run = client.media.video(
                  VideoStreamRequest(
                      modelId = modelId,
                      mode = VideoStreamRequestMode.TXT2VID,
                      prompt = prompt,
                      negative_prompt = "blurry, low quality, static, jittery, watermark",
                      width = 768,
                      height = 448,
                      // Reference conditioning requires at least 121 frames.
                      video_frames = 217,
                      fps = 24.0,
                      steps = 8,
                      scheduler = VideoStreamRequestScheduler.LTX2,
                      cfg_scale = 1.0,
                      seed = 84,
                      lora = loraPath,
                      lora_strength = 1.37,
                      stg_scale = 1.0,
                      stg_block = 29,
                      reference_images = listOf(referenceSheet),
                      reference_attention_strength = 1.0,
                      reference_downscale_factor = 1.0,
                      temporal_tiling = true,
                      vae_tile_size = VideoStreamRequestVae_tile_size.Variant1(4.0),
                  ),
              )
              run.events.collect { event ->
                  if (event.step != null && event.totalSteps != null) {
                      println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                  }
              }
              val result = run.final.await()

              Files.createDirectories(outputDir)
              result.data.forEachIndexed { index, clip ->
                  val outputPath = outputDir.resolve("ltx_ic_lora_$index.avi")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath")
              }

              println("▸ Stats: ${result.stats}")

              client.models.unload(modelId, clearStorage = false)
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(
          source: String,
          modelType: String,
          modelConfig: JsonObject? = null,
      ): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Text-to-video with audio (MiniMax-H3)

The following script loads MiniMax-H3 with its split layout (diffusion model + Qwen3-VL text encoder + video VAE + audio VAE) and generates a clip with a synchronized 32 kHz audio track. It uses the H3 constraints (dimensions in multiples of 32, `17*k + 5` frames, 24 FPS) and leaves `offload_to_cpu` on so the run fits on a single GPU:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-txt2vid-minimax-h3.js title="diffusion-txt2vid-minimax-h3.js" lineNumbers
      import { loadModel, unloadModel, video } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Pass a directory containing the four MiniMax-H3 files, followed by an output path.
      const modelsDir = process.argv[2];
      if (!modelsDir) {
          throw new Error('Usage: diffusion-txt2vid-minimax-h3.ts <models-directory> [output.avi]');
      }
      const outputPath = process.argv[3] || 'minimax-h3.avi';
      const modelSrc = path.resolve(modelsDir, process.env['H3_MODEL'] || 'minimax_h3_fl2va_pruned-Q4_K.gguf');
      const llmModelSrc = path.resolve(modelsDir, process.env['H3_LLM'] || 'qwen3vl_32b_minimax_h3-Q4_K_M.gguf');
      const vaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_video_vae_fp16.safetensors');
      const audioVaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_audio_vae_fp32.safetensors');
      for (const file of [modelSrc, llmModelSrc, vaeModelSrc, audioVaeModelSrc])
          fs.accessSync(file);
      let modelId;
      try {
          modelId = await loadModel({
              modelType: 'sdcpp-generation',
              modelSrc,
              modelConfig: {
                  mode: 'video',
                  llmModelSrc,
                  vaeModelSrc,
                  audioVaeModelSrc,
                  device: 'gpu',
                  diffusion_fa: true,
                  offload_to_cpu: process.env['H3_OFFLOAD_TO_CPU'] !== '0',
                  stream_layers: process.env['H3_STREAM_LAYERS'] === '1',
                  ...(process.env['H3_BACKEND'] && { backend: process.env['H3_BACKEND'] }),
                  ...(process.env['H3_PARAMS_BACKEND'] && { params_backend: process.env['H3_PARAMS_BACKEND'] }),
                  ...(process.env['H3_MAX_VRAM'] && { max_vram: process.env['H3_MAX_VRAM'] })
              }
          });
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'txt2vid',
              prompt: process.env['PROMPT'] ||
                  'Premium cinematic coffee commercial. A confident adult sits at a small café table at sunrise, slowly lifts one matte black coffee cup, takes a relaxed sip, and smiles. Warm golden rim light, drifting steam, realistic skin, natural hands, shallow depth of field, subtle slow camera push-in, restrained natural motion, polished live-action advertising, no dialogue, no text overlay.',
              negative_prompt: 'extra people, duplicate cup, malformed hands, cup fused to hand, text, subtitles, watermark, cartoon, CGI, blur, flicker, jitter, camera shake',
              width: 960,
              height: 544,
              // H3 uses 17*k+5 frames; 124 frames at 24 FPS is approximately 5.17 seconds.
              video_frames: Number(process.env['FRAMES'] || 124),
              fps: 24,
              steps: 8,
              cfg_scale: 1,
              seed: 11
          });
          const progress = (async () => {
              for await (const tick of progressStream)
                  console.log(`Step ${tick.step}/${tick.totalSteps}`);
          })();
          const [buffers, runtimeStats] = await Promise.all([outputs, stats, progress]);
          if (!buffers[0])
              throw new Error('Generation finished without an AVI result');
          fs.writeFileSync(outputPath, buffers[0]);
          console.log(`Saved ${outputPath}`, runtimeStats);
      }
      finally {
          if (modelId)
              await unloadModel({ modelId, clearStorage: false });
      }
      process.exit(0);
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-txt2vid-minimax-h3.ts title="diffusion-txt2vid-minimax-h3.ts" lineNumbers
      import { loadModel, unloadModel, video } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // Pass a directory containing the four MiniMax-H3 files, followed by an output path.
      const modelsDir = process.argv[2]
      if (!modelsDir) {
        throw new Error('Usage: diffusion-txt2vid-minimax-h3.ts <models-directory> [output.avi]')
      }
      const outputPath = process.argv[3] || 'minimax-h3.avi'
      const modelSrc = path.resolve(
        modelsDir,
        process.env['H3_MODEL'] || 'minimax_h3_fl2va_pruned-Q4_K.gguf'
      )
      const llmModelSrc = path.resolve(
        modelsDir,
        process.env['H3_LLM'] || 'qwen3vl_32b_minimax_h3-Q4_K_M.gguf'
      )
      const vaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_video_vae_fp16.safetensors')
      const audioVaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_audio_vae_fp32.safetensors')
      for (const file of [modelSrc, llmModelSrc, vaeModelSrc, audioVaeModelSrc]) fs.accessSync(file)

      let modelId: string | undefined
      try {
        modelId = await loadModel({
          modelType: 'sdcpp-generation',
          modelSrc,
          modelConfig: {
            mode: 'video',
            llmModelSrc,
            vaeModelSrc,
            audioVaeModelSrc,
            device: 'gpu',
            diffusion_fa: true,
            offload_to_cpu: process.env['H3_OFFLOAD_TO_CPU'] !== '0',
            stream_layers: process.env['H3_STREAM_LAYERS'] === '1',
            ...(process.env['H3_BACKEND'] && { backend: process.env['H3_BACKEND'] }),
            ...(process.env['H3_PARAMS_BACKEND'] && { params_backend: process.env['H3_PARAMS_BACKEND'] }),
            ...(process.env['H3_MAX_VRAM'] && { max_vram: process.env['H3_MAX_VRAM'] })
          }
        })
        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'txt2vid',
          prompt:
            process.env['PROMPT'] ||
            'Premium cinematic coffee commercial. A confident adult sits at a small café table at sunrise, slowly lifts one matte black coffee cup, takes a relaxed sip, and smiles. Warm golden rim light, drifting steam, realistic skin, natural hands, shallow depth of field, subtle slow camera push-in, restrained natural motion, polished live-action advertising, no dialogue, no text overlay.',
          negative_prompt:
            'extra people, duplicate cup, malformed hands, cup fused to hand, text, subtitles, watermark, cartoon, CGI, blur, flicker, jitter, camera shake',
          width: 960,
          height: 544,
          // H3 uses 17*k+5 frames; 124 frames at 24 FPS is approximately 5.17 seconds.
          video_frames: Number(process.env['FRAMES'] || 124),
          fps: 24,
          steps: 8,
          cfg_scale: 1,
          seed: 11
        })
        const progress = (async () => {
          for await (const tick of progressStream) console.log(`Step ${tick.step}/${tick.totalSteps}`)
        })()
        const [buffers, runtimeStats] = await Promise.all([outputs, stats, progress])
        if (!buffers[0]) throw new Error('Generation finished without an AVI result')
        fs.writeFileSync(outputPath, buffers[0])
        console.log(`Saved ${outputPath}`, runtimeStats)
      } finally {
        if (modelId) await unloadModel({ modelId, clearStorage: false })
      }
      process.exit(0)
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_txt2vid_minimax_h3.py title="diffusion_txt2vid_minimax_h3.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-txt2vid-minimax-h3.ts.

      Text-to-video (+ synchronized 32 kHz audio) with MiniMax-H3, which uses a
      split layout: a diffusion model, a Qwen3-VL text encoder, a video VAE and an
      audio VAE. The four files are read from a local directory you pass as argv, so
      nothing is downloaded.

      This example needs powerful hardware. `offload_to_cpu` stays on so the run
      fits on a single GPU; tune placement through the H3_* environment variables.

      TypeScript's `video()` hands back three channels -- `progressStream`, `outputs`
      and `stats` -- and the example drains the progress one concurrently with
      `Promise.all`. Python exposes one async iterator that yields all three in
      order, so the loop below needs no concurrency.

      RUN: python examples/diffusion_txt2vid_minimax_h3.py <models-directory> [output.avi]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import os
      import sys
      from pathlib import Path
      from typing import Any

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )

      DEFAULT_PROMPT = (
          "Premium cinematic coffee commercial. A confident adult sits at a small "
          "café table at sunrise, slowly lifts one matte black coffee cup, takes a "
          "relaxed sip, and smiles. Warm golden rim light, drifting steam, realistic "
          "skin, natural hands, shallow depth of field, subtle slow camera push-in, "
          "restrained natural motion, polished live-action advertising, no dialogue, "
          "no text overlay."
      )


      async def main() -> int:
          # Pass a directory containing the four MiniMax-H3 files, followed by an
          # output path.
          models_dir = sys.argv[1] if len(sys.argv) > 1 else None
          if not models_dir:
              print(
                  "Usage: python examples/diffusion_txt2vid_minimax_h3.py "
                  "<models-directory> [output.avi]",
                  file=sys.stderr,
              )
              return 1

          output_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("minimax-h3.avi")
          root = Path(models_dir).resolve()
          model_src = root / os.environ.get("H3_MODEL", "minimax_h3_fl2va_pruned-Q4_K.gguf")
          llm_model_src = root / os.environ.get(
              "H3_LLM", "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"
          )
          vae_model_src = root / "vae/minimax_h3_video_vae_fp16.safetensors"
          audio_vae_model_src = root / "vae/minimax_h3_audio_vae_fp32.safetensors"
          for file in (model_src, llm_model_src, vae_model_src, audio_vae_model_src):
              if not file.is_file():
                  print(f"✖ missing model file: {file}", file=sys.stderr)
                  return 1

          model_config: dict[str, Any] = {
              "mode": "video",
              "llmModelSrc": str(llm_model_src),
              "vaeModelSrc": str(vae_model_src),
              "audioVaeModelSrc": str(audio_vae_model_src),
              "device": "gpu",
              "diffusion_fa": True,
              "offload_to_cpu": os.environ.get("H3_OFFLOAD_TO_CPU") != "0",
              "stream_layers": os.environ.get("H3_STREAM_LAYERS") == "1",
          }
          for key, variable in (
              ("backend", "H3_BACKEND"),
              ("params_backend", "H3_PARAMS_BACKEND"),
              ("max_vram", "H3_MAX_VRAM"),
          ):
              value = os.environ.get(variable)
              if value:
                  model_config[key] = value

          model_id = None
          try:
              async with Client() as client:
                  t = client.transport
                  try:
                      model_id = await load_model(
                          t,
                          model_src=str(model_src),
                          model_type="sdcpp-generation",
                          model_config=model_config,
                      )

                      request = VideoStreamRequest.model_validate(
                          {
                              "type": "videoStream",
                              "modelId": model_id,
                              "mode": "txt2vid",
                              "prompt": os.environ.get("PROMPT") or DEFAULT_PROMPT,
                              "negative_prompt": (
                                  "extra people, duplicate cup, malformed hands, cup "
                                  "fused to hand, text, subtitles, watermark, cartoon, "
                                  "CGI, blur, flicker, jitter, camera shake"
                              ),
                              "width": 960,
                              "height": 544,
                              # H3 uses 17*k+5 frames; 124 frames at 24 FPS is
                              # approximately 5.17 seconds.
                              "video_frames": int(os.environ.get("FRAMES") or 124),
                              "fps": 24,
                              "steps": 8,
                              "cfg_scale": 1,
                              "seed": 11,
                          }
                      )

                      clips: list[bytes] = []
                      stats = None
                      async for response in video_stream(t, request):
                          if response.step is not None and response.total_steps is not None:
                              print(f"Step {response.step:.0f}/{response.total_steps:.0f}")
                          if response.data is not None:
                              clips.append(base64.b64decode(response.data))
                          if response.done:
                              stats = response.stats

                      if not clips:
                          raise RuntimeError("Generation finished without an AVI result")
                      output_path.write_bytes(clips[0])
                      print(
                          f"Saved {output_path}",
                          stats.model_dump(exclude_none=True) if stats else None,
                      )
                  finally:
                      if model_id:
                          await unload_model(t, model_id, clear_storage=False)
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionTxt2vidMinimaxH3.kt title="DiffusionTxt2vidMinimaxH3.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-txt2vid-minimax-h3.ts.
      //
      // Text-to-video (+ synchronized 32 kHz audio) with MiniMax-H3, which uses a
      // split layout: a diffusion model, a Qwen3-VL text encoder, a video VAE and an
      // audio VAE. The four files are read from a local directory you pass as args,
      // so nothing is downloaded.
      //
      // This example needs powerful hardware. `offload_to_cpu` stays on so the run
      // fits on a single GPU; tune placement through the H3_* environment variables.
      //
      // TypeScript's `video()` hands back separate channels and the example drains
      // the progress one concurrently with `Promise.all`. The Kotlin `QvacMediaRun`
      // buffers its `events` Flow, so collecting it first and then awaiting the
      // `final` Deferred needs no extra concurrency.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionTxt2vidMinimaxH3 --args="<models-directory> [output.avi]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      private const val DEFAULT_PROMPT =
          "Premium cinematic coffee commercial. A confident adult sits at a small " +
              "café table at sunrise, slowly lifts one matte black coffee cup, takes a " +
              "relaxed sip, and smiles. Warm golden rim light, drifting steam, realistic " +
              "skin, natural hands, shallow depth of field, subtle slow camera push-in, " +
              "restrained natural motion, polished live-action advertising, no dialogue, " +
              "no text overlay."

      fun main(args: Array<String>): Unit = runBlocking {
          // Pass a directory containing the four MiniMax-H3 files, followed by an
          // output path.
          val modelsDir = args.getOrNull(0)
          if (modelsDir.isNullOrEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionTxt2vidMinimaxH3 " +
                      "--args=\"<models-directory> [output.avi]\"",
              )
              exitProcess(1)
          }

          val outputPath = Path.of(args.getOrNull(1) ?: "minimax-h3.avi")
          val root = Path.of(modelsDir).toAbsolutePath().normalize()
          val modelSrc = root.resolve(System.getenv("H3_MODEL") ?: "minimax_h3_fl2va_pruned-Q4_K.gguf")
          val llmModelSrc = root.resolve(System.getenv("H3_LLM") ?: "qwen3vl_32b_minimax_h3-Q4_K_M.gguf")
          val vaeModelSrc = root.resolve("vae/minimax_h3_video_vae_fp16.safetensors")
          val audioVaeModelSrc = root.resolve("vae/minimax_h3_audio_vae_fp32.safetensors")
          for (file in listOf(modelSrc, llmModelSrc, vaeModelSrc, audioVaeModelSrc)) {
              if (!Files.isRegularFile(file)) {
                  System.err.println("✖ missing model file: $file")
                  exitProcess(1)
              }
          }

          val modelConfig = buildJsonObject {
              put("mode", "video")
              put("llmModelSrc", llmModelSrc.toString())
              put("vaeModelSrc", vaeModelSrc.toString())
              put("audioVaeModelSrc", audioVaeModelSrc.toString())
              put("device", "gpu")
              put("diffusion_fa", true)
              put("offload_to_cpu", System.getenv("H3_OFFLOAD_TO_CPU") != "0")
              put("stream_layers", System.getenv("H3_STREAM_LAYERS") == "1")
              for ((key, variable) in listOf(
                  "backend" to "H3_BACKEND",
                  "params_backend" to "H3_PARAMS_BACKEND",
                  "max_vram" to "H3_MAX_VRAM",
              )) {
                  System.getenv(variable)?.takeIf { it.isNotEmpty() }?.let { put(key, it) }
              }
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val loaded = client.models.load(
                  source = modelSrc.toString(),
                  modelType = "sdcpp-generation",
                  modelConfig = modelConfig,
              )
              val modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")
              try {
                  val run = client.media.video(
                      VideoStreamRequest(
                          modelId = modelId,
                          mode = VideoStreamRequestMode.TXT2VID,
                          prompt = System.getenv("PROMPT")?.takeIf { it.isNotEmpty() } ?: DEFAULT_PROMPT,
                          negative_prompt = "extra people, duplicate cup, malformed hands, cup " +
                              "fused to hand, text, subtitles, watermark, cartoon, " +
                              "CGI, blur, flicker, jitter, camera shake",
                          width = 960,
                          height = 544,
                          // H3 uses 17*k+5 frames; 124 frames at 24 FPS is
                          // approximately 5.17 seconds.
                          video_frames = System.getenv("FRAMES")?.takeIf { it.isNotEmpty() }?.toLong() ?: 124,
                          fps = 24.0,
                          steps = 8,
                          cfg_scale = 1.0,
                          seed = 11,
                      ),
                  )
                  run.events.collect { event ->
                      if (event.step != null && event.totalSteps != null) {
                          println("Step %.0f/%.0f".format(event.step, event.totalSteps))
                      }
                  }
                  val result = run.final.await()

                  val clip = result.data.firstOrNull() ?: error("Generation finished without an AVI result")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("Saved $outputPath ${result.stats}")
              } finally {
                  client.models.unload(modelId, clearStorage = false)
              }
          } finally {
              client.close()
          }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Image-to-video (MiniMax-H3)

The following script animates a first-frame image with MiniMax-H3. It uses the same diffusion, Qwen3-VL, and video VAE layout as H3 text-to-video; no CLIP-vision encoder is needed. The audio VAE is omitted for silent output, but you can add `audioVaeModelSrc` when loading the model to generate synchronized 32 kHz audio.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-img2vid-minimax-h3.js title="diffusion-img2vid-minimax-h3.js" lineNumbers
      import { loadModel, unloadModel, video } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      const modelsDir = process.argv[2];
      const initImagePath = process.argv[3];
      if (!modelsDir || !initImagePath) {
          console.error('✖ models directory and init image path are required');
          console.error('Usage: bun run bare:example dist/examples/diffusion-img2vid-minimax-h3.js ' +
              '<modelsDirectory> <initImagePath> [output.avi]');
          process.exit(1);
      }
      const outputPath = process.argv[4] || 'minimax-h3-img2vid.avi';
      const modelSrc = path.resolve(modelsDir, process.env['H3_MODEL'] || 'minimax_h3_fl2va_pruned-Q4_K.gguf');
      const llmModelSrc = path.resolve(modelsDir, process.env['H3_LLM'] || 'qwen3vl_32b_minimax_h3-Q4_K_M.gguf');
      const vaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_video_vae_fp16.safetensors');
      let modelId;
      try {
          for (const file of [modelSrc, llmModelSrc, vaeModelSrc, initImagePath])
              fs.accessSync(file);
          console.log('▸ Loading MiniMax-H3 model (diffusion + Qwen3-VL + video VAE)...');
          modelId = await loadModel({
              modelType: 'sdcpp-generation',
              modelSrc,
              modelConfig: {
                  mode: 'video',
                  llmModelSrc,
                  vaeModelSrc,
                  device: 'gpu',
                  diffusion_fa: true,
                  offload_to_cpu: process.env['H3_OFFLOAD_TO_CPU'] !== '0',
                  stream_layers: process.env['H3_STREAM_LAYERS'] === '1',
                  ...(process.env['H3_BACKEND'] && { backend: process.env['H3_BACKEND'] }),
                  ...(process.env['H3_PARAMS_BACKEND'] && { params_backend: process.env['H3_PARAMS_BACKEND'] }),
                  ...(process.env['H3_MAX_VRAM'] && { max_vram: process.env['H3_MAX_VRAM'] })
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          const init_image = new Uint8Array(fs.readFileSync(initImagePath));
          const prompt = process.env['PROMPT'] ||
              'The boat glides forward through the mist while the camera slowly pulls back, cinematic natural motion.';
          console.log(`▸ Generating video for: "${prompt}"`);
          const { progressStream, outputs, stats } = video({
              modelId,
              mode: 'img2vid',
              prompt,
              init_image,
              width: 864,
              height: 480,
              // H3 uses 17*k+5 frames and requires 24 FPS.
              video_frames: Number(process.env['FRAMES'] || 124),
              fps: 24,
              steps: 8,
              cfg_scale: 1,
              seed: 11
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          if (!buffers[0])
              throw new Error('Generation finished without an AVI result');
          fs.writeFileSync(outputPath, buffers[0]);
          console.log(`▸ Saved ${outputPath}`, await stats);
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          if (modelId)
              await unloadModel({ modelId, clearStorage: false });
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-img2vid-minimax-h3.ts title="diffusion-img2vid-minimax-h3.ts" lineNumbers
      import { loadModel, unloadModel, video } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      const modelsDir = process.argv[2]
      const initImagePath = process.argv[3]
      if (!modelsDir || !initImagePath) {
        console.error('✖ models directory and init image path are required')
        console.error(
          'Usage: bun run bare:example dist/examples/diffusion-img2vid-minimax-h3.js ' +
            '<modelsDirectory> <initImagePath> [output.avi]'
        )
        process.exit(1)
      }

      const outputPath = process.argv[4] || 'minimax-h3-img2vid.avi'
      const modelSrc = path.resolve(
        modelsDir,
        process.env['H3_MODEL'] || 'minimax_h3_fl2va_pruned-Q4_K.gguf'
      )
      const llmModelSrc = path.resolve(
        modelsDir,
        process.env['H3_LLM'] || 'qwen3vl_32b_minimax_h3-Q4_K_M.gguf'
      )
      const vaeModelSrc = path.resolve(modelsDir, 'vae/minimax_h3_video_vae_fp16.safetensors')

      let modelId: string | undefined
      try {
        for (const file of [modelSrc, llmModelSrc, vaeModelSrc, initImagePath]) fs.accessSync(file)

        console.log('▸ Loading MiniMax-H3 model (diffusion + Qwen3-VL + video VAE)...')
        modelId = await loadModel({
          modelType: 'sdcpp-generation',
          modelSrc,
          modelConfig: {
            mode: 'video',
            llmModelSrc,
            vaeModelSrc,
            device: 'gpu',
            diffusion_fa: true,
            offload_to_cpu: process.env['H3_OFFLOAD_TO_CPU'] !== '0',
            stream_layers: process.env['H3_STREAM_LAYERS'] === '1',
            ...(process.env['H3_BACKEND'] && { backend: process.env['H3_BACKEND'] }),
            ...(process.env['H3_PARAMS_BACKEND'] && { params_backend: process.env['H3_PARAMS_BACKEND'] }),
            ...(process.env['H3_MAX_VRAM'] && { max_vram: process.env['H3_MAX_VRAM'] })
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        const init_image = new Uint8Array(fs.readFileSync(initImagePath))
        const prompt =
          process.env['PROMPT'] ||
          'The boat glides forward through the mist while the camera slowly pulls back, cinematic natural motion.'
        console.log(`▸ Generating video for: "${prompt}"`)

        const { progressStream, outputs, stats } = video({
          modelId,
          mode: 'img2vid',
          prompt,
          init_image,
          width: 864,
          height: 480,
          // H3 uses 17*k+5 frames and requires 24 FPS.
          video_frames: Number(process.env['FRAMES'] || 124),
          fps: 24,
          steps: 8,
          cfg_scale: 1,
          seed: 11
        })

        for await (const { step, totalSteps } of progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const buffers = await outputs
        if (!buffers[0]) throw new Error('Generation finished without an AVI result')
        fs.writeFileSync(outputPath, buffers[0])
        console.log(`▸ Saved ${outputPath}`, await stats)
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        if (modelId) await unloadModel({ modelId, clearStorage: false })
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/diffusion_img2vid_minimax_h3.py title="diffusion_img2vid_minimax_h3.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-img2vid-minimax-h3.ts.

      Image-to-video with MiniMax-H3, using the same diffusion + Qwen3-VL + video
      VAE layout as H3 text-to-video; no CLIP-vision encoder is needed. The audio
      VAE is omitted for silent output -- add `audioVaeModelSrc` when loading the
      model to generate synchronized 32 kHz audio. The three files are read from a
      local directory you pass as argv, so nothing is downloaded.

      This example needs powerful hardware. `offload_to_cpu` stays on so the run
      fits on a single GPU; tune placement through the H3_* environment variables.

      TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes them
      on the way to the worker. Python calls the worker directly through
      `video_stream`, where `init_image` is already the encoded string, so the
      example encodes the file itself. The same iterator then carries progress, the
      finished clips and the closing stats, which TypeScript receives as three
      separate channels.

      RUN: python examples/diffusion_img2vid_minimax_h3.py <models-directory> <init-image> [output.avi]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import os
      import sys
      from pathlib import Path
      from typing import Any

      from tetherto.qvac_sdk import (
          Client,
          VideoStreamRequest,
          load_model,
          unload_model,
          video_stream,
      )

      DEFAULT_PROMPT = (
          "The boat glides forward through the mist while the camera slowly pulls "
          "back, cinematic natural motion."
      )


      async def main() -> int:
          models_dir = sys.argv[1] if len(sys.argv) > 1 else None
          init_image_path = Path(sys.argv[2]) if len(sys.argv) > 2 else None
          if not models_dir or not init_image_path:
              print("✖ models directory and init image path are required", file=sys.stderr)
              print(
                  "Usage: python examples/diffusion_img2vid_minimax_h3.py "
                  "<modelsDirectory> <initImagePath> [output.avi]",
                  file=sys.stderr,
              )
              return 1

          output_path = (
              Path(sys.argv[3]) if len(sys.argv) > 3 else Path("minimax-h3-img2vid.avi")
          )
          root = Path(models_dir).resolve()
          model_src = root / os.environ.get("H3_MODEL", "minimax_h3_fl2va_pruned-Q4_K.gguf")
          llm_model_src = root / os.environ.get(
              "H3_LLM", "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"
          )
          vae_model_src = root / "vae/minimax_h3_video_vae_fp16.safetensors"
          for file in (model_src, llm_model_src, vae_model_src, init_image_path):
              if not file.is_file():
                  print(f"✖ missing model file: {file}", file=sys.stderr)
                  return 1

          model_config: dict[str, Any] = {
              "mode": "video",
              "llmModelSrc": str(llm_model_src),
              "vaeModelSrc": str(vae_model_src),
              "device": "gpu",
              "diffusion_fa": True,
              "offload_to_cpu": os.environ.get("H3_OFFLOAD_TO_CPU") != "0",
              "stream_layers": os.environ.get("H3_STREAM_LAYERS") == "1",
          }
          for key, variable in (
              ("backend", "H3_BACKEND"),
              ("params_backend", "H3_PARAMS_BACKEND"),
              ("max_vram", "H3_MAX_VRAM"),
          ):
              value = os.environ.get(variable)
              if value:
                  model_config[key] = value

          model_id = None
          try:
              async with Client() as client:
                  t = client.transport
                  try:
                      print(
                          "▸ Loading MiniMax-H3 model "
                          "(diffusion + Qwen3-VL + video VAE)..."
                      )
                      model_id = await load_model(
                          t,
                          model_src=str(model_src),
                          model_type="sdcpp-generation",
                          model_config=model_config,
                      )
                      print(f"▸ Model loaded: {model_id}")

                      init_image = base64.b64encode(init_image_path.read_bytes()).decode(
                          "ascii"
                      )
                      prompt = os.environ.get("PROMPT") or DEFAULT_PROMPT
                      print(f'▸ Generating video for: "{prompt}"')

                      request = VideoStreamRequest.model_validate(
                          {
                              "type": "videoStream",
                              "modelId": model_id,
                              "mode": "img2vid",
                              "prompt": prompt,
                              "init_image": init_image,
                              "width": 864,
                              "height": 480,
                              # H3 uses 17*k+5 frames and requires 24 FPS.
                              "video_frames": int(os.environ.get("FRAMES") or 124),
                              "fps": 24,
                              "steps": 8,
                              "cfg_scale": 1,
                              "seed": 11,
                          }
                      )

                      clips: list[bytes] = []
                      stats = None
                      async for response in video_stream(t, request):
                          if response.step is not None and response.total_steps is not None:
                              print(f"▸ step {response.step:.0f}/{response.total_steps:.0f}")
                          if response.data is not None:
                              clips.append(base64.b64decode(response.data))
                          if response.done:
                              stats = response.stats

                      if not clips:
                          raise RuntimeError("Generation finished without an AVI result")
                      output_path.write_bytes(clips[0])
                      print(
                          f"▸ Saved {output_path}",
                          stats.model_dump(exclude_none=True) if stats else None,
                      )
                  finally:
                      if model_id:
                          await unload_model(t, model_id, clear_storage=False)
          except Exception as error:
              print("✖", error, file=sys.stderr)
              return 1

          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/DiffusionImg2vidMinimaxH3.kt title="DiffusionImg2vidMinimaxH3.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-img2vid-minimax-h3.ts.
      //
      // Image-to-video with MiniMax-H3, using the same diffusion + Qwen3-VL + video
      // VAE layout as H3 text-to-video; no CLIP-vision encoder is needed. The audio
      // VAE is omitted for silent output -- add `audioVaeModelSrc` when loading the
      // model to generate synchronized 32 kHz audio. The three files are read from a
      // local directory you pass as args, so nothing is downloaded.
      //
      // This example needs powerful hardware. `offload_to_cpu` stays on so the run
      // fits on a single GPU; tune placement through the H3_* environment variables.
      //
      // TypeScript's `video()` takes `init_image` as raw bytes and base64-encodes
      // them on the way to the worker. The typed `VideoStreamRequest` carries the
      // encoded string, so the example encodes the file with `java.util.Base64`. The
      // returned `QvacMediaRun` splits progress (`events` Flow) from the clips and
      // stats (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionImg2vidMinimaxH3 --args="<models-directory> <init-image> [output.avi]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequest
      import io.tether.qvac.sdk.generated.schema.VideoStreamRequestMode
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.media
      import io.tether.qvac.sdk.models
      import java.nio.file.Files
      import java.nio.file.Path
      import java.util.Base64
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      private const val DEFAULT_PROMPT =
          "The boat glides forward through the mist while the camera slowly pulls " +
              "back, cinematic natural motion."

      fun main(args: Array<String>): Unit = runBlocking {
          val modelsDir = args.getOrNull(0)
          val initImagePath = args.getOrNull(1)?.let { Path.of(it) }
          if (modelsDir.isNullOrEmpty() || initImagePath == null) {
              System.err.println("✖ models directory and init image path are required")
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionImg2vidMinimaxH3 " +
                      "--args=\"<modelsDirectory> <initImagePath> [output.avi]\"",
              )
              exitProcess(1)
          }

          val outputPath = Path.of(args.getOrNull(2) ?: "minimax-h3-img2vid.avi")
          val root = Path.of(modelsDir).toAbsolutePath().normalize()
          val modelSrc = root.resolve(System.getenv("H3_MODEL") ?: "minimax_h3_fl2va_pruned-Q4_K.gguf")
          val llmModelSrc = root.resolve(System.getenv("H3_LLM") ?: "qwen3vl_32b_minimax_h3-Q4_K_M.gguf")
          val vaeModelSrc = root.resolve("vae/minimax_h3_video_vae_fp16.safetensors")
          for (file in listOf(modelSrc, llmModelSrc, vaeModelSrc, initImagePath)) {
              if (!Files.isRegularFile(file)) {
                  System.err.println("✖ missing model file: $file")
                  exitProcess(1)
              }
          }

          val modelConfig = buildJsonObject {
              put("mode", "video")
              put("llmModelSrc", llmModelSrc.toString())
              put("vaeModelSrc", vaeModelSrc.toString())
              put("device", "gpu")
              put("diffusion_fa", true)
              put("offload_to_cpu", System.getenv("H3_OFFLOAD_TO_CPU") != "0")
              put("stream_layers", System.getenv("H3_STREAM_LAYERS") == "1")
              for ((key, variable) in listOf(
                  "backend" to "H3_BACKEND",
                  "params_backend" to "H3_PARAMS_BACKEND",
                  "max_vram" to "H3_MAX_VRAM",
              )) {
                  System.getenv(variable)?.takeIf { it.isNotEmpty() }?.let { put(key, it) }
              }
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading MiniMax-H3 model (diffusion + Qwen3-VL + video VAE)...")
              val loaded = client.models.load(
                  source = modelSrc.toString(),
                  modelType = "sdcpp-generation",
                  modelConfig = modelConfig,
              )
              val modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")
              try {
                  println("▸ Model loaded: $modelId")

                  val initImage = Base64.getEncoder().encodeToString(Files.readAllBytes(initImagePath))
                  val prompt = System.getenv("PROMPT")?.takeIf { it.isNotEmpty() } ?: DEFAULT_PROMPT
                  println("▸ Generating video for: \"$prompt\"")

                  val run = client.media.video(
                      VideoStreamRequest(
                          modelId = modelId,
                          mode = VideoStreamRequestMode.IMG2VID,
                          prompt = prompt,
                          init_image = initImage,
                          width = 864,
                          height = 480,
                          // H3 uses 17*k+5 frames and requires 24 FPS.
                          video_frames = System.getenv("FRAMES")?.takeIf { it.isNotEmpty() }?.toLong() ?: 124,
                          fps = 24.0,
                          steps = 8,
                          cfg_scale = 1.0,
                          seed = 11,
                      ),
                  )
                  run.events.collect { event ->
                      if (event.step != null && event.totalSteps != null) {
                          println("▸ step %.0f/%.0f".format(event.step, event.totalSteps))
                      }
                  }
                  val result = run.final.await()

                  val clip = result.data.firstOrNull() ?: error("Generation finished without an AVI result")
                  Files.write(outputPath, Base64.getDecoder().decode(clip))
                  println("▸ Saved $outputPath ${result.stats}")
              } finally {
                  client.models.unload(modelId, clearStorage = false)
              }
          } finally {
              client.close()
          }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and
  runnable. For instructions on how to run them, see the [JS/TS
  quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python
  quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin
  quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
