aqualaguna's picture
Add files using upload-large-folder tool
565b868 verified
Raw History Blame Contribute Delete
12 kB
#!/usr/bin/env python3
"""MOSS-Image text-to-image server for CT 140: OpenMOSS-Team/MOSS-Image-SFT (Apache-2.0, 5B DiT + Qwen3.5-9B text encoder + FLUX.2 VAE)
on the Arc GPU through OpenVINO, behind one gateway aux route.
POST /v1/mossimage JSON {"prompt": "..." | {layout object}, "width": 1024, "height": 1024, "steps": 30, ...} -> JSON (+ image files)
GET /health 200 once the DiT is in memory and the text encoder has run once (the gateway waits for it)
The gateway replays the body byte for byte and keeps only a text/JSON answer, so the images are files: they are written into the
job's output dir (header x-job-out-dir, set by the gateway) and listed in `files`; the caller downloads them with
GET /v1/jobs/<id>/files/<name>. Called directly (no gateway) they land in $MOSSIMAGE_OUT_DIR/<random>. See the gateway's docs/MOSSIMAGE.md.
"""
import argparse
import asyncio
import gc
import io
import json
import os
import random
import sys
import tempfile
import threading
import time
import uuid
from aiohttp import web
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from moss_pipeline import VARIANTS, Cancelled, MAX_TEXT_TOKENS, MossImage # noqa: E402
MODEL_NAME = "MOSS-Image-SFT"
MODEL_NAMES = {"sft": "MOSS-Image-SFT", "sft-int8": "MOSS-Image-SFT (int8 weights, ffn_down in fp16)"}
MIN_SIDE, MAX_SIDE = 256, 2048
MAX_PIXELS = 1536 * 1152 # 1.77 MP: the DiT's scratch memory grows with the token count; this is the largest size that fits the 24 GB card with margin (fp16 models)
MAX_STEPS = 100
MAX_IMAGES = 4
FORMATS = {"png": ("PNG", "png"), "jpeg": ("JPEG", "jpg"), "webp": ("WEBP", "webp")}
MODELS_DIR = os.environ.get("MOSSIMAGE_MODELS_DIR", os.path.join(os.path.dirname(HERE), "models"))
CACHE_DIR = os.environ.get("MOSSIMAGE_CACHE_DIR", os.path.join(os.path.dirname(HERE), "cache"))
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
class Bad(Exception):
"""A request the caller must fix: answered as 4xx {"error": ...}, which the gateway passes through."""
def __init__(self, msg, code=400):
super().__init__(msg)
self.code = code
class State:
pipe = None
device = "GPU"
ready = False
gpu = threading.Lock() # one generation at a time inside the service, whatever the gateway does
def number(body, key, default, lo, hi, integer=False):
v = body.get(key, default)
if isinstance(v, bool) or not isinstance(v, (int, float)) or not lo <= v <= hi or (integer and int(v) != v):
raise Bad(f"`{key}` must be {'an integer' if integer else 'a number'} in [{lo}, {hi}]")
return int(v) if integer else float(v)
def prompt_text(v, field):
"""A prompt is a string, or a layout object/list that is serialised the way the model was trained on (ensure_ascii=False)."""
if isinstance(v, (dict, list)):
v = json.dumps(v, ensure_ascii=False)
if not isinstance(v, str):
raise Bad(f"`{field}` must be a string (or a layout object)")
return v
def check_size(width, height, max_pixels=MAX_PIXELS):
if width % 16 or height % 16:
raise Bad("`width` and `height` must be multiples of 16")
if not (MIN_SIDE <= width <= MAX_SIDE and MIN_SIDE <= height <= MAX_SIDE):
raise Bad(f"`width` and `height` must be between {MIN_SIDE} and {MAX_SIDE}")
if width * height > max_pixels:
eg = "1536x1536, 2048x1152, 1792x1280" if max_pixels > MAX_PIXELS else "1536x1152, 1280x1280, 1792x960, 2048x864"
raise Bad(f"{width}x{height} is {width * height / 1e6:.2f} MP; the limit is {max_pixels / 1e6:.2f} MP (e.g. {eg}): "
"the card runs out of memory above it")
def work(body, ctx):
prompt = body.get("prompt")
if prompt is None or prompt == "":
raise Bad("`prompt` is required: text, or a layout object (summary / items / bbox_format / bbox_coord_space)")
prompt = prompt_text(prompt, "prompt")
if not prompt.strip():
raise Bad("`prompt` is empty")
variant = body.get("model", "sft")
if not isinstance(variant, str) or variant not in VARIANTS:
raise Bad(f"`model` must be one of: {', '.join(VARIANTS)}")
installed = State.pipe.installed_variants()
if variant not in installed:
raise Bad(f"model `{variant}` is not installed on this server; installed: {', '.join(installed)}")
vcfg = VARIANTS[variant]
negative = prompt_text(body.get("negative_prompt", ""), "negative_prompt")
width = number(body, "width", 1024, 16, 100000, integer=True)
height = number(body, "height", 1024, 16, 100000, integer=True)
check_size(width, height, vcfg.get("max_pixels", MAX_PIXELS))
steps = number(body, "steps", vcfg["default_steps"], 1, vcfg["max_steps"], integer=True)
guidance = number(body, "guidance", 3.0, 0.0, 15.0)
n = number(body, "n", 1, 1, MAX_IMAGES, integer=True)
seed = body.get("seed")
if seed is None:
seed = random.randrange(0, 2**31 - 1 - MAX_IMAGES)
else:
seed = number(body, "seed", None, 0, 2**31 - 1 - MAX_IMAGES, integer=True)
fmt = body.get("format", "png")
if fmt not in FORMATS:
raise Bad(f"`format` must be one of: {', '.join(FORMATS)}")
quality = number(body, "quality", 95, 1, 100, integer=True)
skip = body.get("uncond_skip", True)
if not isinstance(skip, bool):
raise Bad("`uncond_skip` must be true or false")
for key, val in (("prompt", prompt), ("negative_prompt", negative)):
if val:
count = State.pipe.token_count(val)
if count > MAX_TEXT_TOKENS:
raise Bad(f"`{key}` is {count} tokens; the limit is {MAX_TEXT_TOKENS}")
t = time.time()
images, rows = [], []
stats = None
cancel = ctx.get("cancel")
from PIL import Image, PngImagePlugin
with State.gpu:
for i in range(n):
s = seed + i
marks = [0]
def progress(done, total, i=i):
if done - marks[0] >= 10 or done == total:
marks[0] = done
log(f" image {i + 1}/{n} step {done}/{total} ({time.time() - t:.0f} s)")
img, st = State.pipe.generate(prompt, negative, width, height, steps, guidance, s, skip_uncond_block=skip, progress=progress,
cancel=(cancel.is_set if cancel is not None else None), variant=variant)
if not st["finite"]:
raise RuntimeError("the sampler produced non-finite values (fp16 overflow); try another seed or a smaller size")
name = f"image.{FORMATS[fmt][1]}" if n == 1 else f"image_{i + 1}.{FORMATS[fmt][1]}"
im = Image.fromarray(img)
kw = {}
if fmt == "png":
info = PngImagePlugin.PngInfo()
info.add_text("parameters", json.dumps({"model": variant, "prompt": prompt, "negative_prompt": negative, "seed": s, "steps": steps,
"guidance": guidance, "width": width, "height": height}, ensure_ascii=False))
kw["pnginfo"] = info
elif fmt == "jpeg":
kw.update(quality=quality)
else:
kw.update(quality=quality, method=4)
im.save(os.path.join(ctx["out_dir"], name), FORMATS[fmt][0], **kw)
images.append(name)
rows.append({"file": name, "seed": s})
stats = st
took = time.time() - t
gc.collect()
return {"files": images, "images": rows, "model": variant, "model_name": MODEL_NAMES[variant], "width": width, "height": height, "steps": stats["steps"], "steps_requested": steps,
"guidance": guidance, "negative_prompt": negative, "uncond_skip": skip, "format": fmt, "n": n, "seed": seed,
"prompt_tokens": stats["tokens_prompt"], "negative_tokens": stats["tokens_negative"],
"seconds": round(took, 2), "text_encoder_seconds": stats["text_encoder_s"], "denoise_seconds": stats["denoise_s"],
"seconds_per_step": stats["s_per_step"], "model_load_seconds": stats.get("dit_load_s", 0.0), "vae_seconds": stats["vae_s"], "peak_gpu_mb": stats["peak_gpu_usm_device_mb"],
"job": ctx["job"], "device": State.device}
async def mossimage(request):
try:
body = await request.json()
except ValueError:
return web.json_response({"error": "body is not valid JSON"}, status=400)
if not isinstance(body, dict):
return web.json_response({"error": "body must be a JSON object"}, status=400)
if not State.ready:
return web.json_response({"error": "the service is still loading its models; retry in a minute"}, status=503)
t = time.time()
out_dir = request.headers.get("x-job-out-dir")
if not out_dir: # called without the gateway: keep the files where the caller can find them
out_dir = os.path.join(os.environ.get("MOSSIMAGE_OUT_DIR") or os.path.join(tempfile.gettempdir(), "mossimage-out"), uuid.uuid4().hex[:12])
os.makedirs(out_dir, exist_ok=True)
cancel = threading.Event()
ctx = {"out_dir": out_dir, "job": request.headers.get("x-job-id"), "cancel": cancel}
fut = asyncio.get_running_loop().run_in_executor(None, work, body, ctx)
fut.add_done_callback(lambda f: None if f.cancelled() else f.exception()) # mark a late error (after a hang-up) as retrieved
try:
out = await asyncio.shield(fut)
except asyncio.CancelledError: # the caller hung up: stop denoising at the next step
cancel.set()
raise
except Bad as e:
return web.json_response({"error": str(e)}, status=e.code)
except Cancelled:
return web.json_response({"error": "cancelled"}, status=499)
except Exception as e:
log("generation failed:", repr(e))
msg = f"{type(e).__name__}: {e}"
return web.json_response({"error": msg[:600]}, status=500)
if not request.headers.get("x-job-out-dir"):
out["out_dir"] = out_dir
log(f"{out['n']} image(s) {out['width']}x{out['height']} {out['steps']} steps in {time.time() - t:.1f} s")
return web.json_response(out)
async def health(request):
if not State.ready:
return web.json_response({"ok": False, "loading": True}, status=503)
return web.json_response({"ok": True, "model": MODEL_NAME, "device": State.device, "max_pixels": MAX_PIXELS, "max_pixels_int8": VARIANTS["sft-int8"].get("max_pixels", MAX_PIXELS), "max_side": MAX_SIDE,
"max_steps": MAX_STEPS, "models": State.pipe.installed_variants(), "active": State.pipe.variant,
"resident": ["dit", "text_encoder (loaded per request)", "vae (loaded per request)"]})
def preload():
try:
t = time.time()
State.pipe = MossImage(MODELS_DIR, State.device, CACHE_DIR, log=lambda *a: log(*a), te_precision=os.environ.get("MOSSIMAGE_TE_PRECISION") or None)
State.pipe.warm()
log(f"warm in {time.time() - t:.1f} s")
except BaseException as e:
log("preload failed:", repr(e))
os._exit(1) # systemd shows 'failed' and the gateway reports the journal tail instead of waiting out the timeout
State.ready = True
log("ready")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=8109)
ap.add_argument("--device", default="GPU", choices=["GPU", "CPU"])
a = ap.parse_args()
State.device = a.device
app = web.Application(client_max_size=8 * 2**20)
app.add_routes([web.post("/v1/mossimage", mossimage), web.get("/health", health)])
async def start(app):
loop = asyncio.get_running_loop()
app["preload"] = loop.run_in_executor(None, preload)
app.on_startup.append(start)
web.run_app(app, host=a.host, port=a.port, print=lambda *_: None)
if __name__ == "__main__":
main()