"""OpenAI-compatible /v1/images/generations front end for Iris-3B. speridlabs/iris-3b — "Iris-3B: Going Beyond the Latent with Pixel-Space Diffusion Training, Conversion and Fine-Tuning" (arXiv 2610.09450). A 3B diffusion transformer that works DIRECTLY IN PIXEL SPACE: there is no VAE and no latent anywhere in the graph. The noisy image is cut into 16x16 RGB patches (in_channels 3, patch_size 16), 8 dual-stream blocks and 16 single-stream blocks run over them with 2D RoPE, and a small pixel head paints the result. Every other diffusion model on this rig encodes to a latent first; this one does not, which is the reason to have it. NOT THE SAME MODEL AS `iris` ON 9047. That is asdf98/IRIS-architecture, a 48-136M architecture-only repo with no trained weights, by different authors. Unrelated. This server deliberately does NOT answer to the bare alias "iris" so a stale client cannot silently land on the wrong one. TWO VARIANTS, one code path, selected by IRIS_VARIANT: * base — 100 DPM-Solver++ steps (order 2), cfg 3.0, flow shift 4.0. FP32 weights. * turbo — the distilled 4-step model. Its distill.yaml carries the four sigmas and guidance is BAKED INTO THE WEIGHTS, so there is no step count, no CFG, no negative prompt and no shift to set. Asking for any of them is a 400 here, mirroring what the author's own scripts/sample.py does (it calls parser.error on exactly that combination) rather than quietly ignoring the request. Model code is VENDORED, not reimplemented: /home/dh/code/iris3b pinned at commit cee0c13 is mounted read-only and imported, so IrisDiT, FlowDPMSolver, the Qwen3-VL text encoder and both generate() paths are the author's own modules. Only the HTTP shape is ours. The text encoder is a FROZEN Qwen3-VL-4B-Instruct, and the model reads ELEVEN hidden layers out of it (2,5,8,...,35) rather than just the last, so another Qwen3-VL size is not a drop-in: text_encoder.dim must be 2560. It is served from a local directory because the container runs HF_HUB_OFFLINE=1. Weights are FP32 with a BF16 autocast at the forward, which is how the author's sample.py loads them. LICENSE: Apache-2.0, text encoder Apache-2.0 — commercial-OK. Defaults are hardcoded in ImageRequest below and echoed per call under "params_used"; query them via GET /v1/config. """ import base64, io, os, sys, threading, time from typing import Optional import numpy as np import torch from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse from PIL import Image from pydantic import BaseModel, Field import uvicorn IRIS_SRC = os.environ.get("IRIS_SRC", "/iris3b/src") sys.path.insert(0, IRIS_SRC) from omegaconf import OmegaConf # noqa: E402 from iris3b.config import inference_config # noqa: E402 from iris3b.models.dit import IrisDiT # noqa: E402 from iris3b.registry import TEXT_ENCODERS # noqa: E402 from iris3b.sampling import generate, generate_few_step, load_for_inference # noqa: E402 import iris3b.text # noqa: E402,F401 — registers the encoders VARIANT = os.environ.get("IRIS_VARIANT", "base") SERVED_MODEL_ID = os.environ.get("SERVED_MODEL_ID", f"iris-3b{'' if VARIANT == 'base' else '-' + VARIANT}") PORT = int(os.environ.get("PORT", "9207")) MODEL_DIR = os.environ.get("MODEL_DIR", "/model") TEXT_ENCODER_DIR = os.environ.get("IRIS_TEXT_ENCODER", os.path.join(MODEL_DIR, "text_encoder")) # inference_config() always drops a checkpoint's null_embed_dir as machine-local, so the # default "output/pretrained_models" would be created relative to the CWD. The model dir # is mounted read-only, so point the cache somewhere writable. NULL_EMBED_DIR = os.environ.get("IRIS_NULL_EMBED_DIR", "/tmp/iris-null-embeds") CKPT_DIR = MODEL_DIR if VARIANT == "base" else os.path.join(MODEL_DIR, VARIANT) PATCH = 16 # pixel patch size — H and W must be multiples of it MAX_PIXELS = 1 << 20 # the model is trained to ~1 megapixel; beyond that is extrapolation app = FastAPI() _lock = threading.Lock() # one model, one CUDA stream; see generate_images() _state = {} def _load(): t0 = time.time() raw, weights = load_for_inference(CKPT_DIR) cfg = inference_config(raw, [ f"text_encoder.pretrained={TEXT_ENCODER_DIR}", f"text_encoder.null_embed_dir={NULL_EMBED_DIR}", ]) # Built on the meta device, then the checkpoint tensors BECOME the parameters # (assign=True) — the author's own load path, and it avoids a second 12 GB copy. with torch.device("meta"): model = IrisDiT(cfg.model) model.load_state_dict(weights, strict=True, assign=True) model = model.eval().to(device="cuda", dtype=torch.float32) text_encoder = TEXT_ENCODERS.build(cfg.text_encoder.name, cfg.text_encoder, device="cuda") # A distilled export fixes its own schedule; its presence is what selects the # few-step path, exactly as scripts/sample.py decides it. distill = os.path.join(CKPT_DIR, "distill.yaml") sigmas = list(OmegaConf.load(distill).dmd.sigmas) if os.path.isfile(distill) else None _state.update(dict(model=model, text_encoder=text_encoder, cfg=cfg, sigmas=sigmas)) n_params = sum(p.numel() for p in model.parameters()) print(f"iris-3b ({VARIANT}) loaded in {time.time()-t0:.1f}s | {n_params/1e9:.2f}B params fp32 | " f"pixel-space, no VAE | sigmas={sigmas} | text encoder {TEXT_ENCODER_DIR}", flush=True) class ImageRequest(BaseModel): prompt: str = Field(..., description="Text prompt, encoded by the frozen Qwen3-VL-4B-Instruct stack (300 token budget; longer captions warn and truncate).") n: int = Field(1, description="Number of images, generated in ONE batched sampler call (the sampler takes a list of prompts).") size: str = Field("1024x1024", description="WxH in PIXELS — this model has no latent, so these are the real sampled dimensions. Both must be multiples of 16 (the pixel patch size). 2D RoPE makes any aspect ratio valid; the model was trained 256->512->1024 up to about one megapixel, and more pixels than that is extrapolation. Native is 1024x1024; 752x1344 and 896x1200 are among the author's listed shapes.") num_inference_steps: int = Field(100, description="DPM-Solver++ steps. Author's default is 100; fewer is faster with less detail. TURBO IGNORES THIS — its schedule is fixed at 4 sigmas and passing a value is a 400.") guidance_scale: float = Field(3.0, description="CFG scale. Author's default is 3.0. TURBO IGNORES THIS — guidance is baked into the distilled weights and passing a value is a 400.") order: int = Field(2, description="DPM-Solver++ order. Author's default is 2. Turbo: not applicable.") shift: float = Field(4.0, description="Rectified-flow timestep shift, from the checkpoint's flow.shift. Turbo: not applicable.") negative_prompt: str = Field("", description="CFG unconditional. Empty string is the dropout null used in training, which is what the author samples with. Turbo: not applicable (no CFG).") seed: Optional[int] = Field(None, description="Random seed. null = random per call.") response_format: str = Field("b64_json", description="Only b64_json supported.") # Fields that a distilled checkpoint has no meaning for. Mirrors the author's # scripts/sample.py, which refuses the same set rather than ignoring it. _TURBO_REJECTS = ("num_inference_steps", "guidance_scale", "order", "shift", "negative_prompt") def _params_doc(): out = {} for name, info in ImageRequest.model_fields.items(): d = info.default out[name] = {"default": None if d is ... else d, "description": info.description} if _state.get("sigmas"): for name in _TURBO_REJECTS: out[name]["fixed_by_distillation"] = True return out @app.get("/health") def health(): ok = bool(_state) return {"status": "ok" if ok else "degraded", "model": SERVED_MODEL_ID, "loaded": ok, "variant": VARIANT} @app.get("/v1/models") def models(): return {"object": "list", "data": [{"id": SERVED_MODEL_ID, "object": "model"}]} @app.get("/v1/config") def config(): sigmas = _state.get("sigmas") return {"model": SERVED_MODEL_ID, "variant": VARIANT, "params": _params_doc(), "latent_space": None, "sigmas": sigmas, "notes": [ "PIXEL-SPACE: no VAE, no latent. The DiT patches the noisy RGB image " "itself (in_channels 3, patch_size 16), so `size` is the real sampled " "resolution and both dimensions must be multiples of 16.", "Trained 256->512->1024, up to about one megapixel; beyond ~1 MP is " "extrapolation. Any aspect ratio is valid (2D RoPE).", "Text encoder is a frozen Qwen3-VL-4B-Instruct and the DiT reads eleven " "of its hidden layers, so another Qwen3-VL size is not a substitute.", ("TURBO: 4 fixed sigmas with guidance baked in — steps, cfg, order, shift " "and negative_prompt are rejected with a 400, not ignored.") if sigmas else "BASE: 100 DPM-Solver++ steps / cfg 3.0 by default; use iris-3b-turbo for 4-step.", "NOT the `iris` on port 9047 (asdf98/IRIS-architecture, untrained). " "Different project, different authors.", "Apache-2.0, text encoder Apache-2.0 — commercial use is allowed.", ]} @app.post("/v1/images/generations") def generate_images(req: ImageRequest): if not _state: raise HTTPException(503, "model not loaded") if req.response_format != "b64_json": raise HTTPException(400, "only response_format=b64_json is supported") try: w, h = (int(x) for x in req.size.lower().split("x")) except ValueError: raise HTTPException(400, f"size must look like 1024x1024; got {req.size}") if w % PATCH or h % PATCH: raise HTTPException(400, f"size must be a multiple of {PATCH} in both dimensions " f"(the pixel patch size); got {req.size}") if w <= 0 or h <= 0: raise HTTPException(400, f"size must be positive; got {req.size}") sigmas = _state["sigmas"] if sigmas: # Explicit beats ignored: name every field the caller set that the distilled # schedule cannot honour, instead of silently dropping it. sent = [f for f in _TURBO_REJECTS if req.model_fields_set and f in req.model_fields_set] if sent: raise HTTPException(400, f"{SERVED_MODEL_ID} is a distilled {len(sigmas)}-step model: " f"its schedule is fixed and guidance is baked into the " f"weights, so {', '.join(sent)} cannot be applied. Drop " f"them, or use the base model for a tunable sampler.") seed = req.seed if req.seed is not None else int(time.time() * 1000) % (2**31) cfg = _state["cfg"] prompts = [req.prompt] * req.n t0 = time.time() # FastAPI runs `def` endpoints in a threadpool; one model and one CUDA stream means # concurrent calls would interleave. Same guard as the other image servers here. with _lock: queued = time.time() - t0 generator = torch.Generator(device="cuda").manual_seed(seed) with torch.autocast("cuda", dtype=torch.bfloat16): if sigmas: images = generate_few_step( _state["model"], _state["text_encoder"], prompts, height=h, width=w, sigmas=sigmas, generator=generator, device="cuda", num_train_timesteps=cfg.flow.num_train_timesteps, prediction=cfg.flow.prediction) else: images = generate( _state["model"], _state["text_encoder"], prompts, height=h, width=w, steps=req.num_inference_steps, order=req.order, cfg_scale=req.guidance_scale, cfg_interval=tuple(cfg.sample.cfg_interval), shift=req.shift, negative_prompt=req.negative_prompt, generator=generator, device="cuda", num_train_timesteps=cfg.flow.num_train_timesteps, prediction=cfg.flow.prediction) # generate() returns [B,3,H,W] clamped to [-1,1]; the author's CLI hands that to # save_image(normalize=True, value_range=(-1,1)), which is this rescale. arr = ((images.float() + 1) * 127.5).round().clamp(0, 255).to(torch.uint8).cpu().numpy() data = [] for img in arr: pil = Image.fromarray(np.transpose(img, (1, 2, 0)), mode="RGB") buf = io.BytesIO(); pil.save(buf, format="PNG") data.append({"b64_json": base64.b64encode(buf.getvalue()).decode()}) elapsed = time.time() - t0 used = {"n": req.n, "size": req.size, "seed": seed, "variant": VARIANT, "pixel_space": True, "queued_s": round(queued, 3), "elapsed_s": round(elapsed, 3)} if sigmas: used.update({"sigmas": sigmas, "num_inference_steps": len(sigmas), "guidance_scale": None, "_note": "distilled schedule; guidance is baked into the weights"}) else: used.update({"num_inference_steps": req.num_inference_steps, "guidance_scale": req.guidance_scale, "order": req.order, "shift": req.shift, "negative_prompt": req.negative_prompt}) print(f"Generated {len(data)} image(s) at {req.size} in {elapsed:.1f}s ({VARIANT})", flush=True) return JSONResponse({"created": int(time.time()), "data": data, "params_used": used}) if __name__ == "__main__": print(f"iris-3b ({VARIANT}) adapter on :{PORT}", flush=True) _load() uvicorn.run(app, host="0.0.0.0", port=PORT)