motif64

m64_60db135e0456 / zimage_server.py

143 lines, 4.6 KBraw
1"""OpenAI-style /v1/images/generations server for Z-Image-Turbo 6B (m64 capsule).23Ported from gx10:~/code/vlmtest/z_image_server.py (run by machines/gx10/start_z_image_turbo.sh),4through the sana15-1.6b-gb10 capsule's server. Differences from the original:5- weights load from /weights/zimage (an m64 artifact mount), port from M64_PORT;6- size, steps and guidance are baked constants (the capsule's [params], the original's7  z-image-turbo-6b defaults: 9 steps, guidance 0, which Turbo requires); a request carries8  only `prompt` and `seed` (the m64 front rejects anything else with a 400); one image;9- progress is reported as JSON lines appended to M64_STATUS.10"""1112import base6413import io14import json15import os16import secrets17import threading18import time19import traceback20from typing import Optional2122import torch23import uvicorn24from fastapi import FastAPI, HTTPException25from fastapi.responses import JSONResponse26from pydantic import BaseModel, Field2728SERVED_MODEL_ID = "z-image-turbo-6b"29WEIGHTS = "/weights/zimage"30PORT = int(os.environ["M64_PORT"])31STATUS = os.environ["M64_STATUS"]3233# Baked generation settings. Keep in sync with [params] in capsule.toml.34SIZE = "1024x1024"35NUM_INFERENCE_STEPS = 936GUIDANCE_SCALE = 0.0  # Turbo is distilled for CFG off37WIDTH, HEIGHT = (int(x) for x in SIZE.split("x"))38MAX_SEED = 2**63 - 13940app = FastAPI()41pipe = None42lock = threading.Lock()  # one generation at a time on the single pipeline434445def status(phase: str, **extra) -> None:46    with open(STATUS, "a") as f:47        f.write(json.dumps({"phase": phase, **extra}) + "\n")484950def load_model() -> None:51    global pipe52    from diffusers import ZImagePipeline5354    status("loading", progress=0.0, detail="loading Z-Image-Turbo 6B (bf16)")55    print("Loading Z-Image-Turbo 6B...", flush=True)56    t0 = time.time()57    # Same arguments as the original server.58    pipe = ZImagePipeline.from_pretrained(WEIGHTS, torch_dtype=torch.bfloat16, low_cpu_mem_usage=False)59    pipe.to("cuda")60    print(f"Model loaded in {time.time() - t0:.1f}s.", flush=True)6162    status("warming", detail="one short warm-up generation")63    t0 = time.time()64    with lock:65        pipe(prompt="warm-up", width=WIDTH, height=HEIGHT, num_inference_steps=2,66             guidance_scale=GUIDANCE_SCALE, generator=torch.Generator("cuda").manual_seed(0))67    print(f"Warm-up done in {time.time() - t0:.1f}s.", flush=True)686970class ImageRequest(BaseModel):71    prompt: str = Field(..., min_length=1, description="Text prompt")72    seed: Optional[int] = Field(None, ge=0, le=MAX_SEED, description="RNG seed. null = random; the one used is returned.")737475def baked() -> dict:76    return {"size": SIZE, "num_inference_steps": NUM_INFERENCE_STEPS, "guidance_scale": GUIDANCE_SCALE}777879@app.get("/health")80def health():81    if pipe is None:82        raise HTTPException(503, "Model not loaded")83    return {"status": "ok", "model": SERVED_MODEL_ID}848586@app.get("/v1/config")87def config():88    return {89        "model": SERVED_MODEL_ID,90        "params": baked(),91        "request_fields": {92            "prompt": {"required": True, "description": "Text prompt"},93            "seed": {"required": False, "default": None, "description": "RNG seed; null = random"},94        },95    }969798@app.post("/v1/images/generations")99def generate(req: ImageRequest):100    if pipe is None:101        raise HTTPException(503, "Model not loaded")102    seed = req.seed if req.seed is not None else secrets.randbelow(2**31)103    t0 = time.time()104    with lock:105        gen = torch.Generator("cuda").manual_seed(seed)106        images = pipe(107            prompt=req.prompt,108            width=WIDTH, height=HEIGHT,109            num_inference_steps=NUM_INFERENCE_STEPS,110            guidance_scale=GUIDANCE_SCALE,111            num_images_per_prompt=1,112            generator=gen,113        ).images114    elapsed = time.time() - t0115    print(f"Generated {len(images)} image(s) in {elapsed:.1f}s (seed {seed})", flush=True)116    data = []117    for img in images:118        buf = io.BytesIO()119        img.save(buf, format="PNG")120        data.append({"b64_json": base64.b64encode(buf.getvalue()).decode()})121    return JSONResponse({122        "created": int(time.time()),123        "model": SERVED_MODEL_ID,124        "seed": seed,125        "elapsed_seconds": round(elapsed, 2),126        "data": data,127        "params_used": {**baked(), "seed": seed},128    })129130131def main() -> None:132    try:133        load_model()134    except Exception:135        traceback.print_exc()136        status("error", detail="model load failed; see container logs")137        raise138    status("ready")139    uvicorn.run(app, host="0.0.0.0", port=PORT)  # the gate reaches us over the capsule network140141142if __name__ == "__main__":143    main()