Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
qwen-image clients: no request can wedge the engine
JustVugg9fd6d15e643a
diff --git a/c/image_engine.py b/c/image_engine.pyindex 6d83bb68..22f12aee 100644--- a/c/image_engine.py+++ b/c/image_engine.py@@ -44,11 +44,20 @@ DEFAULT_INFO = {"model": "qwen-image-2.1", "default_width": 768, "default_height# groups, so 16:9 is 1024x576, never 768x432.SIZE_PRESETS = ((512, 512), (768, 512), (512, 768), (1024, 576), (576, 1024), (1024, 1024))MAX_STEPS = 200+# One step is refused: the schedule's terminal stretch divides by zero there, and+# the reference pipeline gives NaN too.+MIN_STEPS = 2MAX_SEED = 2**32 - 1# A frame larger than the biggest legal image is a desynchronised stream, not# a picture: 2048 x 2048 x 4 is 16 MiB, so anything past 64 MiB is refused# before a single byte of it is allocated.MAX_FRAME_BYTES = 64 << 20+# The prompt, in UTF-8 bytes. The engine caps the tokens too (1024 with the+# template); this refuses early, before a multi-megabyte GEN line is written.+MAX_PROMPT_BYTES = 8192+# How long a new request waits for the final frame of one that was abandoned+# (its client vanished, a callback raised) before the engine is given up on.+ABANDONED_TIMEOUT = 600_FRAMES = ("READY", "PROGRESS", "PREVIEW", "IMAGE", "ERROR")@@ -146,6 +155,7 @@ class ImageEngine:self.events = queue.Queue()self.dead = None # why the engine is gone, once it isself._seq = 0+ self._abandoned = None # id of a request left without its final frametry:self.info = self._await_ready(load_timeout)except BaseException:@@ -280,9 +290,12 @@ class ImageEngine:polled between frames and on every idle tick; with `interruptible` thefirst Ctrl-C sends CANCEL and keeps waiting (the engine is still busyuntil it answers), the second one propagates."""+ if len(prompt.encode("utf-8")) > MAX_PROMPT_BYTES:+ raise ImageRequestError(f"`prompt` is longer than {MAX_PROMPT_BYTES} bytes.", "prompt")with self.lock:if self.dead:raise ImageEngineError(self.dead)+ self._finish_abandoned()self._seq += 1rid = f"r{self._seq}"self._send("GEN", {"id": rid, "prompt": prompt, "width": width, "height": height,@@ -295,61 +308,99 @@ class ImageEngine:cancel_sent = Trueself._send("CANCEL", {"id": rid})- while True:- try:+ finished = False+ try:+ while True:try:- kind, body, payload = self.events.get(timeout=0.2)- except queue.Empty:- if cancelled is not None and cancelled():- cancel()- if on_idle is not None:- on_idle()+ try:+ kind, body, payload = self.events.get(timeout=0.2)+ except queue.Empty:+ if cancelled is not None and cancelled():+ cancel()+ if on_idle is not None:+ on_idle()+ continue+ except KeyboardInterrupt:+ if not interruptible or cancel_sent:+ raise+ cancel()+ if on_interrupt is not None:+ on_interrupt()continue- except KeyboardInterrupt:- if not interruptible or cancel_sent:- raise- cancel()- if on_interrupt is not None:- on_interrupt()- continue- if kind == "_error":- self.dead = f"the image engine protocol broke: {body.get('message')}"- continue # the _eof that follows raises- if kind == "_eof":+ if kind == "_error":+ self.dead = f"the image engine protocol broke: {body.get('message')}"+ continue # the _eof that follows raises+ if kind == "_eof":+ try:+ code = self.process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ code = None+ self.dead = self.dead or f"the image engine exited ({describe_exit(code)})"+ raise ImageEngineError(self.dead)+ if body.get("id") not in (rid, None, ""):+ continue # a frame for an abandoned request+ if kind == "PROGRESS":+ if on_progress is not None:+ on_progress(body)+ elif kind == "PREVIEW":+ if on_preview is not None:+ on_preview(body, payload)+ elif kind == "IMAGE":+ finished = True # the engine is done with this request+ width_out, height_out = body.get("width"), body.get("height")+ channels = body.get("channels", 4)+ if (not isinstance(width_out, int) or not isinstance(height_out, int) or+ channels != 4 or len(payload) != width_out * height_out * 4):+ raise ImageEngineError(+ f"IMAGE frame does not describe its payload ({width_out}x{height_out}"+ f"x{channels}, {len(payload)} bytes)")+ return {"width": width_out, "height": height_out, "channels": 4,+ "seed": body.get("seed", seed), "steps": body.get("steps", steps),+ "timings": body.get("timings") or {}, "rgba": payload}+ elif kind == "ERROR":+ finished = True+ message = str(body.get("message") or "unknown engine error")+ if message == "cancelled":+ # A cancel is an outcome, not a failure, whoever asked+ # for it: shown and reported as such.+ raise ImageCancelled()+ raise ImageEngineError(message)+ if cancelled is not None and cancelled():+ cancel()+ finally:+ if not finished and not self.dead:+ # Left without the final frame (a callback raised, the caller was+ # interrupted): the engine is still drawing. Ask it to stop, and make+ # the next request drain this one's frames first, or they would be+ # taken for its own.try:- code = self.process.wait(timeout=5)- except subprocess.TimeoutExpired:- code = None- self.dead = self.dead or f"the image engine exited ({describe_exit(code)})"- raise ImageEngineError(self.dead)- if body.get("id") not in (rid, None, ""):- continue # a frame for an abandoned request- if kind == "PROGRESS":- if on_progress is not None:- on_progress(body)- elif kind == "PREVIEW":- if on_preview is not None:- on_preview(body, payload)- elif kind == "IMAGE":- width_out, height_out = body.get("width"), body.get("height")- channels = body.get("channels", 4)- if (not isinstance(width_out, int) or not isinstance(height_out, int) or- channels != 4 or len(payload) != width_out * height_out * 4):- raise ImageEngineError(- f"IMAGE frame does not describe its payload ({width_out}x{height_out}"- f"x{channels}, {len(payload)} bytes)")- return {"width": width_out, "height": height_out, "channels": 4,- "seed": body.get("seed", seed), "steps": body.get("steps", steps),- "timings": body.get("timings") or {}, "rgba": payload}- elif kind == "ERROR":- message = str(body.get("message") or "unknown engine error")- if message == "cancelled":- # A cancel is an outcome, not a failure, whoever asked- # for it: shown and reported as such.- raise ImageCancelled()- raise ImageEngineError(message)- if cancelled is not None and cancelled():- cancel()+ if not cancel_sent:+ self._send("CANCEL", {"id": rid})+ except ImageEngineError:+ pass+ self._abandoned = rid++ def _finish_abandoned(self):+ """Drain the frames of an abandoned request up to its final one."""+ rid, self._abandoned = self._abandoned, None+ if rid is None:+ return+ deadline = time.monotonic() + ABANDONED_TIMEOUT+ while True:+ left = deadline - time.monotonic()+ if left <= 0:+ self.dead = "the image engine did not finish an abandoned request"+ self._kill_quietly()+ raise ImageEngineError(self.dead)+ try:+ kind, body, _payload = self.events.get(timeout=min(left, 1.0))+ except queue.Empty:+ continue+ if kind in ("_error", "_eof"):+ self.events.put((kind, body, None)) # the request that follows sees it+ return+ if kind in ("IMAGE", "ERROR") and body.get("id") == rid:+ returndef close(self, timeout=10):"""stdin EOF is the engine's clean exit; escalate only if it ignores it."""@@ -430,8 +481,8 @@ def random_seed():def check_steps(steps):- if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= MAX_STEPS:- return f"steps must be an integer between 1 and {MAX_STEPS}"+ if isinstance(steps, bool) or not isinstance(steps, int) or not MIN_STEPS <= steps <= MAX_STEPS:+ return f"steps must be an integer between {MIN_STEPS} and {MAX_STEPS}"return None@@ -451,6 +502,8 @@ def image_request(body, info):prompt = body.get("prompt")if not isinstance(prompt, str) or not prompt.strip():raise ImageRequestError("`prompt` must be a non-empty string.", "prompt")+ if len(prompt.encode("utf-8", "surrogatepass")) > MAX_PROMPT_BYTES:+ raise ImageRequestError(f"`prompt` is longer than {MAX_PROMPT_BYTES} bytes.", "prompt")n = body.get("n", 1)if n is not None and (isinstance(n, bool) or n != 1):raise ImageRequestError("Only `n`: 1 is supported; the engine draws one image at a "diff --git a/c/openai_server.py b/c/openai_server.pyindex 703c44ff..9d595ac9 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -5038,7 +5038,13 @@ class APIHandler(BaseHTTPRequestHandler):for name, value in queue_headers.items():self.send_header(name, value)self.send_cors_headers()- self.end_headers()+ try:+ self.end_headers()+ except OSError:+ # The client left between admission and the first frame: count+ # it as gone, so the generation is cancelled like any hang-up+ # instead of this exception abandoning it mid-image.+ state["connected"] = Falsedef write(data):with lock:diff --git a/c/tests/test_qwen_image_cli.py b/c/tests/test_qwen_image_cli.pyindex 1c83b491..26908b0d 100644--- a/c/tests/test_qwen_image_cli.py+++ b/c/tests/test_qwen_image_cli.py@@ -272,7 +272,7 @@ class CommandsTest(unittest.TestCase):self.assertEqual(entry["id"], "qwen-image-2.1-colibri")self.assertEqual(entry["capabilities"], ["image_generation"])body = json.dumps({"model": entry["id"], "prompt": "x", "size": "256x256",- "steps": 1}).encode()+ "steps": 2}).encode()req = Request(f"http://127.0.0.1:{port}/v1/images/generations", data=body,headers={"Content-Type": "application/json"})with urlopen(req, timeout=30) as r:diff --git a/c/tests/test_qwen_image_client.py b/c/tests/test_qwen_image_client.pyindex 222b3a74..12957fb6 100644--- a/c/tests/test_qwen_image_client.py+++ b/c/tests/test_qwen_image_client.py@@ -214,11 +214,11 @@ class ImageEngineTest(unittest.TestCase):def test_engine_error_leaves_the_engine_usable(self):engine = self.engine()with self.assertRaisesRegex(ie.ImageEngineError, "stub failure"):- engine.generate("__stub_error__", 256, 256, 1, 1)+ engine.generate("__stub_error__", 256, 256, 2, 1)with self.assertRaisesRegex(ie.ImageEngineError, "multiple of 32"):- engine.generate("x", 250, 256, 1, 1) # the engine's own validation+ engine.generate("x", 250, 256, 2, 1) # the engine's own validationself.assertTrue(engine.alive)- self.assertEqual(engine.generate("x", 256, 256, 1, 1)["width"], 256)+ self.assertEqual(engine.generate("x", 256, 256, 2, 1)["width"], 256)def test_cancel_between_steps(self):engine = self.engine(delay=0.2)@@ -229,7 +229,7 @@ class ImageEngineTest(unittest.TestCase):cancelled=lambda: len(seen) >= 2)self.assertLess(time.time() - started, 4) # 30 steps would take 6 sself.assertTrue(engine.alive)- self.assertEqual(engine.generate("y", 256, 256, 1, 2)["seed"], 2)+ self.assertEqual(engine.generate("y", 256, 256, 2, 2)["seed"], 2)def test_a_crash_is_reported_and_the_engine_marked_dead(self):engine = self.engine()@@ -237,11 +237,11 @@ class ImageEngineTest(unittest.TestCase):engine.generate("__stub_crash__", 256, 256, 4, 1)self.assertFalse(engine.alive)with self.assertRaises(ie.ImageEngineError):- engine.generate("x", 256, 256, 1, 1)+ engine.generate("x", 256, 256, 2, 1)def test_stray_output_is_ignored(self):engine = self.engine()- result = engine.generate("__stub_garbage__", 256, 256, 1, 1)+ result = engine.generate("__stub_garbage__", 256, 256, 2, 1)self.assertEqual(result["width"], 256)self.assertTrue(any("stray" in line for line in self.logs))diff --git a/c/tests/test_qwen_image_gateway.py b/c/tests/test_qwen_image_gateway.pyindex 1836285c..e9d2b1db 100644--- a/c/tests/test_qwen_image_gateway.py+++ b/c/tests/test_qwen_image_gateway.py@@ -134,16 +134,16 @@ class ImagesEndpointTest(unittest.TestCase):def test_same_seed_same_image_other_seed_other_image(self):def pixels(seed):_s, _h, raw = self.gw.generate(prompt="a lighthouse", size="256x256", seed=seed,- steps=1)+ steps=2)return png_pixels(json.loads(raw)["data"][0]["b64_json"])[3]self.assertEqual(pixels(11), pixels(11))self.assertNotEqual(pixels(11), pixels(12))def test_width_and_height_fields_and_defaults(self):- status, _h, raw = self.gw.generate(prompt="x", width=256, height=512, steps=1)+ status, _h, raw = self.gw.generate(prompt="x", width=256, height=512, steps=2)self.assertEqual(status, 200, raw)self.assertEqual(json.loads(raw)["colibri"]["height"], 512)- status, _h, raw = self.gw.generate(prompt="x", steps=1)+ status, _h, raw = self.gw.generate(prompt="x", steps=2)meta = json.loads(raw)["colibri"]info = self.gw.engine.infoself.assertEqual((meta["width"], meta["height"]),@@ -215,7 +215,12 @@ class ImagesEndpointTest(unittest.TestCase):self.assertEqual((status, error["param"]), (400, "n"))def test_other_bad_parameters(self):- for key, value in (("steps", 0), ("steps", 10**6), ("seed", -1), ("seed", "x"),+ # A prompt past MAX_PROMPT_BYTES is refused before it reaches the engine: a+ # 72 KB one used to be written as one GEN line the engine never answered.+ status, _h, raw = self.gw.generate(prompt="x" * 8193, size="256x256")+ status, error = self.error(status, raw)+ self.assertEqual((status, error["param"]), (400, "prompt"))+ for key, value in (("steps", 0), ("steps", 1), ("steps", 10**6), ("seed", -1), ("seed", "x"),("response_format", "url"), ("output_format", "jpeg"),("stream", "yes"), ("partial_images", -1)):with self.subTest(key=key, value=value):@@ -260,7 +265,7 @@ class ImagesEndpointTest(unittest.TestCase):self.assertEqual(status, 403)status, headers, _raw = self.gw.request("/v1/images/generations",- {"model": MODEL_ID, "prompt": "x", "size": "256x256", "steps": 1},+ {"model": MODEL_ID, "prompt": "x", "size": "256x256", "steps": 2},headers={"Origin": "http://localhost:5173"})self.assertEqual(status, 200)self.assertEqual(headers.get("Access-Control-Allow-Origin"), "http://localhost:5173")@@ -280,12 +285,12 @@ class ImagesEndpointTest(unittest.TestCase):"stream": True})self.assertEqual(status, 500)# And the engine is still serving.- status, _h, _raw = self.gw.generate(prompt="fine", size="256x256", steps=1)+ status, _h, _raw = self.gw.generate(prompt="fine", size="256x256", steps=2)self.assertEqual(status, 200)def test_stray_engine_output_does_not_break_the_protocol(self):status, _h, raw = self.gw.generate(prompt="__stub_garbage__ a boat", size="256x256",- steps=1)+ steps=2)self.assertEqual(status, 200, raw)@@ -315,7 +320,7 @@ class ImagesFailureTest(unittest.TestCase):deadline = time.time() + 10while gw.server.scheduler.snapshot()["active"] == 0 and time.time() < deadline:time.sleep(0.02)- status, headers, raw = gw.generate(prompt="second", size="256x256", steps=1)+ status, headers, raw = gw.generate(prompt="second", size="256x256", steps=2)self.assertEqual(status, 503, raw)self.assertEqual(json.loads(raw)["error"]["code"], "queue_full")first.join(timeout=20)@@ -346,7 +351,7 @@ class ImagesFailureTest(unittest.TestCase):self.assertTrue(gw.engine.alive)# 20 steps at 0.3 s would be 6 s; the next request starts right away.started = time.time()- status, _h, _raw = gw.generate(prompt="next", size="256x256", steps=1)+ status, _h, _raw = gw.generate(prompt="next", size="256x256", steps=2)self.assertEqual(status, 200)self.assertLess(time.time() - started, 5)finally:diff --git a/c/tests/test_qwenimage_engine_serve.py b/c/tests/test_qwenimage_engine_serve.pyindex 93e39fb1..9ccaf652 100644--- a/c/tests/test_qwenimage_engine_serve.py+++ b/c/tests/test_qwenimage_engine_serve.py@@ -55,10 +55,47 @@ class RealEngineServe(unittest.TestCase):self.assertEqual(len(self.generate(1)["rgba"]), 256 * 256 * 4)def test_cancel_keeps_the_engine(self):+ # Through the client: a job long enough that the CANCEL, sent at the first+ # frame, lands before the last step (two steps of the tiny model can finish+ # before it arrives, which would be a race, not a result).with self.assertRaises(image_engine.ImageCancelled):- self.generate(2, cancelled=lambda: True)+ self.engine.generate("a fox", 512, 512, 100, 2, cancelled=lambda: True)self.assertEqual(len(self.generate(2)["rgba"]), 256 * 256 * 4)+ def test_cancel_pipelined_with_its_gen(self):+ # The protocol itself: a CANCEL written right behind its GEN is answered+ # "cancelled", whatever the speed of the machine.+ self.engine._send("GEN", {"id": "c1", "prompt": "x", "width": 256, "height": 256, "steps": 2})+ self.engine._send("CANCEL", {"id": "c1"})+ self.assertEqual(self._final("c1"), "cancelled")++ def test_abandoned_request_does_not_swallow_the_next(self):+ # A callback that raises leaves generate() without the final frame while+ # the engine is still drawing: the engine keeps the next GEN instead of+ # dropping it, and the client drains the abandoned frames first.+ def boom(frame):+ if frame.get("stage") == "denoise":+ raise ConnectionResetError("client went away")+ with self.assertRaises(ConnectionResetError):+ self.engine.generate("a fox", 512, 512, 6, 1, on_progress=boom)+ self.assertEqual(len(self.generate(5)["rgba"]), 256 * 256 * 4)++ def test_engine_refuses_what_it_cannot_do(self):+ with self.assertRaisesRegex(image_engine.ImageEngineError, "prompt too long"):+ self.engine.generate("7" * 4000, 256, 256, 2, 1) # 4 KB, one token per digit+ for steps in (1, 201):+ with self.assertRaises(image_engine.ImageEngineError):+ self.engine._send("GEN", {"id": "raw", "prompt": "x", "width": 256, "height": 256, "steps": steps})+ raise image_engine.ImageEngineError(self._final("raw"))+ self.assertEqual(len(self.generate(6)["rgba"]), 256 * 256 * 4)++ def _final(self, rid):+ while True:+ kind, body, _payload = self.engine.events.get(timeout=60)+ if body.get("id") == rid and kind in ("IMAGE", "ERROR"):+ self.assertEqual(kind, "ERROR", body)+ return body.get("message")+def test_progress_counts_completed_steps(self):seen = []self.generate(4, on_progress=lambda frame: seen.append((frame.get("stage"), frame.get("step"))))diff --git a/c/tools/qwenimage_stub.py b/c/tools/qwenimage_stub.pyindex 9aa66a7a..43842a73 100644--- a/c/tools/qwenimage_stub.py+++ b/c/tools/qwenimage_stub.py@@ -202,8 +202,8 @@ def check(request, info):return (f"{key} {value} is not a multiple of {info['multiple']} in "f"[{info['min_side']}, {info['max_side']}]")steps = request.get("steps", info["default_steps"])- if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= MAX_STEPS:- return f"steps must be an integer in [1, {MAX_STEPS}]"+ if isinstance(steps, bool) or not isinstance(steps, int) or not 2 <= steps <= MAX_STEPS:+ return f"steps must be an integer in [2, {MAX_STEPS}]"seed = request.get("seed", 0)if isinstance(seed, bool) or not isinstance(seed, int) or seed < 0:return "seed must be a non-negative integer"diff --git a/docs/qwen-image.md b/docs/qwen-image.mdindex 2d569972..2fbd5e7e 100644--- a/docs/qwen-image.md+++ b/docs/qwen-image.md@@ -123,7 +123,7 @@ only the path on stdout.image tokens 2x2, which is why 32 and not 16: 16:9 is 1024x576 or 512x288,never 768x432. The default is 768x512. The presets, the same ones the web UIoffers: 512x512, 768x512, 512x768, 1024x576, 576x1024, 1024x1024.-- **Steps**: default 8, from 1 to 200. Eight is a good draft for photographs;+- **Steps**: default 8, from 2 to 200. Eight is a good draft for photographs;16 gives visibly better anatomy and colour and is what text inside thepicture needs to come out legible (compared on the reference pipeline at8, 16 and 30 steps; 30 adds little over 16). Time grows with the steps.diff --git a/web/src/components/ImageTurn.tsx b/web/src/components/ImageTurn.tsxindex 5ac33959..96c9b416 100644--- a/web/src/components/ImageTurn.tsx+++ b/web/src/components/ImageTurn.tsx@@ -3,7 +3,7 @@ import { ChevronDown, Copy, Dices, Download, Footprints, Proportions, RefreshCw,import type { GeneratedImage, ImageProgress } from "@/lib/api"import {- MAX_STEPS, SIZE_PRESETS, clampSteps, duration, elapsedClock, presetOf, progressFraction,+ MAX_STEPS, MIN_STEPS, SIZE_PRESETS, clampSteps, duration, elapsedClock, presetOf, progressFraction,sizeKey, snapSide, validSide, type ImageSize,} from "@/lib/images"import { cn } from "@/lib/utils"@@ -179,7 +179,7 @@ export function ImageControls({ size, custom, steps, seed, seedValid, onSize, ononChange={(event) => {setStepsText(event.target.value)const value = Number(event.target.value)- if (event.target.value && Number.isInteger(value) && value >= 1 && value <= MAX_STEPS) onSteps(value)+ if (event.target.value && Number.isInteger(value) && value >= MIN_STEPS && value <= MAX_STEPS) onSteps(value)}}onBlur={(event) => { const value = clampSteps(Number(event.target.value || steps)); setStepsText(String(value)); onSteps(value) }}onKeyDown={(event) => {diff --git a/web/src/lib/images.test.ts b/web/src/lib/images.test.tsindex 1d70f0b2..62ffa4c3 100644--- a/web/src/lib/images.test.ts+++ b/web/src/lib/images.test.ts@@ -27,8 +27,8 @@ describe("image sizes", () => {})describe("steps and seed", () => {- it("keeps steps a whole number from 1 to 200 (the gateway's range)", () => {- expect([0, 8, 8.6, 500, Number.NaN].map(clampSteps)).toEqual([1, 8, 9, 200, 8])+ it("keeps steps a whole number from 2 to 200 (the gateway's range)", () => {+ expect([0, 8, 8.6, 500, Number.NaN].map(clampSteps)).toEqual([2, 8, 9, 200, 8])})it("reads an empty seed as random and refuses anything that is not a whole number", () => {diff --git a/web/src/lib/images.ts b/web/src/lib/images.tsindex bf40e70b..cbe5e394 100644--- a/web/src/lib/images.ts+++ b/web/src/lib/images.ts@@ -23,6 +23,8 @@ export const SIZE_PRESETS: ReadonlyArray<ImageSize & { ratio: string }> = [export const DEFAULT_SIZE: ImageSize = { width: 768, height: 512 }export const DEFAULT_STEPS = 8export const MAX_STEPS = 200+/* One step is refused by the engine (its schedule divides by zero there). */+export const MIN_STEPS = 2/* A seed the UI draws itself fits a signed 32-bit integer, whatever the enginekeeps it in. The gateway is still sent an explicit seed every time, so a newseed is really new even on a server that would fall back to a fixed one. */@@ -57,7 +59,7 @@ export function parseSize(text: string | null): ImageSize | null {export function clampSteps(value: number) {if (!Number.isFinite(value)) return DEFAULT_STEPS- return Math.min(MAX_STEPS, Math.max(1, Math.round(value)))+ return Math.min(MAX_STEPS, Math.max(MIN_STEPS, Math.round(value)))}/* An empty field means "draw a new seed"; anything else must be a whole