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

# Image generation (/sdk/v0.23/ai-capabilities/image-generation)



## Overview

Image 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"`. Then, provide a text `prompt` describing the image to generate.

For image-to-image, pass `init_image` as PNG or JPEG bytes in a `Uint8Array`. SD models denoise the source image; reference-editing models such as Qwen-Image-2.1 generate a new target from noise conditioned on your references. Pass `init_images` for ordered references on supported models. The two fields are mutually exclusive. `diffusion()` returns PNG images as `Uint8Array` buffers and preserves alpha when the model produces RGBA. Use `progressStream` to track generation progress.

For higher-resolution outputs, you can chain a Real-ESRGAN upscaler. Either attach it as a post-processing step at load time and trigger it per generation via `diffusion({ upscale })`, or load an ESRGAN model standalone with `modelConfig.mode: "upscale"` and call `upscale()` on any PNG/JPEG buffer — generated or not. Both paths return PNG `Uint8Array` buffers and accept a `repeats` option that compounds the scale factor across sequential passes.

## Functions

Use the following sequence of function calls:

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

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

## Models

Supported model families and their file layouts:

* **FLUX.2-klein**: split layout — diffusion model `*.gguf` + LLM text encoder `*.gguf` (via `llmModelSrc`) + VAE `*.safetensors` (via `vaeModelSrc`).
* **Qwen-Image-2.1** uses local diffusion weights as `modelSrc`, the matching Qwen3-VL encoder as `llmModelSrc`, and the 2.1 VAE as `vaeModelSrc`. Reference editing with the GGUF encoder also needs its vision projector as `projectionModelSrc`. QVAC provides no registry entry or model constant for these weights.
* **Ideogram 4**: split layout — diffusion model `*.gguf` + unconditional diffusion model `*.gguf` (via `uncondModelSrc`) + LLM text encoder `*.gguf` (via `llmModelSrc`) + VAE `*.safetensors` (via `vaeModelSrc`).
* **SD1.x, SD2.x**: single all-in-one `*.gguf` file. No companion files needed.
* **SDXL, SD3**: may require separate CLIP/T5 text encoder files (`clipLModelSrc`, `clipGModelSrc`, `t5XxlModelSrc`) in `modelConfig` depending on the model variant.
* **ESRGAN**: post-generation upscaler, `*.pth` format. Two ways to load:
  * **Paired with a diffusion model** — set `modelConfig.upscaler.model_src` at `loadModel()` time alongside the diffusion `modelSrc`.
  * **Standalone** — pass the ESRGAN model as the top-level `modelSrc` with `modelConfig.mode: "upscale"`.

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

<Callout type="info">
  **On upscaling:** ESRGAN can be used standalone via `modelConfig.mode: "upscale"` + `upscale()`, or paired with an RGB-output diffusion model via `diffusion({ upscale })`. ESRGAN accepts RGB only. Qwen-Image-2.1 produces RGBA and rejects post-generation upscaling; keep `upscale` omitted or `false`. Available constants: `REALESRGAN_X4PLUS_ANIME_6B`, `REALESRGAN_X4PLUS`.
</Callout>

## Examples

### FLUX.2-klein

