"""mossimage server test. usage: server_test.py BASE [TOKEN] (BASE = the service itself, http://127.0.0.1:8297, or the gateway) Runs on CT 140 with the /opt/mossimage venv. About 6 minutes of GPU. Prints PASS/FAIL lines and exits 1 on any failure.""" import io import json import os import sys import time import urllib.error import urllib.request import numpy as np from PIL import Image BASE = sys.argv[1].rstrip("/") HDR = {"content-type": "application/json"} if len(sys.argv) > 2: HDR["authorization"] = "Bearer " + sys.argv[2] ROUTE = "/v1/mossimage" fails = [] def check(name, ok, extra=""): print(("PASS " if ok else "FAIL ") + name + (f" {extra}" if extra else ""), flush=True) if not ok: fails.append(name) def post(body, timeout=900, raw=None): data = raw if raw is not None else json.dumps(body).encode() req = urllib.request.Request(BASE + ROUTE, data=data, headers=HDR, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, json.loads(r.read()) except urllib.error.HTTPError as e: raw = e.read() try: return e.code, json.loads(raw) except ValueError: return e.code, {"error": raw.decode("utf-8", "replace")} def fetch(r, name): """The bytes of a result file: from the job's file URL (gateway) or from the out dir (service called directly).""" if r.get("out_dir"): return open(os.path.join(r["out_dir"], name), "rb").read() req = urllib.request.Request(f"{BASE}/v1/jobs/{r['job']}/files/{name}", headers=HDR) with urllib.request.urlopen(req, timeout=300) as resp: return resp.read() def image(r, name=None): return Image.open(io.BytesIO(fetch(r, name or r["files"][0]))) def psnr(a, b): mse = np.mean((np.asarray(a, np.float64) - np.asarray(b, np.float64)) ** 2) return 99.0 if mse == 0 else 10 * np.log10(255.0 ** 2 / mse) def msg(r): return r.get("error") or r.get("detail") or "" # --- validation: every refusal is a 400 naming the field long_prompt = "a red apple on a wooden table. " * 700 # ~5000+ tokens for body, frag, name in [ ({}, "prompt", "no prompt -> 400"), ({"prompt": ""}, "prompt", "empty prompt -> 400"), ({"prompt": 5}, "prompt", "numeric prompt -> 400"), ({"prompt": "x", "width": 1000}, "multiples of 16", "width not a multiple of 16 -> 400"), ({"prompt": "x", "width": 128, "height": 128}, "between", "too small -> 400"), ({"prompt": "x", "width": 2048, "height": 2048}, "limit", "too many pixels -> 400"), ({"prompt": "x", "width": 2064, "height": 512}, "between", "side over 2048 -> 400"), ({"prompt": "x", "steps": 0}, "steps", "steps 0 -> 400"), ({"prompt": "x", "steps": 101}, "steps", "steps 101 -> 400"), ({"prompt": "x", "steps": 10.5}, "steps", "fractional steps -> 400"), ({"prompt": "x", "guidance": -1}, "guidance", "negative guidance -> 400"), ({"prompt": "x", "format": "gif"}, "format", "unknown format -> 400"), ({"prompt": "x", "n": 5}, "`n`", "n=5 -> 400"), ({"prompt": "x", "seed": -1}, "seed", "negative seed -> 400"), ({"prompt": "x", "seed": "a"}, "seed", "string seed -> 400"), ({"prompt": "x", "uncond_skip": "yes"}, "uncond_skip", "uncond_skip not boolean -> 400"), ({"prompt": "x", "negative_prompt": 3}, "negative_prompt", "numeric negative -> 400"), ({"prompt": long_prompt}, "tokens", "prompt over 4096 tokens -> 400"), ]: code, r = post(body) check(name, code == 400 and frag in msg(r), f"{code} {msg(r)[:110]}") code, r = post(None, raw=b"{not json") check("invalid JSON -> 400", code == 400, f"{code} {msg(r)[:80]}") code, r = post(None, raw=b"[1, 2]") check("JSON array body -> 400", code == 400, f"{code} {msg(r)[:80]}") # --- a small generation, then the same again, then another seed body = {"prompt": "A red fox sitting in fresh snow at sunrise, photograph", "width": 512, "height": 512, "steps": 12, "seed": 7} t = time.time() code, a = post(body) dt = time.time() - t check("512x512, 12 steps -> 200 with one png", code == 200 and a.get("files") == ["image.png"] and (a.get("job") is not None or a.get("out_dir")), f"{code} {str(a)[:200]}") if code == 200: ia = image(a) arr = np.asarray(ia.convert("RGB")) check("png is 512x512 RGB, not flat, not clipped", ia.size == (512, 512) and ia.mode == "RGB" and 20 < arr.std() < 110 and 0 < arr.mean() < 255, f"size {ia.size} mean {arr.mean():.0f} std {arr.std():.0f}") meta = json.loads(ia.text.get("parameters", "{}")) check("png carries its parameters (seed, steps, prompt)", meta.get("seed") == 7 and meta.get("steps") == 12 and "fox" in meta.get("prompt", ""), str(meta)[:120]) check("answer reports timing and tokens", all(k in a for k in ("seconds", "seconds_per_step", "prompt_tokens", "negative_tokens", "peak_gpu_mb", "images")) and a["steps"] == 12, f"{dt:.1f} s total, {a.get('seconds_per_step')} s/step, {a.get('prompt_tokens')}+{a.get('negative_tokens')} tokens") code, b = post(body) check("same request again -> 200", code == 200, f"{code}") if code == 200: p = psnr(arr, np.asarray(image(b).convert("RGB"))) check("same seed reproduces the image (PSNR >= 40 dB)", p >= 40, f"{p:.1f} dB") code, c = post({**body, "seed": 8}) if code == 200: p = psnr(arr, np.asarray(image(c).convert("RGB"))) check("another seed gives another image (PSNR < 25 dB)", p < 25, f"{p:.1f} dB") else: check("seed 8 -> 200", False, f"{code} {msg(c)}") # --- shape, format, count: two jpegs of 640x384, seeds consecutive code, r = post({"prompt": "A lighthouse on a cliff in a storm, oil painting", "width": 640, "height": 384, "steps": 6, "seed": 100, "n": 2, "format": "jpeg"}) check("n=2 jpeg 640x384 -> 2 files", code == 200 and r.get("files") == ["image_1.jpg", "image_2.jpg"] and [x["seed"] for x in r.get("images", [])] == [100, 101], f"{code} {str(r)[:160]}") if code == 200: sizes = [image(r, f).size for f in r["files"]] check("both are 640x384 JPEG", sizes == [(640, 384)] * 2 and image(r, r["files"][0]).format == "JPEG", str(sizes)) # --- layout object as the prompt == the same layout as a string; guidance 1 (no negative branch) layout = {"summary": {"meta": ["poster"], "canvas": "single", "caption": "A minimalist travel poster, cream background, blue mountain, the title EXPLORE at the top."}, "items": [{"label": "text", "caption": "Large dark-blue uppercase title.", "text": "EXPLORE", "bbox": [-208, -192, -144, 192]}, {"label": "object", "caption": "A flat blue mountain.", "bbox": [-96, -144, 192, 144]}], "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"} code, r1 = post({"prompt": layout, "width": 512, "height": 512, "steps": 4, "seed": 3}) code2, r2 = post({"prompt": json.dumps(layout, ensure_ascii=False), "width": 512, "height": 512, "steps": 4, "seed": 3}) check("layout object prompt works and equals the same layout sent as a string", code == 200 and code2 == 200 and r1["prompt_tokens"] == r2["prompt_tokens"] > 100 and psnr(np.asarray(image(r1)), np.asarray(image(r2))) >= 40, f"{code}/{code2} tokens {r1.get('prompt_tokens')}/{r2.get('prompt_tokens')}") code, r = post({"prompt": "A cup of tea on a table", "width": 512, "height": 512, "steps": 4, "seed": 1, "guidance": 1}) check("guidance 1 runs one forward per step (no negative branch)", code == 200 and r.get("negative_tokens") is None, f"{code} {str(r)[:140]}") code, r = post({"prompt": "A cup of tea on a table", "negative_prompt": "nsfw, worst quality, bad anatomy, watermark, jpeg artifact", "width": 512, "height": 512, "steps": 4, "seed": 1}) check("negative prompt is encoded", code == 200 and (r.get("negative_tokens") or 0) > 10, f"{code} neg tokens {r.get('negative_tokens')}") # --- the largest size the service takes (memory edge): 1536x1152, 2 steps t = time.time() code, r = post({"prompt": "A mountain village at dusk, warm lights", "width": 1536, "height": 1152, "steps": 2, "seed": 5, "format": "webp"}) check("1536x1152 (the pixel limit) runs", code == 200 and image(r).size == (1536, 1152) and r.get("peak_gpu_mb", 99999) < 23500, f"{code} {time.time() - t:.0f} s, peak {r.get('peak_gpu_mb')} MB, {r.get('seconds_per_step')} s/step" if code == 200 else f"{code} {msg(r)}") # --- model variants (update1): both are generated for real. The default model is the fp16 SFT; update1 changes the default steps from 50 to 30 (50 stays selectable). FOX = "A red fox sitting in fresh snow at sunrise, photograph" for body_, frag_, name_ in [ ({"prompt": "x", "model": "nope"}, "sft-int8", "unknown model -> 400 naming the models"), ({"prompt": "x", "model": "dmd8"}, "sft-int8", "the removed 8-step LoRA model name dmd8 -> 400"), ({"prompt": "x", "model": 5}, "model", "numeric model -> 400"), ({"prompt": "x", "model": "sft-int8", "steps": 0}, "steps", "sft-int8 steps 0 -> 400"), ]: code, r = post(body_) check(name_, code == 400 and frag_ in msg(r), f"{code} {msg(r)[:120]}") check("sft-int8 accepts up to 100 steps (101 -> 400)", post({"prompt": "x", "model": "sft-int8", "steps": 101})[0] == 400) sft_png = arr if "arr" in globals() else None # default steps = 30, steps 50 stays selectable t = time.time() code, r = post({"prompt": FOX, "width": 512, "height": 512, "seed": 7}) check("sft: no `steps` -> 30 steps (the default), model sft", code == 200 and r.get("steps") == 30 and r.get("steps_requested") == 30 and r.get("model") == "sft" and r.get("guidance") == 3.0, f"{code} {time.time() - t:.1f} s, {r.get('seconds_per_step')} s/step" if code == 200 else f"{code} {msg(r)}") code, r = post({"prompt": FOX, "width": 256, "height": 256, "seed": 7, "steps": 50}) check("sft: steps 50 stays selectable", code == 200 and r.get("steps") == 50, f"{code} {r.get('seconds')} s" if code == 200 else f"{code} {msg(r)}") t = time.time() code, v0 = post({"prompt": FOX, "width": 512, "height": 512, "seed": 7, "model": "sft-int8"}) check("sft-int8: no `steps` -> 30 steps, model sft-int8, one png", code == 200 and v0.get("steps") == 30 and v0.get("model") == "sft-int8" and v0.get("files") == ["image.png"] and v0.get("guidance") == 3.0, f"{code} {time.time() - t:.1f} s total, model load {v0.get('model_load_seconds')} s, {v0.get('seconds_per_step')} s/step, peak {v0.get('peak_gpu_mb')} MB" if code == 200 else f"{code} {msg(v0)}") code, v50 = post({"prompt": FOX, "width": 256, "height": 256, "seed": 7, "steps": 50, "model": "sft-int8"}) check("sft-int8: steps 50 stays selectable", code == 200 and v50.get("steps") == 50, f"{code} {v50.get('seconds')} s" if code == 200 else f"{code} {msg(v50)}") b_ = {"prompt": FOX, "width": 512, "height": 512, "seed": 7, "model": "sft-int8", "steps": 12} code, v1 = post(b_) check("sft-int8 512x512 12 steps -> model sft-int8", code == 200 and v1.get("steps") == 12 and v1.get("model") == "sft-int8" and v1.get("files") == ["image.png"], f"{code} {v1.get('seconds_per_step')} s/step" if code == 200 else f"{code} {msg(v1)}") if code == 200: a_ = np.asarray(image(v1).convert("RGB")) check("sft-int8 png is not flat, not clipped", 20 < a_.std() < 110 and 0 < a_.mean() < 255, f"mean {a_.mean():.0f} std {a_.std():.0f}") code, v2 = post(b_) p2 = psnr(a_, np.asarray(image(v2).convert("RGB"))) if code == 200 else 0 check("sft-int8 same seed reproduces the image (PSNR >= 40 dB)", code == 200 and p2 >= 40, f"{code} {p2:.1f} dB") if sft_png is not None: p = psnr(sft_png, a_) # same prompt, seed and steps as the fp16 image above; int8 weights change the picture, only a gross failure is caught here check("sft-int8 stays recognisably close to the fp16 image of the same seed (PSNR >= 12 dB, informational bound)", p >= 12, f"{p:.1f} dB") # the plain sft-int8 model with FEW steps (8), with CFG (guidance 3: two forwards per step) and without (guidance 1: one forward per step); nothing but steps/guidance changes sp_ = {} for g_ in (3, 1): code, r = post({"prompt": FOX, "width": 512, "height": 512, "seed": 7, "steps": 8, "guidance": g_, "model": "sft-int8"}) ok_ = code == 200 and r.get("steps") == 8 and r.get("guidance") == g_ and r.get("model") == "sft-int8" and (r.get("negative_tokens") is not None) == (g_ != 1) check(f"sft-int8 steps 8, guidance {g_}: {'two forwards per step (negative prompt encoded)' if g_ != 1 else 'one forward per step (no negative pass)'}", ok_, f"{code} {r.get('seconds_per_step')} s/step, negative tokens {r.get('negative_tokens')}" if code == 200 else f"{code} {msg(r)}") if code == 200: sp_[g_] = r["seconds_per_step"] a_ = np.asarray(image(r).convert("RGB")) check(f"sft-int8 steps 8 guidance {g_}: png not flat", 15 < a_.std() < 110 and 0 < a_.mean() < 255, f"mean {a_.mean():.0f} std {a_.std():.0f}") if len(sp_) == 2: check("guidance 1 costs about half the time per step of guidance 3", sp_[1] < 0.8 * sp_[3], f"{sp_[1]} vs {sp_[3]} s/step") # the same on the fp16 model code, r = post({"prompt": FOX, "width": 512, "height": 512, "seed": 7, "steps": 8, "guidance": 1, "model": "sft"}) check("sft (fp16) steps 8, guidance 1 is accepted: one forward per step", code == 200 and r.get("steps") == 8 and r.get("negative_tokens") is None and r.get("model") == "sft", f"{code} {r.get('seconds_per_step')} s/step" if code == 200 else f"{code} {msg(r)}") # the default is untouched after all of that: no `model` field -> fp16 SFT, bit-for-bit the same image as at the start of this run code, b2 = post(body) check("no `model` field -> sft again, the first image is reproduced (PSNR >= 40 dB)", code == 200 and b2.get("model") == "sft" and sft_png is not None and psnr(sft_png, np.asarray(image(b2).convert("RGB"))) >= 40, f"{code} model {b2.get('model')} reload {b2.get('model_load_seconds')} s") if BASE.startswith("http://127.0.0.1:8297") or ":8109" in BASE: try: with urllib.request.urlopen(BASE + "/health", timeout=5) as r_: h_ = json.loads(r_.read()) check("/health lists the two models and the active one", sorted(h_.get("models", [])) == ["sft", "sft-int8"] and h_.get("active") == "sft", str(h_)[:200]) except Exception as e_: # noqa: BLE001 check("/health lists the models", False, repr(e_)) # memory edge: the pixel limit of the int8 model, 2 steps (the 1536x1152 run of the fp16 SFT is above). The int8 model may go up to 2.36 MP. code, r = post({"prompt": "x", "width": 1536, "height": 1536, "steps": 1, "model": "sft"}) check("sft (fp16) 1536x1536 -> 400 over the 1.77 MP limit", code == 400 and "limit" in msg(r), f"{code} {msg(r)[:100]}") code, r = post({"prompt": "x", "width": 1536, "height": 1664, "steps": 1, "model": "sft-int8"}) check("sft-int8 1536x1664 -> 400 over the 2.36 MP limit", code == 400 and "2.36" in msg(r), f"{code} {msg(r)[:100]}") for var_, (w_, h_) in (("sft-int8", (1536, 1536)), ("sft-int8", (2048, 1152))): t = time.time() code, r = post({"prompt": "A mountain village at dusk, warm lights", "width": w_, "height": h_, "steps": 2, "seed": 5, "model": var_, "format": "webp"}) check(f"{var_} {w_}x{h_} (its pixel limit) runs", code == 200 and image(r).size == (w_, h_) and r.get("peak_gpu_mb", 99999) < 23500, f"{code} {time.time() - t:.0f} s, peak {r.get('peak_gpu_mb')} MB, {r.get('seconds_per_step')} s/step" if code == 200 else f"{code} {msg(r)}") print(f"\n{len(fails)} FAILED: {fails}" if fails else "\nALL PASSED", flush=True) sys.exit(1 if fails else 0)