motif64

m64_3ad665d84176 / iris3b_server.py

258 lines, 13.6 KBraw
1"""OpenAI-compatible /v1/images/generations front end for Iris-3B.23speridlabs/iris-3b — "Iris-3B: Going Beyond the Latent with Pixel-Space Diffusion4Training, Conversion and Fine-Tuning" (arXiv 2610.09450). A 3B diffusion transformer5that works DIRECTLY IN PIXEL SPACE: there is no VAE and no latent anywhere in the6graph. The noisy image is cut into 16x16 RGB patches (in_channels 3, patch_size 16),78 dual-stream blocks and 16 single-stream blocks run over them with 2D RoPE, and a8small pixel head paints the result. Every other diffusion model on this rig encodes9to a latent first; this one does not, which is the reason to have it.1011NOT THE SAME MODEL AS `iris` ON 9047. That is asdf98/IRIS-architecture, a 48-136M12architecture-only repo with no trained weights, by different authors. Unrelated. This13server deliberately does NOT answer to the bare alias "iris" so a stale client cannot14silently land on the wrong one.1516TWO VARIANTS, one code path, selected by IRIS_VARIANT:17  * base  — 100 DPM-Solver++ steps (order 2), cfg 3.0, flow shift 4.0. FP32 weights.18  * turbo — the distilled 4-step model. Its distill.yaml carries the four sigmas and19    guidance is BAKED INTO THE WEIGHTS, so there is no step count, no CFG, no negative20    prompt and no shift to set. Asking for any of them is a 400 here, mirroring what21    the author's own scripts/sample.py does (it calls parser.error on exactly that22    combination) rather than quietly ignoring the request.2324Model code is VENDORED, not reimplemented: /home/dh/code/iris3b pinned at commit25cee0c13 is mounted read-only and imported, so IrisDiT, FlowDPMSolver, the Qwen3-VL26text encoder and both generate() paths are the author's own modules. Only the HTTP27shape is ours.2829The text encoder is a FROZEN Qwen3-VL-4B-Instruct, and the model reads ELEVEN hidden30layers out of it (2,5,8,...,35) rather than just the last, so another Qwen3-VL size is31not a drop-in: text_encoder.dim must be 2560. It is served from a local directory32because the container runs HF_HUB_OFFLINE=1.3334Weights are FP32 with a BF16 autocast at the forward, which is how the author's35sample.py loads them.3637LICENSE: Apache-2.0, text encoder Apache-2.0 — commercial-OK.3839Defaults are hardcoded in ImageRequest below and echoed per call under "params_used";40query them via GET /v1/config.41"""42import base64, io, os, sys, threading, time43from typing import Optional4445import numpy as np46import torch47from fastapi import FastAPI, HTTPException48from fastapi.responses import JSONResponse49from PIL import Image50from pydantic import BaseModel, Field51import uvicorn5253IRIS_SRC = os.environ.get("IRIS_SRC", "/iris3b/src")54sys.path.insert(0, IRIS_SRC)5556from omegaconf import OmegaConf                                      # noqa: E40257from iris3b.config import inference_config                           # noqa: E40258from iris3b.models.dit import IrisDiT                                # noqa: E40259from iris3b.registry import TEXT_ENCODERS                            # noqa: E40260from iris3b.sampling import generate, generate_few_step, load_for_inference  # noqa: E40261import iris3b.text  # noqa: E402,F401  — registers the encoders6263VARIANT = os.environ.get("IRIS_VARIANT", "base")64SERVED_MODEL_ID = os.environ.get("SERVED_MODEL_ID", f"iris-3b{'' if VARIANT == 'base' else '-' + VARIANT}")65PORT = int(os.environ.get("PORT", "9207"))66MODEL_DIR = os.environ.get("MODEL_DIR", "/model")67TEXT_ENCODER_DIR = os.environ.get("IRIS_TEXT_ENCODER", os.path.join(MODEL_DIR, "text_encoder"))68# inference_config() always drops a checkpoint's null_embed_dir as machine-local, so the69# default "output/pretrained_models" would be created relative to the CWD. The model dir70# is mounted read-only, so point the cache somewhere writable.71NULL_EMBED_DIR = os.environ.get("IRIS_NULL_EMBED_DIR", "/tmp/iris-null-embeds")7273CKPT_DIR = MODEL_DIR if VARIANT == "base" else os.path.join(MODEL_DIR, VARIANT)74PATCH = 16          # pixel patch size — H and W must be multiples of it75MAX_PIXELS = 1 << 20  # the model is trained to ~1 megapixel; beyond that is extrapolation7677app = FastAPI()78_lock = threading.Lock()   # one model, one CUDA stream; see generate_images()79_state = {}808182def _load():83    t0 = time.time()84    raw, weights = load_for_inference(CKPT_DIR)85    cfg = inference_config(raw, [86        f"text_encoder.pretrained={TEXT_ENCODER_DIR}",87        f"text_encoder.null_embed_dir={NULL_EMBED_DIR}",88    ])89    # Built on the meta device, then the checkpoint tensors BECOME the parameters90    # (assign=True) — the author's own load path, and it avoids a second 12 GB copy.91    with torch.device("meta"):92        model = IrisDiT(cfg.model)93    model.load_state_dict(weights, strict=True, assign=True)94    model = model.eval().to(device="cuda", dtype=torch.float32)9596    text_encoder = TEXT_ENCODERS.build(cfg.text_encoder.name, cfg.text_encoder, device="cuda")9798    # A distilled export fixes its own schedule; its presence is what selects the99    # few-step path, exactly as scripts/sample.py decides it.100    distill = os.path.join(CKPT_DIR, "distill.yaml")101    sigmas = list(OmegaConf.load(distill).dmd.sigmas) if os.path.isfile(distill) else None102103    _state.update(dict(model=model, text_encoder=text_encoder, cfg=cfg, sigmas=sigmas))104    n_params = sum(p.numel() for p in model.parameters())105    print(f"iris-3b ({VARIANT}) loaded in {time.time()-t0:.1f}s | {n_params/1e9:.2f}B params fp32 | "106          f"pixel-space, no VAE | sigmas={sigmas} | text encoder {TEXT_ENCODER_DIR}", flush=True)107108109class ImageRequest(BaseModel):110    prompt: str = Field(..., description="Text prompt, encoded by the frozen Qwen3-VL-4B-Instruct stack (300 token budget; longer captions warn and truncate).")111    n: int = Field(1, description="Number of images, generated in ONE batched sampler call (the sampler takes a list of prompts).")112    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.")113    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.")114    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.")115    order: int = Field(2, description="DPM-Solver++ order. Author's default is 2. Turbo: not applicable.")116    shift: float = Field(4.0, description="Rectified-flow timestep shift, from the checkpoint's flow.shift. Turbo: not applicable.")117    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).")118    seed: Optional[int] = Field(None, description="Random seed. null = random per call.")119    response_format: str = Field("b64_json", description="Only b64_json supported.")120121122# Fields that a distilled checkpoint has no meaning for. Mirrors the author's123# scripts/sample.py, which refuses the same set rather than ignoring it.124_TURBO_REJECTS = ("num_inference_steps", "guidance_scale", "order", "shift", "negative_prompt")125126127def _params_doc():128    out = {}129    for name, info in ImageRequest.model_fields.items():130        d = info.default131        out[name] = {"default": None if d is ... else d, "description": info.description}132    if _state.get("sigmas"):133        for name in _TURBO_REJECTS:134            out[name]["fixed_by_distillation"] = True135    return out136137138@app.get("/health")139def health():140    ok = bool(_state)141    return {"status": "ok" if ok else "degraded", "model": SERVED_MODEL_ID,142            "loaded": ok, "variant": VARIANT}143144145@app.get("/v1/models")146def models():147    return {"object": "list", "data": [{"id": SERVED_MODEL_ID, "object": "model"}]}148149150@app.get("/v1/config")151def config():152    sigmas = _state.get("sigmas")153    return {"model": SERVED_MODEL_ID, "variant": VARIANT, "params": _params_doc(),154            "latent_space": None,155            "sigmas": sigmas,156            "notes": [157                "PIXEL-SPACE: no VAE, no latent. The DiT patches the noisy RGB image "158                "itself (in_channels 3, patch_size 16), so `size` is the real sampled "159                "resolution and both dimensions must be multiples of 16.",160                "Trained 256->512->1024, up to about one megapixel; beyond ~1 MP is "161                "extrapolation. Any aspect ratio is valid (2D RoPE).",162                "Text encoder is a frozen Qwen3-VL-4B-Instruct and the DiT reads eleven "163                "of its hidden layers, so another Qwen3-VL size is not a substitute.",164                ("TURBO: 4 fixed sigmas with guidance baked in — steps, cfg, order, shift "165                 "and negative_prompt are rejected with a 400, not ignored.") if sigmas else166                "BASE: 100 DPM-Solver++ steps / cfg 3.0 by default; use iris-3b-turbo for 4-step.",167                "NOT the `iris` on port 9047 (asdf98/IRIS-architecture, untrained). "168                "Different project, different authors.",169                "Apache-2.0, text encoder Apache-2.0 — commercial use is allowed.",170            ]}171172173@app.post("/v1/images/generations")174def generate_images(req: ImageRequest):175    if not _state:176        raise HTTPException(503, "model not loaded")177    if req.response_format != "b64_json":178        raise HTTPException(400, "only response_format=b64_json is supported")179    try:180        w, h = (int(x) for x in req.size.lower().split("x"))181    except ValueError:182        raise HTTPException(400, f"size must look like 1024x1024; got {req.size}")183    if w % PATCH or h % PATCH:184        raise HTTPException(400, f"size must be a multiple of {PATCH} in both dimensions "185                                 f"(the pixel patch size); got {req.size}")186    if w <= 0 or h <= 0:187        raise HTTPException(400, f"size must be positive; got {req.size}")188189    sigmas = _state["sigmas"]190    if sigmas:191        # Explicit beats ignored: name every field the caller set that the distilled192        # schedule cannot honour, instead of silently dropping it.193        sent = [f for f in _TURBO_REJECTS194                if req.model_fields_set and f in req.model_fields_set]195        if sent:196            raise HTTPException(400, f"{SERVED_MODEL_ID} is a distilled {len(sigmas)}-step model: "197                                     f"its schedule is fixed and guidance is baked into the "198                                     f"weights, so {', '.join(sent)} cannot be applied. Drop "199                                     f"them, or use the base model for a tunable sampler.")200201    seed = req.seed if req.seed is not None else int(time.time() * 1000) % (2**31)202    cfg = _state["cfg"]203    prompts = [req.prompt] * req.n204    t0 = time.time()205206    # FastAPI runs `def` endpoints in a threadpool; one model and one CUDA stream means207    # concurrent calls would interleave. Same guard as the other image servers here.208    with _lock:209        queued = time.time() - t0210        generator = torch.Generator(device="cuda").manual_seed(seed)211        with torch.autocast("cuda", dtype=torch.bfloat16):212            if sigmas:213                images = generate_few_step(214                    _state["model"], _state["text_encoder"], prompts,215                    height=h, width=w, sigmas=sigmas, generator=generator, device="cuda",216                    num_train_timesteps=cfg.flow.num_train_timesteps,217                    prediction=cfg.flow.prediction)218            else:219                images = generate(220                    _state["model"], _state["text_encoder"], prompts,221                    height=h, width=w,222                    steps=req.num_inference_steps, order=req.order,223                    cfg_scale=req.guidance_scale,224                    cfg_interval=tuple(cfg.sample.cfg_interval),225                    shift=req.shift, negative_prompt=req.negative_prompt,226                    generator=generator, device="cuda",227                    num_train_timesteps=cfg.flow.num_train_timesteps,228                    prediction=cfg.flow.prediction)229        # generate() returns [B,3,H,W] clamped to [-1,1]; the author's CLI hands that to230        # save_image(normalize=True, value_range=(-1,1)), which is this rescale.231        arr = ((images.float() + 1) * 127.5).round().clamp(0, 255).to(torch.uint8).cpu().numpy()232233    data = []234    for img in arr:235        pil = Image.fromarray(np.transpose(img, (1, 2, 0)), mode="RGB")236        buf = io.BytesIO(); pil.save(buf, format="PNG")237        data.append({"b64_json": base64.b64encode(buf.getvalue()).decode()})238239    elapsed = time.time() - t0240    used = {"n": req.n, "size": req.size, "seed": seed, "variant": VARIANT,241            "pixel_space": True, "queued_s": round(queued, 3),242            "elapsed_s": round(elapsed, 3)}243    if sigmas:244        used.update({"sigmas": sigmas, "num_inference_steps": len(sigmas),245                     "guidance_scale": None,246                     "_note": "distilled schedule; guidance is baked into the weights"})247    else:248        used.update({"num_inference_steps": req.num_inference_steps,249                     "guidance_scale": req.guidance_scale, "order": req.order,250                     "shift": req.shift, "negative_prompt": req.negative_prompt})251    print(f"Generated {len(data)} image(s) at {req.size} in {elapsed:.1f}s ({VARIANT})", flush=True)252    return JSONResponse({"created": int(time.time()), "data": data, "params_used": used})253254255if __name__ == "__main__":256    print(f"iris-3b ({VARIANT}) adapter on :{PORT}", flush=True)257    _load()258    uvicorn.run(app, host="0.0.0.0", port=PORT)