The following script shows text-to-image generation using FLUX.2-klein with its split-layout model (separate diffusion model, LLM text encoder, and VAE):

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-flux2-klein.js title="diffusion-flux2-klein.js" lineNumbers
      import { loadModel, unloadModel, diffusion, FLUX_2_KLEIN_4B_Q4_0, FLUX_2_KLEIN_4B_VAE, QWEN3_4B_Q4_K_M } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // FLUX.2 [klein] uses a split-layout: separate diffusion model + LLM text encoder + VAE
      const diffusionModelSrc = process.argv[2] || FLUX_2_KLEIN_4B_Q4_0;
      const llmModelSrc = process.argv[3] || QWEN3_4B_Q4_K_M;
      const vaeModelSrc = process.argv[4] || FLUX_2_KLEIN_4B_VAE;
      const prompt = process.argv[5] || 'a futuristic city at sunset, photorealistic';
      const outputDir = process.argv[6] || '.';
      console.log('▸ Loading FLUX.2 [klein] split-layout model...');
      const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
              device: 'gpu',
              threads: 4,
              llmModelSrc,
              vaeModelSrc
          },
          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(`▸ Generating: "${prompt}"`);
      const { progressStream, outputs, stats } = diffusion({
          modelId,
          prompt,
          width: 512,
          height: 512,
          steps: 20,
          guidance: 3.5,
          cfg_scale: 1,
          seed: -1
      });
      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, `flux2_${i}.png`);
          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);
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/diffusion-flux2-klein.ts title="diffusion-flux2-klein.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        diffusion,
        FLUX_2_KLEIN_4B_Q4_0,
        FLUX_2_KLEIN_4B_VAE,
        QWEN3_4B_Q4_K_M
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // FLUX.2 [klein] uses a split-layout: separate diffusion model + LLM text encoder + VAE
      const diffusionModelSrc = process.argv[2] || FLUX_2_KLEIN_4B_Q4_0
      const llmModelSrc = process.argv[3] || QWEN3_4B_Q4_K_M
      const vaeModelSrc = process.argv[4] || FLUX_2_KLEIN_4B_VAE
      const prompt = process.argv[5] || 'a futuristic city at sunset, photorealistic'
      const outputDir = process.argv[6] || '.'

      console.log('▸ Loading FLUX.2 [klein] split-layout model...')

      const modelId = await loadModel({
        modelSrc: diffusionModelSrc,
        modelType: 'sdcpp-generation',
        modelConfig: {
          device: 'gpu',
          threads: 4,
          llmModelSrc,
          vaeModelSrc
        },
        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(`▸ Generating: "${prompt}"`)

      const { progressStream, outputs, stats } = diffusion({
        modelId,
        prompt,
        width: 512,
        height: 512,
        steps: 20,
        guidance: 3.5,
        cfg_scale: 1,
        seed: -1
      })

      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, `flux2_${i}.png`)
        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)
      ```
    </WrapCode>
  </Tab>

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

      Text-to-image with FLUX.2 [klein], which uses a split layout: the diffusion
      model, an LLM text encoder and a VAE are three separate files handed to one
      `load_model` call.

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

      RUN: python examples/diffusion_flux2_klein.py [diffusion-src] [llm-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,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          FLUX_2_KLEIN_4B_Q4_0,
          FLUX_2_KLEIN_4B_VAE,
          QWEN3_4B_Q4_K_M,
      )


      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:
          # FLUX.2 [klein] uses a split-layout: separate diffusion model + LLM text
          # encoder + VAE
          diffusion_model_src = sys.argv[1] if len(sys.argv) > 1 else FLUX_2_KLEIN_4B_Q4_0
          llm_model_src = sys.argv[2] if len(sys.argv) > 2 else QWEN3_4B_Q4_K_M
          vae_model_src = sys.argv[3] if len(sys.argv) > 3 else FLUX_2_KLEIN_4B_VAE
          prompt = (
              sys.argv[4]
              if len(sys.argv) > 4
              else "a futuristic city at sunset, photorealistic"
          )
          output_dir = Path(sys.argv[5]) if len(sys.argv) > 5 else Path(".")

          print("▸ Loading FLUX.2 [klein] split-layout model...")

          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={
                      "device": "gpu",
                      "threads": 4,
                      "llmModelSrc": llm_model_src,
                      "vaeModelSrc": vae_model_src,
                  },
                  on_progress=print_progress,
              )
              print(f"▸ Model loaded: {model_id}")

              print(f'▸ Generating: "{prompt}"')

              request = DiffusionStreamRequest.model_validate(
                  {
                      "type": "diffusionStream",
                      "modelId": model_id,
                      "prompt": prompt,
                      "width": 512,
                      "height": 512,
                      "steps": 20,
                      "guidance": 3.5,
                      "cfg_scale": 1,
                      "seed": -1,
                  }
              )

              images: list[bytes] = []
              stats = None
              async for response in diffusion_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:
                      images.append(base64.b64decode(response.data))
                  if response.done:
                      stats = response.stats

              for index, image in enumerate(images):
                  output_path = output_dir / f"flux2_{index}.png"
                  output_path.write_bytes(image)
                  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")
          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/DiffusionFlux2Klein.kt title="DiffusionFlux2Klein.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-flux2-klein.ts.
      //
      // Text-to-image with FLUX.2 [klein], which uses a split layout: the diffusion
      // model, an LLM text encoder and a VAE are three separate files handed to one
      // load call through `modelConfig`.
      //
      // `client.media.diffusion()` returns a `QvacMediaRun`, the same split TypeScript
      // gets: `events` is a `Flow` of typed `DiffusionStreamResponse` frames (per-step
      // progress), and `final` is a `Deferred` with every base64 image plus the
      // closing stats. The typed `DiffusionStreamRequest` overload carries the fields
      // the convenience overload lacks (`guidance`, `cfg_scale`).
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionFlux2Klein --args="[diffusion-src] [llm-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.DiffusionStreamRequest
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      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 {
          // FLUX.2 [klein] uses a split layout: separate diffusion model + LLM text
          // encoder + VAE
          val diffusionModelSrc = args.getOrNull(0) ?: Models.FLUX_2_KLEIN_4B_Q4_0.src
          val llmModelSrc = args.getOrNull(1) ?: Models.QWEN3_4B_Q4_K_M.src
          val vaeModelSrc = args.getOrNull(2) ?: Models.FLUX_2_KLEIN_4B_VAE.src
          val prompt = args.getOrNull(3) ?: "a futuristic city at sunset, photorealistic"
          val outputDir = Path.of(args.getOrNull(4) ?: ".")

          println("▸ Loading FLUX.2 [klein] split-layout model...")

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

              println("▸ Generating: \"$prompt\"")

              val run = client.media.diffusion(
                  DiffusionStreamRequest(
                      modelId = modelId,
                      prompt = prompt,
                      width = 512,
                      height = 512,
                      steps = 20,
                      guidance = 3.5,
                      cfg_scale = 1.0,
                      seed = -1,
                  ),
              )
              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, image ->
                  val outputPath = outputDir.resolve("flux2_$index.png")
                  Files.write(outputPath, Base64.getDecoder().decode(image))
                  println("▸ Saved $outputPath")
              }

              println("▸ 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>

### Qwen-Image-2.1

Qwen-Image-2.1 uses a split layout with a Qwen3-VL LLM text encoder (`llmModelSrc`), its vision projector (`projectionModelSrc`), and the 2.1 VAE (`vaeModelSrc`). Reference images are passed in order through `init_images`.

The following script combines subjects from two reference images and requests an RGBA image with a transparent background. Pass the paths of the two reference images (PNG or JPEG) as the first two arguments; an optional third argument overrides the default prompt:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-qwen-image-21.js title="diffusion-qwen-image-21.js" lineNumbers
      import { close, diffusion, loadModel, unloadModel } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // Combine two references into an RGBA image, with optional Qwen-Image-2.1-Turbo sampling.
      // Set QWEN_TURBO=1 and pass Turbo weights as the model argument, as a path or URL.
      // Use the pinned model revisions from the diffusion addon's Qwen-Image-2.1 downloader.
      // Model terms: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/d26bb61231c349cf6b7896fa83353113880e1ba3/LICENSE
      const turbo = process.env['QWEN_TURBO'] === '1';
      const HF = 'https://huggingface.co';
      const encoderRepo = `${HF}/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/f982a07559d4a2f6c8744d840bf6fccab30eea96`;
      const referencePathA = process.argv[2];
      const referencePathB = process.argv[3];
      const prompt = process.argv[4] ||
          'Place the subjects from both reference images side by side. Generate an RGBA image with a transparent background and no scenery.';
      const outputDir = process.argv[5] || '.';
      const diffusionModelSrc = process.argv[6] ||
          `${HF}/leejet/Qwen-Image-2.1-GGUF/resolve/cc11433936a06e9765f7c0c0b1f0436cfd2b9856/qwen_image_2.1-Q4_K.gguf`;
      const llmModelSrc = process.argv[7] || `${encoderRepo}/Qwen3VL-8B-Instruct-Q4_K_M.gguf`;
      const vaeModelSrc = process.argv[8] ||
          `${HF}/Comfy-Org/Qwen-Image-2.1/resolve/a8342359c61979b06a8dafb1a47991fe1f30e994/vae/qwen_image_2.1_vae_bf16.safetensors`;
      const projectionModelSrc = process.argv[9] || `${encoderRepo}/mmproj-Qwen3VL-8B-Instruct-F16.gguf`;
      const usage = 'Usage: node --import tsx examples/diffusion-qwen-image-21.ts <referenceA> <referenceB> [prompt] [outputDir] [model] [llm] [vae] [projector]';
      if (process.argv.includes('--help')) {
          console.log(usage);
          console.log('▸ Defaults download pinned Hugging Face weights. Model overrides accept paths or URLs.');
          console.log('▸ Turbo: set QWEN_TURBO=1 and pass your Turbo weights as the model argument.');
          console.log('▸ The default prompt combines both subjects on a transparent background.');
          process.exit(0);
      }
      if (!referencePathA || !referencePathB) {
          console.error('✖ two reference image paths are required');
          console.error(usage);
          process.exit(1);
      }
      if (turbo && !process.argv[6]) {
          console.error('✖ Pass the Turbo diffusion weights as the model argument, as a path or URL');
          process.exit(1);
      }
      function modelSource(source) {
          return /^https?:\/\//.test(source) ? source : path.resolve(source);
      }
      let modelId;
      try {
          const init_images = [referencePathA, referencePathB].map((file) => new Uint8Array(fs.readFileSync(file)));
          console.log('▸ Loading Qwen-Image-2.1 split-layout model...');
          modelId = await loadModel({
              modelSrc: modelSource(diffusionModelSrc),
              modelType: 'sdcpp-generation',
              modelConfig: {
                  llmModelSrc: modelSource(llmModelSrc),
                  vaeModelSrc: modelSource(vaeModelSrc),
                  projectionModelSrc: modelSource(projectionModelSrc),
                  flash_attn: true
              },
              onProgress: (progress) => {
                  const mb = (bytes) => (bytes / 1e6).toFixed(1);
                  const line = `▸ Downloading ${progress.percentage.toFixed(0)}% (${mb(progress.downloaded)}/${mb(progress.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (progress.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log(`▸ Generating from "${referencePathA}" and "${referencePathB}": "${prompt}"`);
          const { progressStream, outputs, stats } = diffusion({
              modelId,
              prompt,
              init_images,
              width: 512,
              height: 512,
              ...(!turbo && { steps: 30 }),
              cfg_scale: turbo ? 1 : 6,
              ...(turbo && {
                  // Official Turbo sample_sigmas plus the native terminal zero.
                  custom_sigmas: [1, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0]
              }),
              sampling_method: 'euler',
              seed: 42
          });
          for await (const { step, totalSteps } of progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const buffers = await outputs;
          if (buffers.length === 0)
              throw new Error('Qwen-Image-2.1 returned no image.');
          for (let i = 0; i < buffers.length; i++) {
              const outputPath = path.join(outputDir, `qwen_image_21${turbo ? '_turbo' : ''}_${i}.png`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('▸ Stats:', await stats);
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          try {
              if (modelId)
                  await unloadModel({ modelId, clearStorage: false });
          }
          catch (error) {
              console.error('✖ Unload failed:', error);
              process.exitCode = 1;
          }
          try {
              await close();
          }
          catch (error) {
              console.error('✖ Cleanup failed:', error);
              process.exitCode = 1;
          }
      }
      if (!process.exitCode)
          console.log('▸ Done');
      ```
    </WrapCode>
  </Tab>

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

      // Combine two references into an RGBA image, with optional Qwen-Image-2.1-Turbo sampling.
      // Set QWEN_TURBO=1 and pass Turbo weights as the model argument, as a path or URL.
      // Use the pinned model revisions from the diffusion addon's Qwen-Image-2.1 downloader.
      // Model terms: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/d26bb61231c349cf6b7896fa83353113880e1ba3/LICENSE

      const turbo = process.env['QWEN_TURBO'] === '1'
      const HF = 'https://huggingface.co'
      const encoderRepo = `${HF}/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/f982a07559d4a2f6c8744d840bf6fccab30eea96`
      const referencePathA = process.argv[2]
      const referencePathB = process.argv[3]
      const prompt =
        process.argv[4] ||
        'Place the subjects from both reference images side by side. Generate an RGBA image with a transparent background and no scenery.'
      const outputDir = process.argv[5] || '.'
      const diffusionModelSrc =
        process.argv[6] ||
        `${HF}/leejet/Qwen-Image-2.1-GGUF/resolve/cc11433936a06e9765f7c0c0b1f0436cfd2b9856/qwen_image_2.1-Q4_K.gguf`
      const llmModelSrc = process.argv[7] || `${encoderRepo}/Qwen3VL-8B-Instruct-Q4_K_M.gguf`
      const vaeModelSrc =
        process.argv[8] ||
        `${HF}/Comfy-Org/Qwen-Image-2.1/resolve/a8342359c61979b06a8dafb1a47991fe1f30e994/vae/qwen_image_2.1_vae_bf16.safetensors`
      const projectionModelSrc = process.argv[9] || `${encoderRepo}/mmproj-Qwen3VL-8B-Instruct-F16.gguf`

      const usage =
        'Usage: node --import tsx examples/diffusion-qwen-image-21.ts <referenceA> <referenceB> [prompt] [outputDir] [model] [llm] [vae] [projector]'

      if (process.argv.includes('--help')) {
        console.log(usage)
        console.log(
          '▸ Defaults download pinned Hugging Face weights. Model overrides accept paths or URLs.'
        )
        console.log('▸ Turbo: set QWEN_TURBO=1 and pass your Turbo weights as the model argument.')
        console.log('▸ The default prompt combines both subjects on a transparent background.')
        process.exit(0)
      }

      if (!referencePathA || !referencePathB) {
        console.error('✖ two reference image paths are required')
        console.error(usage)
        process.exit(1)
      }

      if (turbo && !process.argv[6]) {
        console.error('✖ Pass the Turbo diffusion weights as the model argument, as a path or URL')
        process.exit(1)
      }

      function modelSource(source: string) {
        return /^https?:\/\//.test(source) ? source : path.resolve(source)
      }

      let modelId: string | undefined

      try {
        const init_images = [referencePathA, referencePathB].map(
          (file) => new Uint8Array(fs.readFileSync(file))
        )

        console.log('▸ Loading Qwen-Image-2.1 split-layout model...')
        modelId = await loadModel({
          modelSrc: modelSource(diffusionModelSrc),
          modelType: 'sdcpp-generation',
          modelConfig: {
            llmModelSrc: modelSource(llmModelSrc),
            vaeModelSrc: modelSource(vaeModelSrc),
            projectionModelSrc: modelSource(projectionModelSrc),
            flash_attn: true
          },
          onProgress: (progress) => {
            const mb = (bytes: number) => (bytes / 1e6).toFixed(1)
            const line = `▸ Downloading ${progress.percentage.toFixed(0)}% (${mb(progress.downloaded)}/${mb(progress.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (progress.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)
        console.log(`▸ Generating from "${referencePathA}" and "${referencePathB}": "${prompt}"`)

        const { progressStream, outputs, stats } = diffusion({
          modelId,
          prompt,
          init_images,
          width: 512,
          height: 512,
          ...(!turbo && { steps: 30 }),
          cfg_scale: turbo ? 1 : 6,
          ...(turbo && {
            // Official Turbo sample_sigmas plus the native terminal zero.
            custom_sigmas: [1, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0]
          }),
          sampling_method: 'euler',
          seed: 42
        })

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

        const buffers = await outputs
        if (buffers.length === 0) throw new Error('Qwen-Image-2.1 returned no image.')
        for (let i = 0; i < buffers.length; i++) {
          const outputPath = path.join(outputDir, `qwen_image_21${turbo ? '_turbo' : ''}_${i}.png`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

        console.log('▸ Stats:', await stats)
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        try {
          if (modelId) await unloadModel({ modelId, clearStorage: false })
        } catch (error) {
          console.error('✖ Unload failed:', error)
          process.exitCode = 1
        }
        try {
          await close()
        } catch (error) {
          console.error('✖ Cleanup failed:', error)
          process.exitCode = 1
        }
      }

      if (!process.exitCode) console.log('▸ Done')
      ```
    </WrapCode>
  </Tab>

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

      Qwen-Image-2.1 in split layout: a diffusion model, a Qwen3-VL LLM text
      encoder, its vision projector and the 2.1 VAE, all handed to one `load_model`
      call. Two reference images go in order through `init_images`, and the prompt
      asks for an RGBA image with a transparent background.

      TypeScript's `diffusion()` takes each reference as raw bytes and base64-encodes
      them on the way to the worker. Python calls the worker directly through
      `diffusion_stream`, where `init_images` is already a list of encoded strings,
      so the example encodes the files itself. The same iterator then carries
      progress, the finished images and the closing stats, which TypeScript receives
      as three separate channels.

      The defaults download pinned Hugging Face weights. Model overrides accept local
      paths or URLs. Set QWEN_TURBO=1 and pass Turbo weights as the model argument
      to use the fixed eight-step schedule with CFG 1.
      Model terms: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/d26bb61231c349cf6b7896fa83353113880e1ba3/LICENSE

      RUN: python examples/diffusion_qwen_image_21.py <reference-a> <reference-b> [prompt] [output-dir] [model] [llm] [vae] [projector]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import contextlib
      import os
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )

      HF = "https://huggingface.co"
      ENCODER_REPO = f"{HF}/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/f982a07559d4a2f6c8744d840bf6fccab30eea96"
      DIFFUSION_MODEL_SRC = (
          f"{HF}/leejet/Qwen-Image-2.1-GGUF/resolve/"
          "cc11433936a06e9765f7c0c0b1f0436cfd2b9856/qwen_image_2.1-Q4_K.gguf"
      )
      LLM_MODEL_SRC = f"{ENCODER_REPO}/Qwen3VL-8B-Instruct-Q4_K_M.gguf"
      VAE_MODEL_SRC = (
          f"{HF}/Comfy-Org/Qwen-Image-2.1/resolve/"
          "a8342359c61979b06a8dafb1a47991fe1f30e994/vae/qwen_image_2.1_vae_bf16.safetensors"
      )
      PROJECTION_MODEL_SRC = f"{ENCODER_REPO}/mmproj-Qwen3VL-8B-Instruct-F16.gguf"
      DEFAULT_PROMPT = (
          "Place the subjects from both reference images side by side. "
          "Generate an RGBA image with a transparent background and no scenery."
      )
      USAGE = (
          "Usage: python examples/diffusion_qwen_image_21.py <referenceA> <referenceB> "
          "[prompt] [outputDir] [model] [llm] [vae] [projector]"
      )


      def model_source(source: str) -> str:
          """Pass URLs through; resolve local paths to absolute ones."""
          if source.startswith(("http://", "https://")):
              return source
          return str(Path(source).resolve())


      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:
          if "--help" in sys.argv:
              print(USAGE)
              print(
                  "▸ Defaults download pinned Hugging Face weights. Model overrides accept paths or URLs."
              )
              print(
                  "▸ Turbo: set QWEN_TURBO=1 and pass your Turbo weights as the model argument."
              )
              print(
                  "▸ The default prompt combines both subjects on a transparent background."
              )
              return 0

          turbo = os.environ.get("QWEN_TURBO") == "1"
          reference_path_a = sys.argv[1] if len(sys.argv) > 1 else None
          reference_path_b = sys.argv[2] if len(sys.argv) > 2 else None
          prompt = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else DEFAULT_PROMPT
          output_dir = Path(sys.argv[4]) if len(sys.argv) > 4 else Path(".")
          diffusion_model_src = (
              sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else DIFFUSION_MODEL_SRC
          )
          llm_model_src = sys.argv[6] if len(sys.argv) > 6 else LLM_MODEL_SRC
          vae_model_src = sys.argv[7] if len(sys.argv) > 7 else VAE_MODEL_SRC
          projection_model_src = sys.argv[8] if len(sys.argv) > 8 else PROJECTION_MODEL_SRC

          if not reference_path_a or not reference_path_b:
              print("✖ two reference image paths are required", file=sys.stderr)
              print(USAGE, file=sys.stderr)
              return 1

          if turbo and (len(sys.argv) <= 5 or not sys.argv[5]):
              print(
                  "✖ Pass the Turbo diffusion weights as the model argument, as a path or URL",
                  file=sys.stderr,
              )
              return 1

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

              try:
                  init_images = [
                      base64.b64encode(Path(path).read_bytes()).decode("ascii")
                      for path in (reference_path_a, reference_path_b)
                  ]

                  print("▸ Loading Qwen-Image-2.1 split-layout model...")
                  model_id = await load_model(
                      t,
                      model_src=model_source(diffusion_model_src),
                      model_type="sdcpp-generation",
                      model_config={
                          "llmModelSrc": model_source(llm_model_src),
                          "vaeModelSrc": model_source(vae_model_src),
                          "projectionModelSrc": model_source(projection_model_src),
                          "flash_attn": True,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")
                  print(
                      f'▸ Generating from "{reference_path_a}" and "{reference_path_b}": "{prompt}"'
                  )

                  request = DiffusionStreamRequest.model_validate(
                      {
                          "type": "diffusionStream",
                          "modelId": model_id,
                          "prompt": prompt,
                          "init_images": init_images,
                          "width": 512,
                          "height": 512,
                          **({} if turbo else {"steps": 30}),
                          "cfg_scale": 1 if turbo else 6,
                          **(
                              {
                                  "custom_sigmas": [
                                      1,
                                      0.978453,
                                      0.95418,
                                      0.926626,
                                      0.89508,
                                      0.845148,
                                      0.704534,
                                      0.414568,
                                      0,
                                  ]
                              }
                              if turbo
                              else {}
                          ),
                          "sampling_method": "euler",
                          "seed": 42,
                      }
                  )

                  images: list[bytes] = []
                  stats = None
                  async for response in diffusion_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:
                          images.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  if not images:
                      raise RuntimeError("Qwen-Image-2.1 returned no image.")
                  for index, image in enumerate(images):
                      output_path = (
                          output_dir / f"qwen_image_21{'_turbo' if turbo else ''}_{index}.png"
                      )
                      output_path.write_bytes(image)
                      print(f"▸ Saved {output_path}")

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

                  await unload_model(t, model_id)
                  model_id = None
                  print("▸ Done")
              except Exception as error:
                  if model_id is not None:
                      # Preserve the original error.
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
                  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/DiffusionQwenImage21.kt title="DiffusionQwenImage21.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-qwen-image-21.ts.
      //
      // Qwen-Image-2.1 in split layout: a diffusion model, a Qwen3-VL LLM text
      // encoder, its vision projector and the 2.1 VAE, all handed to one load call
      // through `modelConfig`. Two reference images go in order through
      // `init_images`, and the prompt asks for an RGBA image with a transparent
      // background.
      //
      // TypeScript's `diffusion()` takes each reference as raw bytes and base64-encodes
      // them on the way to the worker. The typed `DiffusionStreamRequest` carries the
      // encoded strings, so the example encodes the files with `java.util.Base64`.
      // `sampling_method` is a generated enum (`DiffusionStreamRequestSamplingMethod`),
      // so a misspelled sampler fails at compile time instead of at the worker. The
      // returned `QvacMediaRun` splits progress (`events` Flow) from the images and
      // stats (`final` Deferred), as TypeScript does. The Turbo fields are nullable
      // constructor parameters, so `steps = null` leaves the step count out of the
      // request, as TypeScript's conditional spread does.
      //
      // The defaults download pinned Hugging Face weights. Model overrides accept local
      // paths or URLs. Set QWEN_TURBO=1 and pass Turbo weights as the model argument
      // to use the fixed eight-step schedule with CFG 1.
      // Model terms: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/d26bb61231c349cf6b7896fa83353113880e1ba3/LICENSE
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionQwenImage21 --args="<reference-a> <reference-b> [prompt] [output-dir] [model] [llm] [vae] [projector]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequest
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequestSamplingMethod
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      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

      private const val HF = "https://huggingface.co"
      private const val ENCODER_REPO = "$HF/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/f982a07559d4a2f6c8744d840bf6fccab30eea96"
      private const val DIFFUSION_MODEL_SRC =
          "$HF/leejet/Qwen-Image-2.1-GGUF/resolve/cc11433936a06e9765f7c0c0b1f0436cfd2b9856/qwen_image_2.1-Q4_K.gguf"
      private const val LLM_MODEL_SRC = "$ENCODER_REPO/Qwen3VL-8B-Instruct-Q4_K_M.gguf"
      private const val VAE_MODEL_SRC =
          "$HF/Comfy-Org/Qwen-Image-2.1/resolve/" +
              "a8342359c61979b06a8dafb1a47991fe1f30e994/vae/qwen_image_2.1_vae_bf16.safetensors"
      private const val PROJECTION_MODEL_SRC = "$ENCODER_REPO/mmproj-Qwen3VL-8B-Instruct-F16.gguf"
      private const val DEFAULT_PROMPT =
          "Place the subjects from both reference images side by side. " +
              "Generate an RGBA image with a transparent background and no scenery."
      // Official Turbo sample_sigmas plus the native terminal zero.
      private val TURBO_SIGMAS = listOf(1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0.0)
      private const val USAGE =
          "Usage: ./gradlew -p examples run -Pexample=DiffusionQwenImage21 --args=\"<referenceA> <referenceB> " +
              "[prompt] [outputDir] [model] [llm] [vae] [projector]\""

      /** Pass URLs through; resolve local paths to absolute ones. */
      private fun modelSource(source: String): String =
          if (source.startsWith("http://") || source.startsWith("https://")) {
              source
          } else {
              Path.of(source).toAbsolutePath().normalize().toString()
          }

      fun main(args: Array<String>): Unit = runBlocking {
          if ("--help" in args) {
              println(USAGE)
              println("▸ Defaults download pinned Hugging Face weights. Model overrides accept paths or URLs.")
              println("▸ Turbo: set QWEN_TURBO=1 and pass your Turbo weights as the model argument.")
              println("▸ The default prompt combines both subjects on a transparent background.")
              return@runBlocking
          }

          val turbo = System.getenv("QWEN_TURBO") == "1"
          val referencePathA = args.getOrNull(0)
          val referencePathB = args.getOrNull(1)
          val prompt = args.getOrNull(2)?.takeIf { it.isNotEmpty() } ?: DEFAULT_PROMPT
          val outputDir = Path.of(args.getOrNull(3) ?: ".")
          val diffusionModelSrc = args.getOrNull(4)?.takeIf { it.isNotEmpty() } ?: DIFFUSION_MODEL_SRC
          val llmModelSrc = args.getOrNull(5) ?: LLM_MODEL_SRC
          val vaeModelSrc = args.getOrNull(6) ?: VAE_MODEL_SRC
          val projectionModelSrc = args.getOrNull(7) ?: PROJECTION_MODEL_SRC

          if (referencePathA.isNullOrEmpty() || referencePathB.isNullOrEmpty()) {
              System.err.println("✖ two reference image paths are required")
              System.err.println(USAGE)
              exitProcess(1)
          }

          if (turbo && args.getOrNull(4).isNullOrEmpty()) {
              System.err.println("✖ Pass the Turbo diffusion weights as the model argument, as a path or URL")
              exitProcess(1)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val initImages = listOf(referencePathA, referencePathB).map { path ->
                  Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(path)))
              }

              println("▸ Loading Qwen-Image-2.1 split-layout model...")
              val modelId = client.loadWithProgress(
                  source = modelSource(diffusionModelSrc),
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("llmModelSrc", modelSource(llmModelSrc))
                      put("vaeModelSrc", modelSource(vaeModelSrc))
                      put("projectionModelSrc", modelSource(projectionModelSrc))
                      put("flash_attn", true)
                  },
              )
              println("▸ Model loaded: $modelId")

              try {
                  println("▸ Generating from \"$referencePathA\" and \"$referencePathB\": \"$prompt\"")

                  val run = client.media.diffusion(
                      DiffusionStreamRequest(
                          modelId = modelId,
                          prompt = prompt,
                          init_images = initImages,
                          width = 512,
                          height = 512,
                          steps = if (turbo) null else 30,
                          cfg_scale = if (turbo) 1.0 else 6.0,
                          custom_sigmas = if (turbo) TURBO_SIGMAS else null,
                          sampling_method = DiffusionStreamRequestSamplingMethod.EULER,
                          seed = 42,
                      ),
                  )
                  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()

                  check(result.data.isNotEmpty()) { "Qwen-Image-2.1 returned no image." }
                  result.data.forEachIndexed { index, image ->
                      val outputPath = outputDir.resolve("qwen_image_21${if (turbo) "_turbo" else ""}_$index.png")
                      Files.write(outputPath, Base64.getDecoder().decode(image))
                      println("▸ Saved $outputPath")
                  }

                  println("▸ Stats: ${result.stats}")
              } catch (error: Exception) {
                  // Preserve the original error.
                  runCatching { client.models.unload(modelId) }
                  throw error
              }

              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>

### Ideogram 4

Ideogram 4 uses a split layout with an extra **unconditional diffusion model** (`uncondModelSrc`) alongside the Qwen3-VL LLM text encoder (`llmModelSrc`) and VAE (`vaeModelSrc`). Unlike the other families, its `prompt` must be a **JSON-serialized structured caption** — an object with a `high_level_description`, a `style_description`, and a `compositional_deconstruction` that lays out each element with an explicit bounding box (`bbox`) and, for text elements, the literal `text` to render. Plain-text prompts produce degenerate or placeholder output.

<Callout type="warn">
  Pass the structured caption serialized, not as an object: `JSON.stringify(...)` in JavaScript and TypeScript, or `json.dumps(..., separators=(",", ":"))` in Python, whose default spacing the model does not expect. The bounding boxes are expressed in the target canvas coordinate space (`[x0, y0, x1, y1]`), so keep them consistent with the requested `width`/`height`. Failure to abide by the JSON format specified within the examples, or adding NSFW prompts, will result in censored image output.
</Callout>

The following script loads Ideogram 4 in split-layout (diffusion model + unconditional model + LLM text encoder + VAE) and generates from a structured caption:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-ideogram.js title="diffusion-ideogram.js" lineNumbers
      import { diffusion, loadModel, unloadModel } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      const diffusionModelSrc = process.argv[2] ||
          'https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4-Q4_0.gguf';
      const uncondModelSrc = process.argv[3] ||
          'https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4_uncond-Q4_0.gguf';
      const llmModelSrc = process.argv[4] ||
          'https://huggingface.co/unsloth/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3-VL-8B-Instruct-Q4_K_M.gguf';
      const vaeModelSrc = process.argv[5] ||
          'https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors';
      const outputDir = process.argv[6] || '.';
      function formatMb(bytes) {
          return (bytes / 1e6).toFixed(1);
      }
      // Ideogram 4 expects a JSON-serialized structured caption with explicit
      // bounding boxes. Plain-text prompts produce degenerate or placeholder output.
      const structuredPrompt = {
          high_level_description: 'A bright product photo of one yellow coffee mug on a clean office desk with a tiny readable label that says IDEO.',
          style_description: {
              aesthetics: 'simple product photography, clean bright office desk, minimal composition',
              lighting: 'soft studio light with gentle shadows',
              photo: 'sharp focus, crisp readable label text',
              medium: 'product photo',
              color_palette: ['#FFD54A', '#FFFFFF', '#111111', '#7EC8E3']
          },
          compositional_deconstruction: {
              canvas: 'Square canvas, upright orientation. All text is horizontal and readable.',
              background: 'Clean white office desk with a soft blue background gradient.',
              elements: [
                  {
                      type: 'obj',
                      bbox: [230, 260, 800, 740],
                      desc: 'Exactly one matte yellow ceramic coffee mug centered on the desk.'
                  },
                  {
                      type: 'text',
                      bbox: [510, 360, 620, 640],
                      text: 'IDEO',
                      desc: 'Small black label printed horizontally on the mug.'
                  }
              ]
          }
      };
      if (process.argv.includes('--help')) {
          console.log('Usage: tsx examples/diffusion-ideogram.ts [model] [uncond] [llm] [vae] [output-dir]');
          console.log('▸ Defaults use the four Hugging Face model URLs supported by the diffusion addon.');
          process.exit(0);
      }
      let modelId;
      try {
          console.log('▸ Loading Ideogram 4 split-layout model...');
          modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  device: 'gpu',
                  threads: 4,
                  diffusion_fa: true,
                  offload_to_cpu: true,
                  llmModelSrc,
                  vaeModelSrc,
                  uncondModelSrc
              },
              onProgress: (progress) => {
                  const line = `▸ Downloading ${progress.percentage.toFixed(0)}% (${formatMb(progress.downloaded)}/${formatMb(progress.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (progress.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          const { progressStream, outputs, stats } = diffusion({
              modelId,
              prompt: JSON.stringify(structuredPrompt),
              width: 768,
              height: 768,
              steps: 16,
              cfg_scale: 7,
              seed: 42
          });
          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, `ideogram_${i}.png`);
              fs.writeFileSync(outputPath, buffers[i]);
              console.log(`▸ Saved ${outputPath}`);
          }
          console.log('▸ Stats:', await stats);
          await unloadModel({ modelId, clearStorage: false });
          modelId = undefined;
          console.log('▸ Done');
          process.exit(0);
      }
      catch (error) {
          if (modelId) {
              try {
                  await unloadModel({ modelId, clearStorage: false });
              }
              catch {
                  // Preserve the original error.
              }
          }
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

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

      const diffusionModelSrc =
        process.argv[2] ||
        'https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4-Q4_0.gguf'
      const uncondModelSrc =
        process.argv[3] ||
        'https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4_uncond-Q4_0.gguf'
      const llmModelSrc =
        process.argv[4] ||
        'https://huggingface.co/unsloth/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3-VL-8B-Instruct-Q4_K_M.gguf'
      const vaeModelSrc =
        process.argv[5] ||
        'https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors'
      const outputDir = process.argv[6] || '.'

      function formatMb(bytes: number) {
        return (bytes / 1e6).toFixed(1)
      }

      // Ideogram 4 expects a JSON-serialized structured caption with explicit
      // bounding boxes. Plain-text prompts produce degenerate or placeholder output.
      const structuredPrompt = {
        high_level_description:
          'A bright product photo of one yellow coffee mug on a clean office desk with a tiny readable label that says IDEO.',
        style_description: {
          aesthetics: 'simple product photography, clean bright office desk, minimal composition',
          lighting: 'soft studio light with gentle shadows',
          photo: 'sharp focus, crisp readable label text',
          medium: 'product photo',
          color_palette: ['#FFD54A', '#FFFFFF', '#111111', '#7EC8E3']
        },
        compositional_deconstruction: {
          canvas: 'Square canvas, upright orientation. All text is horizontal and readable.',
          background: 'Clean white office desk with a soft blue background gradient.',
          elements: [
            {
              type: 'obj',
              bbox: [230, 260, 800, 740],
              desc: 'Exactly one matte yellow ceramic coffee mug centered on the desk.'
            },
            {
              type: 'text',
              bbox: [510, 360, 620, 640],
              text: 'IDEO',
              desc: 'Small black label printed horizontally on the mug.'
            }
          ]
        }
      }

      if (process.argv.includes('--help')) {
        console.log('Usage: tsx examples/diffusion-ideogram.ts [model] [uncond] [llm] [vae] [output-dir]')
        console.log('▸ Defaults use the four Hugging Face model URLs supported by the diffusion addon.')
        process.exit(0)
      }

      let modelId: string | undefined

      try {
        console.log('▸ Loading Ideogram 4 split-layout model...')
        modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            device: 'gpu',
            threads: 4,
            diffusion_fa: true,
            offload_to_cpu: true,
            llmModelSrc,
            vaeModelSrc,
            uncondModelSrc
          },
          onProgress: (progress) => {
            const line = `▸ Downloading ${progress.percentage.toFixed(0)}% (${formatMb(progress.downloaded)}/${formatMb(progress.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (progress.percentage >= 100) process.stderr.write('\n')
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)

        const { progressStream, outputs, stats } = diffusion({
          modelId,
          prompt: JSON.stringify(structuredPrompt),
          width: 768,
          height: 768,
          steps: 16,
          cfg_scale: 7,
          seed: 42
        })

        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, `ideogram_${i}.png`)
          fs.writeFileSync(outputPath, buffers[i]!)
          console.log(`▸ Saved ${outputPath}`)
        }

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

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

      Ideogram 4 in split layout: a diffusion model, an unconditional diffusion
      model, a Qwen3-VL LLM text encoder and a VAE, all handed to one `load_model`
      call. Its `prompt` is not prose but a serialized structured caption, with a
      bounding box per element in the target canvas coordinate space.

      Two Python-specific details. `json.dumps` pads with spaces by default while
      `JSON.stringify` emits none, so `separators` keeps the serialized caption
      byte-identical to what the TypeScript example sends -- the model is sensitive
      to this format. And `diffusion_stream` is one iterator where TypeScript's
      `diffusion()` returns separate progress, output and stats channels, so the
      loop below splits them apart.

      RUN: python examples/diffusion_ideogram.py [model] [uncond] [llm] [vae] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import contextlib
      import json
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )

      DIFFUSION_MODEL_SRC = (
          "https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4-Q4_0.gguf"
      )
      UNCOND_MODEL_SRC = "https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4_uncond-Q4_0.gguf"
      LLM_MODEL_SRC = "https://huggingface.co/unsloth/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3-VL-8B-Instruct-Q4_K_M.gguf"
      VAE_MODEL_SRC = "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors"

      # Ideogram 4 expects a JSON-serialized structured caption with explicit
      # bounding boxes. Plain-text prompts produce degenerate or placeholder output.
      STRUCTURED_PROMPT = {
          "high_level_description": "A bright product photo of one yellow coffee mug on a clean office desk with a tiny readable label that says IDEO.",
          "style_description": {
              "aesthetics": "simple product photography, clean bright office desk, minimal composition",
              "lighting": "soft studio light with gentle shadows",
              "photo": "sharp focus, crisp readable label text",
              "medium": "product photo",
              "color_palette": ["#FFD54A", "#FFFFFF", "#111111", "#7EC8E3"],
          },
          "compositional_deconstruction": {
              "canvas": "Square canvas, upright orientation. All text is horizontal and readable.",
              "background": "Clean white office desk with a soft blue background gradient.",
              "elements": [
                  {
                      "type": "obj",
                      "bbox": [230, 260, 800, 740],
                      "desc": "Exactly one matte yellow ceramic coffee mug centered on the desk.",
                  },
                  {
                      "type": "text",
                      "bbox": [510, 360, 620, 640],
                      "text": "IDEO",
                      "desc": "Small black label printed horizontally on the mug.",
                  },
              ],
          },
      }


      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:
          if "--help" in sys.argv:
              print(
                  "Usage: python examples/diffusion_ideogram.py "
                  "[model] [uncond] [llm] [vae] [output-dir]"
              )
              print(
                  "▸ Defaults use the four Hugging Face model URLs supported by the "
                  "diffusion addon."
              )
              return 0

          diffusion_model_src = sys.argv[1] if len(sys.argv) > 1 else DIFFUSION_MODEL_SRC
          uncond_model_src = sys.argv[2] if len(sys.argv) > 2 else UNCOND_MODEL_SRC
          llm_model_src = sys.argv[3] if len(sys.argv) > 3 else LLM_MODEL_SRC
          vae_model_src = sys.argv[4] if len(sys.argv) > 4 else VAE_MODEL_SRC
          output_dir = Path(sys.argv[5]) if len(sys.argv) > 5 else Path(".")

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

              try:
                  print("▸ Loading Ideogram 4 split-layout model...")
                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "device": "gpu",
                          "threads": 4,
                          "diffusion_fa": True,
                          "offload_to_cpu": True,
                          "llmModelSrc": llm_model_src,
                          "vaeModelSrc": vae_model_src,
                          "uncondModelSrc": uncond_model_src,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  request = DiffusionStreamRequest.model_validate(
                      {
                          "type": "diffusionStream",
                          "modelId": model_id,
                          # Compact separators match JSON.stringify; the model is
                          # sensitive to the caption's exact format.
                          "prompt": json.dumps(STRUCTURED_PROMPT, separators=(",", ":")),
                          "width": 768,
                          "height": 768,
                          "steps": 16,
                          "cfg_scale": 7,
                          "seed": 42,
                      }
                  )

                  images: list[bytes] = []
                  stats = None
                  async for response in diffusion_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:
                          images.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, image in enumerate(images):
                      output_path = output_dir / f"ideogram_{index}.png"
                      output_path.write_bytes(image)
                      print(f"▸ Saved {output_path}")

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

                  await unload_model(t, model_id)
                  model_id = None
                  print("▸ Done")
              except Exception as error:
                  if model_id is not None:
                      # Preserve the original error.
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
                  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/DiffusionIdeogram.kt title="DiffusionIdeogram.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-ideogram.ts.
      //
      // Ideogram 4 in split layout: a diffusion model, an unconditional diffusion
      // model, a Qwen3-VL LLM text encoder and a VAE, all handed to one load call
      // through `modelConfig`. Its `prompt` is not prose but a serialized structured
      // caption, with a bounding box per element in the target canvas coordinate
      // space.
      //
      // The caption is built with `buildJsonObject`, which keeps insertion order, and
      // `JsonObject.toString()` emits compact JSON byte-identical to what
      // `JSON.stringify` sends in TypeScript -- the model is sensitive to this
      // format. The returned `QvacMediaRun` splits progress (`events` Flow) from the
      // images and stats (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionIdeogram --args="[model] [uncond] [llm] [vae] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequest
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      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.add
      import kotlinx.serialization.json.addJsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put
      import kotlinx.serialization.json.putJsonArray
      import kotlinx.serialization.json.putJsonObject

      private const val DIFFUSION_MODEL_SRC =
          "https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4-Q4_0.gguf"
      private const val UNCOND_MODEL_SRC =
          "https://huggingface.co/leejet/ideogram-4-GGUF/resolve/main/ideogram4_uncond-Q4_0.gguf"
      private const val LLM_MODEL_SRC =
          "https://huggingface.co/unsloth/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3-VL-8B-Instruct-Q4_K_M.gguf"
      private const val VAE_MODEL_SRC =
          "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors"

      // Ideogram 4 expects a JSON-serialized structured caption with explicit
      // bounding boxes. Plain-text prompts produce degenerate or placeholder output.
      private val STRUCTURED_PROMPT = buildJsonObject {
          put(
              "high_level_description",
              "A bright product photo of one yellow coffee mug on a clean office desk " +
                  "with a tiny readable label that says IDEO.",
          )
          putJsonObject("style_description") {
              put("aesthetics", "simple product photography, clean bright office desk, minimal composition")
              put("lighting", "soft studio light with gentle shadows")
              put("photo", "sharp focus, crisp readable label text")
              put("medium", "product photo")
              putJsonArray("color_palette") {
                  add("#FFD54A")
                  add("#FFFFFF")
                  add("#111111")
                  add("#7EC8E3")
              }
          }
          putJsonObject("compositional_deconstruction") {
              put("canvas", "Square canvas, upright orientation. All text is horizontal and readable.")
              put("background", "Clean white office desk with a soft blue background gradient.")
              putJsonArray("elements") {
                  addJsonObject {
                      put("type", "obj")
                      putJsonArray("bbox") { listOf(230, 260, 800, 740).forEach { add(it) } }
                      put("desc", "Exactly one matte yellow ceramic coffee mug centered on the desk.")
                  }
                  addJsonObject {
                      put("type", "text")
                      putJsonArray("bbox") { listOf(510, 360, 620, 640).forEach { add(it) } }
                      put("text", "IDEO")
                      put("desc", "Small black label printed horizontally on the mug.")
                  }
              }
          }
      }

      fun main(args: Array<String>): Unit = runBlocking {
          if ("--help" in args) {
              println(
                  "Usage: ./gradlew -p examples run -Pexample=DiffusionIdeogram " +
                      "--args=\"[model] [uncond] [llm] [vae] [output-dir]\"",
              )
              println("▸ Defaults use the four Hugging Face model URLs supported by the diffusion addon.")
              return@runBlocking
          }

          val diffusionModelSrc = args.getOrNull(0) ?: DIFFUSION_MODEL_SRC
          val uncondModelSrc = args.getOrNull(1) ?: UNCOND_MODEL_SRC
          val llmModelSrc = args.getOrNull(2) ?: LLM_MODEL_SRC
          val vaeModelSrc = args.getOrNull(3) ?: VAE_MODEL_SRC
          val outputDir = Path.of(args.getOrNull(4) ?: ".")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading Ideogram 4 split-layout model...")
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("device", "gpu")
                      put("threads", 4)
                      put("diffusion_fa", true)
                      put("offload_to_cpu", true)
                      put("llmModelSrc", llmModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("uncondModelSrc", uncondModelSrc)
                  },
              )
              println("▸ Model loaded: $modelId")

              try {
                  val run = client.media.diffusion(
                      DiffusionStreamRequest(
                          modelId = modelId,
                          // Compact JSON, like JSON.stringify; the model is sensitive
                          // to the caption's exact format.
                          prompt = STRUCTURED_PROMPT.toString(),
                          width = 768,
                          height = 768,
                          steps = 16,
                          cfg_scale = 7.0,
                          seed = 42,
                      ),
                  )
                  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, image ->
                      val outputPath = outputDir.resolve("ideogram_$index.png")
                      Files.write(outputPath, Base64.getDecoder().decode(image))
                      println("▸ Saved $outputPath")
                  }

                  println("▸ Stats: ${result.stats}")
              } catch (error: Exception) {
                  // Preserve the original error.
                  runCatching { client.models.unload(modelId) }
                  throw error
              }

              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>

The Kotlin example serializes the caption with `buildJsonObject { ... }.toString()`, which already produces the compact form.

### Stable Diffusion

The following script shows a minimal text-to-image generation example using a single all-in-one SD 2.1 model:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-simple.js title="diffusion-simple.js" lineNumbers
      import { loadModel, unloadModel, diffusion, SD_V2_1_1B_Q8_0 } from '@qvac/sdk';
      import fs from 'fs';
      // Minimal diffusion example — single GGUF model, no companion files needed.
      // Works with SD 1.x / 2.x all-in-one models.
      const modelSrc = process.argv[2] || SD_V2_1_1B_Q8_0;
      const prompt = process.argv[3] || 'a photo of a cat sitting on a windowsill';
      const modelId = await loadModel({
          modelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: { prediction: 'v' }
      });
      const { outputs } = diffusion({ modelId, prompt });
      const buffers = await outputs;
      fs.writeFileSync('output.png', buffers[0]);
      console.log('▸ Saved output.png');
      await unloadModel({ modelId, clearStorage: false });
      process.exit(0);
      ```
    </WrapCode>
  </Tab>

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

      // Minimal diffusion example — single GGUF model, no companion files needed.
      // Works with SD 1.x / 2.x all-in-one models.
      const modelSrc = process.argv[2] || SD_V2_1_1B_Q8_0
      const prompt = process.argv[3] || 'a photo of a cat sitting on a windowsill'

      const modelId = await loadModel({
        modelSrc,
        modelType: 'sdcpp-generation',
        modelConfig: { prediction: 'v' }
      })

      const { outputs } = diffusion({ modelId, prompt })
      const buffers = await outputs

      fs.writeFileSync('output.png', buffers[0]!)
      console.log('▸ Saved output.png')

      await unloadModel({ modelId, clearStorage: false })
      process.exit(0)
      ```
    </WrapCode>
  </Tab>

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

      Minimal diffusion example -- single GGUF model, no companion files needed.
      Works with SD 1.x / 2.x all-in-one models.

      TypeScript reads the finished image off the `outputs` promise that
      `diffusion()` returns. Python has only the `diffusion_stream` iterator, so the
      image arrives as a base64 chunk on the stream. Everything else the stream
      carries -- per-step progress, closing stats -- is ignored here, exactly as the
      TypeScript example ignores the channels it does not destructure.

      RUN: python examples/diffusion_simple.py [model-src] [prompt]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import SD_V2_1_1B_Q8_0


      async def main() -> int:
          model_src = sys.argv[1] if len(sys.argv) > 1 else SD_V2_1_1B_Q8_0
          prompt = (
              sys.argv[2] if len(sys.argv) > 2 else "a photo of a cat sitting on a windowsill"
          )

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

              model_id = await load_model(
                  t,
                  model_src=model_src,
                  model_type="sdcpp-generation",
                  model_config={"prediction": "v"},
              )

              request = DiffusionStreamRequest.model_validate(
                  {"type": "diffusionStream", "modelId": model_id, "prompt": prompt}
              )

              images: list[bytes] = []
              async for response in diffusion_stream(t, request):
                  if response.data is not None:
                      images.append(base64.b64decode(response.data))

              Path("output.png").write_bytes(images[0])
              print("▸ Saved output.png")

              await unload_model(t, model_id)

          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/DiffusionSimple.kt title="DiffusionSimple.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-simple.ts.
      //
      // Minimal diffusion example: a single GGUF model, no companion files needed.
      // Works with SD 1.x / 2.x all-in-one models.
      //
      // `client.media.diffusion()` returns a `QvacMediaRun`: an `events` Flow (per-step
      // progress) and a `final` Deferred that aggregates the base64 images and the
      // closing stats. Like the TypeScript `outputs` promise, this example awaits only
      // `final` and never collects `events`.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionSimple --args="[model-src] [prompt]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.generated.Models
      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.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          val modelSrc = args.getOrNull(0) ?: Models.SD_V2_1_1B_Q8_0.src
          val prompt = args.getOrNull(1) ?: "a photo of a cat sitting on a windowsill"

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val loaded = client.models.load(
                  source = modelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject { put("prediction", "v") },
              )
              val modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")

              val result = client.media.diffusion(modelId = modelId, prompt = prompt).final.await()

              Files.write(Path.of("output.png"), Base64.getDecoder().decode(result.data.first()))
              println("▸ Saved output.png")

              client.models.unload(modelId)
          } finally {
              client.close()
          }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Image-to-image

Pass `init_image` to transform an existing image guided by a text prompt. Behavior depends on the model family:

* **FLUX.2**: in-context conditioning. Requires `prediction: "flux2_flow"` in `modelConfig` at `loadModel()` time; `strength` is ignored on this path.
* **Qwen-Image-2.1** uses reference conditioning with automatic model detection. Supply `projectionModelSrc` at load time for editing with the GGUF encoder. Use `init_image` or ordered `init_images`; `strength` does not control reference fidelity.
* **SD / SDXL / SD3**: SDEdit-style. Use `strength` to control how much the source is preserved (`0` = keep source, `1` = ignore source).

The following script loads FLUX.2-klein in split-layout and transforms an input image using in-context conditioning (`prediction: "flux2_flow"`):

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-flux2-klein-img2img.js title="diffusion-flux2-klein-img2img.js" lineNumbers
      import { loadModel, unloadModel, diffusion, FLUX_2_KLEIN_4B_Q4_0, FLUX_2_KLEIN_4B_VAE, QWEN3_4B_Q4_K_M } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // img2img with FLUX.2 [klein] split-layout — uses in-context conditioning ("flux2_flow").
      const inputPath = process.argv[2];
      const prompt = process.argv[3] || 'oil painting style, vibrant colors';
      const outputDir = process.argv[4] || '.';
      const diffusionModelSrc = process.argv[5] || FLUX_2_KLEIN_4B_Q4_0;
      const llmModelSrc = process.argv[6] || QWEN3_4B_Q4_K_M;
      const vaeModelSrc = process.argv[7] || FLUX_2_KLEIN_4B_VAE;
      if (!inputPath) {
          console.error('✖ input image path is required');
          console.error('Usage: node dist/examples/diffusion-flux2-klein-img2img.js <inputImage> [prompt] [outputDir] [diffusionModelSrc] [llmModelSrc] [vaeModelSrc]');
          process.exit(1);
      }
      try {
          console.log('▸ Loading FLUX.2 [klein] split-layout model...');
          const modelId = await loadModel({
              modelSrc: diffusionModelSrc,
              modelType: 'sdcpp-generation',
              modelConfig: {
                  device: 'gpu',
                  threads: 4,
                  llmModelSrc,
                  vaeModelSrc,
                  prediction: 'flux2_flow'
              },
              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(inputPath));
          console.log(`▸ Transforming "${inputPath}" with prompt: "${prompt}"`);
          const { progressStream, outputs, stats } = diffusion({
              modelId,
              prompt,
              init_image,
              steps: 20,
              guidance: 3.5,
              cfg_scale: 1,
              seed: -1
          });
          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, `flux2_img2img_${i}.png`);
              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-flux2-klein-img2img.ts title="diffusion-flux2-klein-img2img.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        diffusion,
        FLUX_2_KLEIN_4B_Q4_0,
        FLUX_2_KLEIN_4B_VAE,
        QWEN3_4B_Q4_K_M
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // img2img with FLUX.2 [klein] split-layout — uses in-context conditioning ("flux2_flow").

      const inputPath = process.argv[2]
      const prompt = process.argv[3] || 'oil painting style, vibrant colors'
      const outputDir = process.argv[4] || '.'
      const diffusionModelSrc = process.argv[5] || FLUX_2_KLEIN_4B_Q4_0
      const llmModelSrc = process.argv[6] || QWEN3_4B_Q4_K_M
      const vaeModelSrc = process.argv[7] || FLUX_2_KLEIN_4B_VAE

      if (!inputPath) {
        console.error('✖ input image path is required')
        console.error(
          'Usage: node dist/examples/diffusion-flux2-klein-img2img.js <inputImage> [prompt] [outputDir] [diffusionModelSrc] [llmModelSrc] [vaeModelSrc]'
        )
        process.exit(1)
      }

      try {
        console.log('▸ Loading FLUX.2 [klein] split-layout model...')
        const modelId = await loadModel({
          modelSrc: diffusionModelSrc,
          modelType: 'sdcpp-generation',
          modelConfig: {
            device: 'gpu',
            threads: 4,
            llmModelSrc,
            vaeModelSrc,
            prediction: 'flux2_flow'
          },
          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(inputPath))
        console.log(`▸ Transforming "${inputPath}" with prompt: "${prompt}"`)

        const { progressStream, outputs, stats } = diffusion({
          modelId,
          prompt,
          init_image,
          steps: 20,
          guidance: 3.5,
          cfg_scale: 1,
          seed: -1
        })

        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, `flux2_img2img_${i}.png`)
          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_flux2_klein_img2img.py title="diffusion_flux2_klein_img2img.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-flux2-klein-img2img.ts.

      img2img with FLUX.2 [klein] split-layout -- uses in-context conditioning
      ("flux2_flow").

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

      No `width`/`height` is passed, so the generation runs at the input image's
      size. A large input therefore means much more work per step.

      RUN: python examples/diffusion_flux2_klein_img2img.py <input-image> [prompt] [output-dir] [diffusion-src] [llm-src] [vae-src]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          FLUX_2_KLEIN_4B_Q4_0,
          FLUX_2_KLEIN_4B_VAE,
          QWEN3_4B_Q4_K_M,
      )


      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:
          input_path = sys.argv[1] if len(sys.argv) > 1 else None
          prompt = sys.argv[2] if len(sys.argv) > 2 else "oil painting style, vibrant colors"
          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 FLUX_2_KLEIN_4B_Q4_0
          llm_model_src = sys.argv[5] if len(sys.argv) > 5 else QWEN3_4B_Q4_K_M
          vae_model_src = sys.argv[6] if len(sys.argv) > 6 else FLUX_2_KLEIN_4B_VAE

          if not input_path:
              print("✖ input image path is required", file=sys.stderr)
              print(
                  "Usage: python examples/diffusion_flux2_klein_img2img.py <inputImage> "
                  "[prompt] [outputDir] [diffusionModelSrc] [llmModelSrc] [vaeModelSrc]",
                  file=sys.stderr,
              )
              return 1

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

                  print("▸ Loading FLUX.2 [klein] split-layout model...")
                  model_id = await load_model(
                      t,
                      model_src=diffusion_model_src,
                      model_type="sdcpp-generation",
                      model_config={
                          "device": "gpu",
                          "threads": 4,
                          "llmModelSrc": llm_model_src,
                          "vaeModelSrc": vae_model_src,
                          "prediction": "flux2_flow",
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  init_image = base64.b64encode(Path(input_path).read_bytes()).decode("ascii")
                  print(f'▸ Transforming "{input_path}" with prompt: "{prompt}"')

                  request = DiffusionStreamRequest.model_validate(
                      {
                          "type": "diffusionStream",
                          "modelId": model_id,
                          "prompt": prompt,
                          "init_image": init_image,
                          "steps": 20,
                          "guidance": 3.5,
                          "cfg_scale": 1,
                          "seed": -1,
                      }
                  )

                  images: list[bytes] = []
                  stats = None
                  async for response in diffusion_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:
                          images.append(base64.b64decode(response.data))
                      if response.done:
                          stats = response.stats

                  for index, image in enumerate(images):
                      output_path = output_dir / f"flux2_img2img_{index}.png"
                      output_path.write_bytes(image)
                      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/DiffusionFlux2KleinImg2img.kt title="DiffusionFlux2KleinImg2img.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-flux2-klein-img2img.ts.
      //
      // img2img with FLUX.2 [klein] split-layout -- uses in-context conditioning
      // ("flux2_flow").
      //
      // TypeScript's `diffusion()` takes `init_image` as raw bytes and base64-encodes
      // them on the way to the worker. The typed `DiffusionStreamRequest` carries the
      // already-encoded string, so the example encodes the file with
      // `java.util.Base64`. The returned `QvacMediaRun` splits the stream like
      // TypeScript does: `events` (a `Flow` of per-step progress) and `final` (a
      // `Deferred` with the images and the closing stats).
      //
      // No `width`/`height` is passed, so the generation runs at the input image's
      // size. A large input therefore means much more work per step.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionFlux2KleinImg2img --args="<input-image> [prompt] [output-dir] [diffusion-src] [llm-src] [vae-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.DiffusionStreamRequest
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      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 inputPath = args.getOrNull(0)
          val prompt = args.getOrNull(1) ?: "oil painting style, vibrant colors"
          val outputDir = Path.of(args.getOrNull(2) ?: ".")
          val diffusionModelSrc = args.getOrNull(3) ?: Models.FLUX_2_KLEIN_4B_Q4_0.src
          val llmModelSrc = args.getOrNull(4) ?: Models.QWEN3_4B_Q4_K_M.src
          val vaeModelSrc = args.getOrNull(5) ?: Models.FLUX_2_KLEIN_4B_VAE.src

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

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Loading FLUX.2 [klein] split-layout model...")
              val modelId = client.loadWithProgress(
                  source = diffusionModelSrc,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("device", "gpu")
                      put("threads", 4)
                      put("llmModelSrc", llmModelSrc)
                      put("vaeModelSrc", vaeModelSrc)
                      put("prediction", "flux2_flow")
                  },
              )
              println("▸ Model loaded: $modelId")

              val initImage = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(inputPath)))
              println("▸ Transforming \"$inputPath\" with prompt: \"$prompt\"")

              val run = client.media.diffusion(
                  DiffusionStreamRequest(
                      modelId = modelId,
                      prompt = prompt,
                      init_image = initImage,
                      steps = 20,
                      guidance = 3.5,
                      cfg_scale = 1.0,
                      seed = -1,
                  ),
              )
              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, image ->
                  val outputPath = outputDir.resolve("flux2_img2img_$index.png")
                  Files.write(outputPath, Base64.getDecoder().decode(image))
                  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>

### Upscaling

#### Post-processing

Pass `upscale` to `diffusion()` to upscale generated images in the same call. Requires `modelConfig.upscaler = { type: "esrgan", model_src, tile_size? }` at `loadModel()` time. Behavior depends on the value passed:

* `true` (or `{}` / `{ repeats: 1 }`): single pass at the model's native scale factor (e.g. `x4` for RealESRGAN\_x4plus).
* `{ repeats: N }`: N sequential passes — each pass multiplies the output dimensions by the model's scale factor (e.g. `repeats: 2` with an `x4` model → `x16`).
* When `batch_count > 1`, every output image is upscaled independently.

<Callout type="info">
  Qwen-Image-2.1 produces RGBA and rejects this option; leave `upscale` omitted or `false`.
</Callout>

The following script loads SD 2.1 with an ESRGAN upscaler and generates both a single-pass (`x4`) and a two-pass (`x16`) upscale from the same prompt:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/diffusion-esrgan-upscale.js title="diffusion-esrgan-upscale.js" lineNumbers
      import { loadModel, unloadModel, diffusion, SD_V2_1_1B_Q8_0, REALESRGAN_X4PLUS_ANIME_6B } from '@qvac/sdk';
      import fs from 'fs';
      import path from 'path';
      // ESRGAN upscale example.
      //
      // Usage:
      //   npx tsx examples/diffusion-esrgan-upscale.ts [esrganSrc] [prompt] [outputDir]
      const esrganArg = process.argv[2];
      const promptArg = process.argv[3];
      const outputDirArg = process.argv[4];
      const esrganModelSrc = esrganArg ?? REALESRGAN_X4PLUS_ANIME_6B;
      const prompt = promptArg ??
          'an illustrated red fox portrait, clean line art, soft watercolor background, detailed fur, crisp eyes';
      const negative_prompt = 'blurry, low quality, watermark, text';
      const outputDir = outputDirArg ?? '.';
      const seed = 42;
      try {
          console.log('▸ Loading SD 2.1 + ESRGAN upscaler...');
          const modelId = await loadModel({
              modelSrc: SD_V2_1_1B_Q8_0,
              modelConfig: {
                  prediction: 'v',
                  upscaler: {
                      type: 'esrgan',
                      model_src: esrganModelSrc,
                      tile_size: 128
                  }
              },
              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}`);
          // Source size is intentionally small — each ESRGAN repeat multiplies dimensions.
          const baseParams = {
              modelId,
              prompt,
              negative_prompt,
              width: 128,
              height: 128,
              steps: 5,
              cfg_scale: 7.5,
              seed
          };
          console.log(`▸ Generating ESRGAN x4 upscale: "${prompt}"`);
          const single = diffusion({ ...baseParams, upscale: true });
          for await (const { step, totalSteps } of single.progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const singleBuffers = await single.outputs;
          for (let i = 0; i < singleBuffers.length; i++) {
              const out = path.join(outputDir, `sd2_esrgan_x4_seed${seed}_${i}.png`);
              fs.writeFileSync(out, singleBuffers[i]);
              console.log(`▸ Saved ${out}`);
          }
          console.log('▸ Stats:', await single.stats);
          console.log('▸ Generating ESRGAN two-pass x16 upscale...');
          const twoPass = diffusion({ ...baseParams, upscale: { repeats: 2 } });
          for await (const { step, totalSteps } of twoPass.progressStream) {
              console.log(`▸ step ${step}/${totalSteps}`);
          }
          const twoPassBuffers = await twoPass.outputs;
          for (let i = 0; i < twoPassBuffers.length; i++) {
              const out = path.join(outputDir, `sd2_esrgan_x16_seed${seed}_${i}.png`);
              fs.writeFileSync(out, twoPassBuffers[i]);
              console.log(`▸ Saved ${out}`);
          }
          console.log('▸ Stats:', await twoPass.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-esrgan-upscale.ts title="diffusion-esrgan-upscale.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        diffusion,
        SD_V2_1_1B_Q8_0,
        REALESRGAN_X4PLUS_ANIME_6B
      } from '@qvac/sdk'
      import fs from 'fs'
      import path from 'path'

      // ESRGAN upscale example.
      //
      // Usage:
      //   npx tsx examples/diffusion-esrgan-upscale.ts [esrganSrc] [prompt] [outputDir]

      const esrganArg: string | undefined = process.argv[2]
      const promptArg: string | undefined = process.argv[3]
      const outputDirArg: string | undefined = process.argv[4]

      const esrganModelSrc = esrganArg ?? REALESRGAN_X4PLUS_ANIME_6B

      const prompt =
        promptArg ??
        'an illustrated red fox portrait, clean line art, soft watercolor background, detailed fur, crisp eyes'
      const negative_prompt = 'blurry, low quality, watermark, text'
      const outputDir = outputDirArg ?? '.'
      const seed = 42

      try {
        console.log('▸ Loading SD 2.1 + ESRGAN upscaler...')
        const modelId = await loadModel({
          modelSrc: SD_V2_1_1B_Q8_0,
          modelConfig: {
            prediction: 'v',
            upscaler: {
              type: 'esrgan',
              model_src: esrganModelSrc,
              tile_size: 128
            }
          },
          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}`)

        // Source size is intentionally small — each ESRGAN repeat multiplies dimensions.
        const baseParams = {
          modelId,
          prompt,
          negative_prompt,
          width: 128,
          height: 128,
          steps: 5,
          cfg_scale: 7.5,
          seed
        }

        console.log(`▸ Generating ESRGAN x4 upscale: "${prompt}"`)
        const single = diffusion({ ...baseParams, upscale: true })
        for await (const { step, totalSteps } of single.progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const singleBuffers = await single.outputs
        for (let i = 0; i < singleBuffers.length; i++) {
          const out = path.join(outputDir, `sd2_esrgan_x4_seed${seed}_${i}.png`)
          fs.writeFileSync(out, singleBuffers[i]!)
          console.log(`▸ Saved ${out}`)
        }
        console.log('▸ Stats:', await single.stats)

        console.log('▸ Generating ESRGAN two-pass x16 upscale...')
        const twoPass = diffusion({ ...baseParams, upscale: { repeats: 2 } })
        for await (const { step, totalSteps } of twoPass.progressStream) {
          console.log(`▸ step ${step}/${totalSteps}`)
        }

        const twoPassBuffers = await twoPass.outputs
        for (let i = 0; i < twoPassBuffers.length; i++) {
          const out = path.join(outputDir, `sd2_esrgan_x16_seed${seed}_${i}.png`)
          fs.writeFileSync(out, twoPassBuffers[i]!)
          console.log(`▸ Saved ${out}`)
        }
        console.log('▸ Stats:', await twoPass.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_esrgan_upscale.py title="diffusion_esrgan_upscale.py" lineNumbers
      """Python port of packages/sdk/examples/diffusion-esrgan-upscale.ts.

      ESRGAN post-processing: the upscaler is attached to the diffusion model at
      `load_model` time via `model_config["upscaler"]`, then triggered per
      generation with the request's `upscale` field. Two generations run from the
      same seed and prompt -- one single pass (x4) and one two-pass (x16) -- so the
      only difference between them is `upscale`.

      The ESRGAN constant goes inside `model_config`, not as the top-level
      `model_src`, and needs no conversion: `load_model` reduces every model
      descriptor it finds anywhere in the config to its `src` string.

      Like the other diffusion examples, this one demultiplexes the single
      `diffusion_stream` iterator into the per-step progress, the finished images
      and the closing stats that TypeScript receives as three separate channels.

      RUN: python examples/diffusion_esrgan_upscale.py [esrgan-src] [prompt] [output-dir]
      """

      from __future__ import annotations

      import asyncio
      import base64
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          DiffusionStreamRequest,
          diffusion_stream,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import REALESRGAN_X4PLUS_ANIME_6B, SD_V2_1_1B_Q8_0


      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:
          esrgan_model_src = sys.argv[1] if len(sys.argv) > 1 else REALESRGAN_X4PLUS_ANIME_6B
          prompt = (
              sys.argv[2]
              if len(sys.argv) > 2
              else "an illustrated red fox portrait, clean line art, "
              "soft watercolor background, detailed fur, crisp eyes"
          )
          negative_prompt = "blurry, low quality, watermark, text"
          output_dir = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(".")
          seed = 42

          print("▸ Loading SD 2.1 + ESRGAN upscaler...")

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

              model_id = await load_model(
                  t,
                  model_src=SD_V2_1_1B_Q8_0,
                  model_type="sdcpp-generation",
                  model_config={
                      "prediction": "v",
                      "upscaler": {
                          "type": "esrgan",
                          "model_src": esrgan_model_src,
                          "tile_size": 128,
                      },
                  },
                  on_progress=print_progress,
              )
              print(f"▸ Model loaded: {model_id}")

              # Source size is intentionally small -- each ESRGAN repeat multiplies
              # dimensions.
              base_params = {
                  "type": "diffusionStream",
                  "modelId": model_id,
                  "prompt": prompt,
                  "negative_prompt": negative_prompt,
                  "width": 128,
                  "height": 128,
                  "steps": 5,
                  "cfg_scale": 7.5,
                  "seed": seed,
              }

              print(f'▸ Generating ESRGAN x4 upscale: "{prompt}"')
              single = DiffusionStreamRequest.model_validate({**base_params, "upscale": True})

              single_images: list[bytes] = []
              single_stats = None
              async for response in diffusion_stream(t, single):
                  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:
                      single_images.append(base64.b64decode(response.data))
                  if response.done:
                      single_stats = response.stats

              for index, image in enumerate(single_images):
                  output_path = output_dir / f"sd2_esrgan_x4_seed{seed}_{index}.png"
                  output_path.write_bytes(image)
                  print(f"▸ Saved {output_path}")

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

              print("▸ Generating ESRGAN two-pass x16 upscale...")
              two_pass = DiffusionStreamRequest.model_validate(
                  {**base_params, "upscale": {"repeats": 2}}
              )

              two_pass_images: list[bytes] = []
              two_pass_stats = None
              async for response in diffusion_stream(t, two_pass):
                  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:
                      two_pass_images.append(base64.b64decode(response.data))
                  if response.done:
                      two_pass_stats = response.stats

              for index, image in enumerate(two_pass_images):
                  output_path = output_dir / f"sd2_esrgan_x16_seed{seed}_{index}.png"
                  output_path.write_bytes(image)
                  print(f"▸ Saved {output_path}")

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

              await unload_model(t, model_id, clear_storage=False)

          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/DiffusionEsrganUpscale.kt title="DiffusionEsrganUpscale.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/diffusion-esrgan-upscale.ts.
      //
      // ESRGAN post-processing: the upscaler is attached to the diffusion model at
      // load time via `modelConfig.upscaler`, then triggered per generation with the
      // request's `upscale` field. Two generations run from the same seed and
      // prompt -- one single pass (x4) and one two-pass (x16) -- so the only
      // difference between them is `upscale`.
      //
      // The ESRGAN constant goes inside `modelConfig` as its `src` string, not as the
      // top-level model source. `upscale` is a generated sealed union: `Variant1(true)`
      // for a single pass, or the object arm carrying `repeats` for several passes.
      // Each `QvacMediaRun` splits progress (`events` Flow) from the images and
      // stats (`final` Deferred), as TypeScript does.
      //
      // RUN: ./gradlew -p examples run -Pexample=DiffusionEsrganUpscale --args="[esrgan-src] [prompt] [output-dir]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacMediaRun
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequest
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequestUpscale
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamRequestUpscale9B8B4FE2
      import io.tether.qvac.sdk.generated.schema.DiffusionStreamResponse
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      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
      import kotlinx.serialization.json.putJsonObject

      fun main(args: Array<String>): Unit = runBlocking {
          val esrganModelSrc = args.getOrNull(0) ?: Models.REALESRGAN_X4PLUS_ANIME_6B.src
          val prompt = args.getOrNull(1)
              ?: ("an illustrated red fox portrait, clean line art, " +
                  "soft watercolor background, detailed fur, crisp eyes")
          val negativePrompt = "blurry, low quality, watermark, text"
          val outputDir = Path.of(args.getOrNull(2) ?: ".")
          val seed = 42L

          println("▸ Loading SD 2.1 + ESRGAN upscaler...")

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = Models.SD_V2_1_1B_Q8_0.src,
                  modelType = "sdcpp-generation",
                  modelConfig = buildJsonObject {
                      put("prediction", "v")
                      putJsonObject("upscaler") {
                          put("type", "esrgan")
                          put("model_src", esrganModelSrc)
                          put("tile_size", 128)
                      }
                  },
              )
              println("▸ Model loaded: $modelId")

              // Source size is intentionally small -- each ESRGAN repeat multiplies
              // dimensions.
              val baseParams = DiffusionStreamRequest(
                  modelId = modelId,
                  prompt = prompt,
                  negative_prompt = negativePrompt,
                  width = 128,
                  height = 128,
                  steps = 5,
                  cfg_scale = 7.5,
                  seed = seed,
              )

              println("▸ Generating ESRGAN x4 upscale: \"$prompt\"")
              val single = baseParams.copy(upscale = DiffusionStreamRequestUpscale.Variant1(true))
              saveImages(client.media.diffusion(single), outputDir, "sd2_esrgan_x4_seed$seed")

              println("▸ Generating ESRGAN two-pass x16 upscale...")
              val twoPass = baseParams.copy(
                  upscale = DiffusionStreamRequestUpscale.Value9B8B4FE2(DiffusionStreamRequestUpscale9B8B4FE2(repeats = 2)),
              )
              saveImages(client.media.diffusion(twoPass), outputDir, "sd2_esrgan_x16_seed$seed")

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

          println("▸ Done")
      }

      /** Print step progress, then write each finished image as `<prefix>_<index>.png` and print the stats. */
      private suspend fun saveImages(run: QvacMediaRun<DiffusionStreamResponse>, outputDir: Path, prefix: String) {
          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, image ->
              val outputPath = outputDir.resolve("${prefix}_$index.png")
              Files.write(outputPath, Base64.getDecoder().decode(image))
              println("▸ Saved $outputPath")
          }

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

      /** 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>

#### Standalone

The SDK also exposes `upscale()` — a standalone path that upscales any PNG/JPEG image without running diffusion. Load the ESRGAN model directly with `modelConfig.mode: "upscale"`:

```ts
const modelId = await loadModel(REALESRGAN_X4PLUS_ANIME_6B, {
  modelType: "diffusion",
  modelConfig: { mode: "upscale", upscaler: { tile_size: 128 } },
});
const { outputs } = upscale({ modelId, image: pngBytes, repeats: 2 });
const [upscaledPng] = await outputs;
```

`tile_size` defaults to 128. Increase it to reduce tile seams on large inputs, at the cost of more memory per pass.

<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>
