Skip to main content

metastable

Stable Diffusion middleware: pipeline generators, compute-device selection and checkpoint merging, originally developed as part of sd-api-backend and now extracted so the same engine can power API servers and standalone applications.

  • Pipelines – SD 1.5, SDXL, Illustrious XL, Flux and Z-Image (Base and Turbo) text-to-image and inpainting, LoRA fusion, custom VAEs, scheduler selection
  • Devices – CUDA, ROCm (incl. gfx_override for unsupported AMD cards), Apple MPS and CPU, with automatic dtype selection
  • Merging – linear / SLERP / additive / subtract merges, batch merges and multi-step recipes (SD 1.5, SDXL, Illustrious XL, Flux, Z-Image), streamed with constant memory
  • Telemetry (optional) – GPU memory/utilization and host stats

import metastable is cheap: heavy dependencies load on first use.

Installation

uv add metastable                 # or: pip install metastable
uv add "metastable[telemetry]"    # + psutil for host/MPS stats

Local development / use from a sibling project:

# consumer pyproject.toml
[tool.uv.sources]
metastable = { path = "../sd-lib", editable = true }

torch is declared without a specific build. The consuming application picks the CPU / CUDA / ROCm wheel index (see sd-api-backend's pyproject.linux.toml).

Quick start

import metastable
from PIL import Image

metastable.configure_device({"backend": "auto"})   # optional; auto-detects otherwise

gen = metastable.create_generator("sdxl", "models/sdxl/model.safetensors")
gen.load_pipeline()
gen.add_loras([metastable.LoraSpec("models/loras/style.safetensors", strength=0.7)])
gen.to_device()

image, metadata = gen.forward(
    positive_prompt="a lighthouse at dusk",
    negative_prompt="blurry",
    scheduler_type="DPM++ 2M",   # None keeps the model's scheduler
    steps=25, width=1024, height=1024, cfg=7.0,
    seed=-1,                     # negative = random; metadata reports the seed used
)
Image.fromarray(image).save("out.png")

Flux needs the shared text-encoder/VAE directory:

gen = metastable.create_generator(
    "flux", "models/flux/flux1-dev.safetensors", components_dir="models/flux_components"
)
gen.load_pipeline()
gen.to_device()              # model CPU offload on accelerators
image, meta = gen.forward("a fox", "", "FlowMatch Euler", 28, 1024, 1024, 3.5, 42,
                          true_cfg_scale=1.0)

The text encoders, VAE and scheduler in components_dir are loaded once and shared by every Flux pipeline. Before LoRAs are fused, a pipeline gets its own copy of each component a LoRA can modify (the CLIP text encoder), so fused weights never leak into other pipelines. T5 and the VAE stay shared.

Because modules are shared, every generator using the same components_dir shares one lock (gen.lock): generations, LoRA fusion and placement changes on any of them run one at a time, and concurrent requests queue up. Use gen.lock.acquire(blocking=False) to report "busy" instead. Single-file generators (SD 1.5, SDXL, Illustrious) only serialize calls on the same generator. Generators with different components directories (e.g. Flux and Z-Image) are locked separately and may run concurrently, competing for VRAM.

If components_dir also contains transformer/config.json, it is used to load the checkpoint, so loading works offline; otherwise diffusers infers the config from the checkpoint keys and may fetch it from the Hugging Face Hub.

Z-Image (Base and Turbo) works the same way, with a components directory in the Tongyi-MAI/Z-Image or Tongyi-MAI/Z-Image-Turbo layout (Qwen3 text encoder, tokenizer, VAE, scheduler):

gen = metastable.create_generator(
    "zimage", "models/zimage/z_image_turbo_bf16.safetensors",
    components_dir="models/zimage_turbo_components",
)
gen.load_pipeline()
gen.to_device()
image, meta = gen.forward("a fox", "", None, 8, 1024, 1024, 0.0, 42)    # Turbo

One zimage model type serves both checkpoints; pick the settings to match:

checkpoint steps cfg (guidance_scale) negative prompt
Turbo ~8 0.0 ignored (CFG off)
Base 28–50 ~3–5 used

CFG is enabled whenever cfg > 0. Pair each checkpoint with the components directory from its own repository: the text encoder and VAE are identical, but the scheduler shift differs (3.0 for Turbo, 6.0 for Base). Each directory loads its own copy of the Qwen3 text encoder. forward_inpaint() takes an optional strength (pipeline default 1.0).

Flux and Z-Image use the flow-matching schedulers in FLOW_MATCH_SCHEDULERS (renamed from FLUX_SCHEDULERS; the old name is no longer available). "FlowMatch Heun" has been removed: both pipelines pass custom sigmas to the scheduler, which it does not support.

Inpainting:

gen.load_inpaint_pipeline()
gen.to_device()
image, meta = gen.forward_inpaint("a red door", "", base_image, mask, "Euler a",
                                  steps=30, cfg=7.0, seed=1)

Any extra keyword argument to forward() / forward_inpaint() is passed straight to the diffusers pipeline call.

See examples/ for runnable scripts.

Device configuration

metastable.configure_device({
    "backend": "auto",         # auto | cuda | rocm | mps | cpu
    "index": 0,                # GPU ordinal
    "dtype": "auto",           # auto | float16 | bfloat16 | float32
    "gfx_override": "10.3.0",  # ROCm: HSA_OVERRIDE_GFX_VERSION (e.g. RX 5500 XT)
    "env": {},                 # extra env vars applied before HIP/CUDA init
})

Call it once at startup, before anything else touches torch.cuda. Any mapping or object with to_dict() works. Without it, the library auto-detects mps → cuda/rocm → cpu. To override per generator, pass device=DeviceSettings(...) (e.g. DeviceSettings.cpu()) to its constructor or to create_generator().

Flux and Z-Image default to bfloat16 on accelerators unless dtype is set explicitly.

Merging

from metastable.merge import MergeConfig, MergePipeline

pipe = MergePipeline.for_model_type("sdxl", device="cpu")
pipe.merge("base.safetensors", "target.safetensors",
           MergeConfig(method="slerp", alpha=0.3), "merged.safetensors")

recipe = pipe.create_merge_recipe("base.safetensors", [
    {"target_model": "a.safetensors", "method": "linear", "alpha": 0.5},
    {"target_model": "b.safetensors", "method": "additive", "alpha": 0.2},
])
pipe.execute_merge_recipe(recipe, "recipe.safetensors")

pipe.batch_merge("base.safetensors", ["a.safetensors", "b.safetensors"],
                 "merged/", MergeConfig(alpha=0.4))

Supported model types: sd15, sdxl, illustrious, flux and zimage (Z-Image Base and Turbo).

alpha is always the weight of the target model:

method result
linear (1 - alpha) * base + alpha * target
slerp spherical interpolation, alpha=0 → base, alpha=1 → target
additive base + alpha * (target - reference)
subtract base - alpha * (target - reference)

reference defaults to the base. In recipes it is the original base model. MergeConfig(chunk_size=N) frees accelerator memory every N tensors.

File merges (merge(), recipes, batch_merge()) are streamed: tensors are read one at a time from memory-mapped inputs and written straight to the output, so memory use stays at a few tensors even for 12B-parameter Flux transformers. All checkpoints are checked from their headers (keys, shapes, dtypes) before any weights are read. The output is written to a temporary file and renamed into place, so a failed merge never leaves a partial file; an existing output is renamed to a .backup_<timestamp> file first. Provenance goes to a JSON sidecar next to the output.

MergeConfig(output_dtype="bf16") (also float16, float32) sets the dtype of the merged tensors; by default each tensor keeps the base model's dtype. Recipes take it as execute_merge_recipe(recipe, path, output_dtype=...).

fp8 checkpoints are rejected for every model type: merging them would lose precision. Use a bf16/fp16/fp32 version of the model.

Flux and Z-Image

Flux and Z-Image checkpoints hold the diffusion transformer:

  • Key layouts. Files use either the original/ComfyUI layout (fused qkv projections) or the diffusers layout (separate to_q/to_k/to_v). Both inputs must use the same layout; mixing them is rejected. A model.diffusion_model. prefix on either file is fine. The output keeps the base file's key names, so a ComfyUI-layout base gives a ComfyUI-layout result.
  • All-in-one checkpoints. In files that bundle the transformer (under model.diffusion_model.) with a VAE and text encoders, only the transformer is merged. The other components are copied unchanged from the base file (an fp8 text encoder there is fine); the target's are ignored. A transformer-only base gives a transformer-only result.
  • Model variants. Z-Image Base and Turbo files can't be told apart, so nothing stops merging them; the result mixes a distilled and a non-distilled model, and the right steps/CFG become unpredictable. Flux dev and schnell checkpoints have different keys and are rejected.

Development

uv sync
uv run pytest                      # CPU-only, no model downloads
uv run pytest --cov=metastable

License

This project is released under the GPL v3

Metadata

Release files for metastable 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for metastable 0.3.0
File Size Uploaded Provenance Actions
metastable-0.3.0.tar.gz 188.1 kB Without provenance Details for metastable-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for metastable 0.3.0
File Interpreter ABI Platform Actions
metastable-0.3.0-py3-none-any.whl Python 3 none any Details for metastable-0.3.0-py3-none-any.whl

Total release size: 265.0 kB

Release files / metastable-0.3.0.tar.gz

Download URL metastable-0.3.0.tar.gz
Size 188.1 kB
Tags Source
SHA-256 checksum
How to use checksums
fe6d79d688eafb4a7a777ebe3c2cfd960cd5b95323ef4d1d901b383fe7273eb8
BLAKE2b-256 checksum
How to use checksums
7293223092b00f173efd228fb4acb73dea184cf8d3aa99b175a24bd38c42e193
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Arch Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / metastable-0.3.0-py3-none-any.whl

Download URL metastable-0.3.0-py3-none-any.whl
Size 76.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
706a62c3058e05b2add0213ddabdf1db5209bb2195c3353b34da89b93f95c725
BLAKE2b-256 checksum
How to use checksums
58e637902abe8dd53716da8bdf2a47a65c3fc4a433610a085f1194cef794951b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Arch Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for metastable 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page