File size: 21,063 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""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)}")

# --- editing (models edit / edit-int8): the fox picture of this run is the canvas
import base64  # noqa: E402


def b64png(a):
    buf = io.BytesIO()
    Image.fromarray(a).save(buf, "PNG")
    return base64.b64encode(buf.getvalue()).decode()


if sft_png is not None:
    fox64 = b64png(sft_png)
    for body_, frag_, name_ in [
        ({"prompt": "x", "model": "edit"}, "image", "edit without an image -> 400"),
        ({"prompt": "x", "image": fox64}, "edit", "image with the t2i model -> 400 pointing to model edit"),
        ({"prompt": "x", "model": "edit", "image": "not base64 at all"}, "image", "unreadable image -> 400"),
        ({"prompt": "x", "model": "edit", "images": [fox64] * 2}, "at most 1", "2 images -> 400 (extra references not offered)"),
        ({"prompt": "x", "model": "edit", "image": fox64, "images": [fox64]}, "not both", "image and images -> 400"),
        ({"prompt": "x", "model": "edit", "image": fox64, "width": 512}, "both", "width without height -> 400"),
        ({"prompt": "x", "model": "edit", "image": fox64, "width": 1536, "height": 1536}, "edits at most", "edit over its pixel limit -> 400"),
        ({"prompt": "x", "model": "edit", "image": fox64, "steps": 0}, "steps", "edit steps 0 -> 400"),
    ]:
        code, r = post(body_)
        check(name_, code == 400 and frag_ in msg(r), f"{code} {msg(r)[:120]}")
    eb = {"prompt": "Change the red fox into a white arctic fox. Keep everything else in the image unchanged.", "model": "edit", "image": fox64,
          "width": 512, "height": 512, "steps": 12, "seed": 5}
    t = time.time()
    code, e1 = post(eb)
    check("edit 512x512 12 steps -> 200, one edit.png, mode edit, guidance 4, 1024 reference tokens", code == 200 and e1.get("files") == ["edit.png"] and e1.get("mode") == "edit"
          and e1.get("guidance") == 4.0 and e1.get("reference_tokens") == 1024 and e1.get("model") == "edit",
          f"{code} {time.time() - t:.1f} s, {e1.get('seconds_per_step')} s/step, prefill {e1.get('prefill_seconds')} s, peak {e1.get('peak_gpu_mb')} MB" if code == 200 else f"{code} {msg(e1)}")
    if code == 200:
        ea = np.asarray(image(e1).convert("RGB"))
        meta = json.loads(image(e1).text.get("parameters", "{}"))
        check("edit png is 512x512, carries model edit + references 1", ea.shape == (512, 512, 3) and meta.get("model") == "edit" and meta.get("references") == 1, str(meta)[:120])
        check("edit changed the picture (PSNR to the canvas < 30 dB)", psnr(ea, sft_png) < 30, f"{psnr(ea, sft_png):.1f} dB")
        code, e2 = post(eb)
        check("edit: same seed reproduces (PSNR >= 40 dB)", code == 200 and psnr(ea, np.asarray(image(e2).convert("RGB"))) >= 40, f"{code}")
    code, c1 = post({**eb, "prompt": "Keep the image exactly unchanged.", "image": "data:image/png;base64," + fox64})
    if code == 200:
        p = psnr(np.asarray(image(c1).convert("RGB")), sft_png)
        check("edit 'keep unchanged' (data: URL input) stays close to the canvas (PSNR >= 20 dB)", p >= 20, f"{p:.1f} dB")
    else:
        check("edit with a data: URL -> 200", False, f"{code} {msg(c1)}")
    lay_ = {"summary": {"caption": "Add a small red knitted hat on the fox's head. Keep everything else in the image unchanged."},
            "items": [{"label": "object", "caption": "A small red knitted hat.", "bbox": [-200, -60, -60, 120]}], "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"}
    code, l1 = post({**eb, "prompt": lay_, "steps": 8, "model": "edit-int8"})
    check("edit-int8 with a layout (bbox) prompt -> 200, model edit-int8, prompt over 60 tokens", code == 200 and l1.get("model") == "edit-int8" and l1.get("prompt_tokens", 0) > 60,
          f"{code} {l1.get('seconds_per_step')} s/step, peak {l1.get('peak_gpu_mb')} MB" if code == 200 else f"{code} {msg(l1)}")
    # default size follows image 1: a 800x600 canvas -> about 1 MP at 4:3; 2 steps keep it short
    wide = np.asarray(Image.fromarray(sft_png).resize((800, 600)))
    code, d1 = post({"prompt": "Keep the image exactly unchanged.", "model": "edit", "image": b64png(wide), "steps": 2, "seed": 1, "format": "jpeg"})
    check("edit without width/height: 800x600 canvas -> 1184x880 jpeg, warnings is a list", code == 200 and (d1.get("width"), d1.get("height")) == (1184, 880)
          and image(d1).size == (1184, 880) and isinstance(d1.get("warnings"), list), f"{code} {d1.get('width')}x{d1.get('height')} peak {d1.get('peak_gpu_mb')} MB" if code == 200 else f"{code} {msg(d1)}")
    # memory edge: both edit models at their 1024x1024 limit (2 steps), and one step over it
    big = b64png(np.asarray(Image.fromarray(sft_png).resize((1024, 1024))))
    for var_ in ("edit", "edit-int8"):
        code, r = post({"prompt": "Keep the image exactly unchanged.", "model": var_, "image": big, "width": 1024, "height": 1024, "steps": 2, "seed": 1, "format": "jpeg"})
        check(f"{var_} 1024x1024 (its limit) -> 200, finite, peak_gpu_mb <= 22000 (the gateway reservation)", code == 200 and 0 < r.get("peak_gpu_mb", 0) <= 22000,
              f"{code} peak {r.get('peak_gpu_mb')} MB" if code == 200 else f"{code} {msg(r)}")
    code, r = post({"prompt": "x", "model": "edit-int8", "image": big, "width": 1024, "height": 1040, "steps": 1})
    check("edit-int8 1024x1040 -> 400 over the 1.05 MP limit", code == 400 and "edits at most" in msg(r), f"{code} {msg(r)[:100]}")

# 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 models and the active one", {"sft", "sft-int8"} <= set(h_.get("models", [])) and h_.get("active") == "sft", str(h_)[:200])
        check("/health lists the edit models", {"edit", "edit-int8"} <= set(h_.get("models", [])), str(h_.get("models")))
    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)