diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6381229e..f807ee7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -598,13 +598,28 @@ jobs: fail("no BUILTIN_IDS in recipes.py") builtins = re.findall(r'"([^"]+)"', m.group(1)) - lists = {"index.html select": sorted(ui), "cockpit switch enum": sorted(enum), - "install.sh MODEL_CHOICE": choices, "switch-model.sh guard": guard, - "recipes BUILTIN_IDS": sorted(builtins)} - ref = lists["install.sh MODEL_CHOICE"] - for name, got in lists.items(): + # Two kinds of target since the image lane. The TEXT targets are what + # install.sh can serve as its LLM (MODEL_CHOICE) and what the Models tab + # builds a recipe for. The SWITCH targets are those plus the lanes a flag + # installs, which today is one: `image`, installed by --with-image, switched + # to like any other, and not an LLM checkpoint (it has no recipe, no KV pool + # and no opencode default). Both sets are asserted, so a lane added to the + # switcher and forgotten in the cockpit's enum is still caught. + FLAG_LANES = ["image"] + ref = choices + switch_ref = sorted(ref + FLAG_LANES) + text_lists = {"install.sh MODEL_CHOICE": choices, "recipes BUILTIN_IDS": sorted(builtins)} + switch_lists = {"index.html select": sorted(ui), "cockpit switch enum": sorted(enum), + "switch-model.sh guard": guard} + for name, got in text_lists.items(): if got != ref: fail(f"{name} is {got}, install.sh says {ref}") + for name, got in switch_lists.items(): + if got != switch_ref: + fail(f"{name} is {got}, the switch targets are {switch_ref}") + for lane in FLAG_LANES: + if lane in ref: + fail(f"{lane} is installed by a flag, not MODEL_CHOICE; install.sh must not list it") if len(ui) != len(set(ui)): fail("duplicate option in the selector") # And the prose must not lag the list: "any of the six" outlived the @@ -618,7 +633,8 @@ jobs: or f"the {word} targets" in body or f"{word} switchable targets" in body): fail(f"{path} still says {word} targets, there are {n}") - print(f"{len(ref)} targets, five lists agree: {', '.join(ref)}") + print(f"{len(ref)} text targets and {len(FLAG_LANES)} flag lane, five lists agree: " + f"{', '.join(switch_ref)}") PYEOF - name: opencode limits, the one table and both callers diff --git a/README.md b/README.md index 50ca7df4..53813ce9 100644 --- a/README.md +++ b/README.md @@ -259,17 +259,13 @@ references, and the native RGBA this model is built for. It is opt-in because it curl -fsSL https://raw.githubusercontent.com/hasso5703/dgx-spark-qwen38/main/get.sh | bash -s -- --with-image ``` -Start and stop it from the cockpit's **Image** tab, which confirms what stopping the text -lane costs before it does it, or from a terminal: +Then it is a third lane, driven like the other two: pick **Qwen-Image 2.1** in the cockpit's +switcher, **Switch**, stop the serving lane, **Start Qwen-Image** (about 70 s). From a terminal, +`./switch-model.sh image` does the switch and prints the rest. -```bash -sudo systemctl start qwen38-image.service # images (this stops the text lane) -sudo systemctl start qwen38-sglang.service # back to text -``` - -31 GB of weights do not fit beside a serving LLM, so the unit carries `Conflicts=` and the two -lanes take turns. That is declared in systemd rather than left to a wrapper script, and the -image unit is not enabled at boot. +31 GB of weights do not fit beside a serving LLM, so the lanes take turns: the cockpit refuses +to start any engine while another is busy, for all three alike, and the unit's `Conflicts=` is +a second belt for a `systemctl start` typed at a terminal. **Measured on a Spark, not copied from the cookbook:** 1024x1024 at 40 steps in **38.2 s** (34.8 GB peak), 512x512 in 9.0 s, an edit with one reference in 44.6 s, ten references in 69.6 s, diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index 10996a67..cb0a3e1e 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -62,7 +62,8 @@ DRY_RUN = os.environ.get("COCKPIT_DRY_RUN", "0") == "1" # Fields from get_server_info that must never reach a browser. MASKED_FIELDS = {"api_key", "admin_api_key"} -UNITS = ("qwen38-sglang.service", "qwen38-flash.service", "qwen38-keepalive.service") +UNITS = ("qwen38-sglang.service", "qwen38-flash.service", "qwen38-image.service", + "qwen38-keepalive.service") JOURNAL_UNITS = UNITS + (AGENT_UNIT, "qwen38-image.service") # what the Logs tab may read CONTAINERS = ("qwen38-sglang", "qwen38-flash") @@ -905,6 +906,12 @@ UNIT_TARGET_CACHE: dict = {} def unit_target(unit: str) -> dict: """{model, target} the unit is configured for, from its own file. Cached on mtime.""" + if unit == "qwen38-image.service": + # one checkpoint, one target: the model is read from the unit so a lane + # installed with IMAGE_MODEL= reports what it really serves + model = _image_unit_flag("--model-path", "Qwen/Qwen-Image-2.1") \ + if IMAGE_UNIT_PATH.exists() else None + return {"model": model, "target": "image" if model else None} path = UNIT_PATHS.get(unit) if not path: return {"model": None, "target": None} @@ -958,12 +965,28 @@ def collect_lifecycle(): if unit not in lc.ENGINE_UNITS: states[unit] = "ready" if active == "active" else "stopped" continue - cont = UNIT2CONT[unit] - running = bool(run(["docker", "ps", "-q", "-f", - f"name=^{cont}$"]).strip()) + is_image = unit == lc.IMAGE_UNIT + if is_image and not IMAGE_UNIT_PATH.exists(): + continue # not installed: no card, no pill, no gate boot = {"stage": None, "fired_up": False, "done": []} rebuild = False - if running and not healthy: + if is_image: + # No container, no /get_load, no KV pool: the unit's own state, its own + # /health, and its journal for the boot stages. None of the LLM belts + # below (pool guard, wedge canary, autoheal) apply to it. + running = active in ("active", "activating") + healthy_u = running and image_healthy() + if running and not healthy_u: + boot = lc.parse_image_boot_log(_image_journal()) + st = lc.derive_state(unit_active=active, unit_sub=d.get("SubState", "?"), + container_running=running, healthy=healthy_u, boot=boot) + if st["state"] == "degraded" and prev.get(unit) not in ("ready", "degraded"): + st["state"] = "warming-up" + else: + cont = UNIT2CONT[unit] + running = bool(run(["docker", "ps", "-q", "-f", + f"name=^{cont}$"]).strip()) + if not is_image and running and not healthy: # A mature server's tail is pure decode noise: only read logs # while health is down (boot or trouble), where markers live. tail = run(["docker", "logs", "--tail", "300", cont], @@ -972,24 +995,27 @@ def collect_lifecycle(): # Hysteresis: a 2 s health probe times out under a heavy prefill. # Leaving ready needs 3 consecutive misses AND no fresh progress line; # a single 200 restores it at once. - if healthy: + if is_image: + pass # its state was derived above, from its own facts + elif healthy: UNHEALTHY_TICKS[unit] = 0 else: UNHEALTHY_TICKS[unit] = UNHEALTHY_TICKS.get(unit, 0) + 1 - progressing = LAST_PROGRESS["ts"] and time.time() - LAST_PROGRESS["ts"] < 30 - sticky_ready = (prev.get(unit) in ("ready", "wedged") and running and not healthy - and (UNHEALTHY_TICKS[unit] < 3 or progressing)) - st = lc.derive_state(unit_active=active, unit_sub=d.get("SubState", "?"), - container_running=running, - healthy=(healthy or sticky_ready) and running, boot=boot, - rebuild=False) - # degraded means "WAS serving, lost health", not "health probe has - # not caught up yet": right after fired-up, stay warming-up unless - # we had already reached ready in this activation. - if st["state"] == "degraded" and prev.get(unit) not in ("ready", - "degraded"): - st["state"] = "warming-up" - if st["state"] == "ready": + if not is_image: + progressing = LAST_PROGRESS["ts"] and time.time() - LAST_PROGRESS["ts"] < 30 + sticky_ready = (prev.get(unit) in ("ready", "wedged") and running and not healthy + and (UNHEALTHY_TICKS[unit] < 3 or progressing)) + st = lc.derive_state(unit_active=active, unit_sub=d.get("SubState", "?"), + container_running=running, + healthy=(healthy or sticky_ready) and running, boot=boot, + rebuild=False) + # degraded means "WAS serving, lost health", not "health probe has + # not caught up yet": right after fired-up, stay warming-up unless + # we had already reached ready in this activation. + if st["state"] == "degraded" and prev.get(unit) not in ("ready", + "degraded"): + st["state"] = "warming-up" + if st["state"] == "ready" and not is_image: with STATE_LOCK: load = ((STATE.get("engine_fast") or {}).get("data", {}) .get("load") or [{}])[0] @@ -1071,7 +1097,7 @@ def collect_lifecycle(): audit({"kind": "autoheal", "unit": unit, "code": code, "out": out}) else: WEDGED_SINCE.pop(unit, None) - if st["state"] in lc.TRANSITIONAL and running: + if st["state"] in lc.TRANSITIONAL and running and not is_image: jl = run(["journalctl", "-u", unit, "-n", "40", "--no-pager", "-o", "cat"], timeout=6).splitlines() rebuild = lc.journal_flags(jl)["rebuild"] @@ -1112,6 +1138,11 @@ def collect_lifecycle(): engines[unit] = {"state": st["state"], "rebuild": st.get("rebuild", False), **unit_target(unit), "stage_done": boot.get("done", []), + # which stage list this engine walks, and what it is loading + # now: the UI draws each from here rather than assuming + "stages": list(lc.IMAGE_STAGES if is_image else lc.STAGES), + "detail": boot.get("detail", ""), + "kind": "image" if is_image else "text", "elapsed": round(elapsed, 1) if elapsed else None, "state_elapsed": round(state_elapsed, 1) if state_elapsed is not None else None, "eta": eta, "overdue": overdue, @@ -1126,6 +1157,13 @@ def collect_lifecycle(): if st["state"] == "ready" and elapsed and witnessed \ and was in lc.TRANSITIONAL: history = lc.record_boot(history, unit, elapsed, rebuild) + if is_image: + # It has no KV pool, and ENGINE_BASE is the text lane's port: reading + # a pool here would record the wrong engine's, or nothing. + save_history(history) + with LIFE_LOCK: + LIFE["witnessed"][unit] = False + continue # The KV pool this boot won, kept per target: it decides whether the # declared opencode limits can be served. Read from the engine now, not # from the engine_info collector: at this instant that cache holds either @@ -1246,7 +1284,7 @@ ACTIONS = { "switch": { "danger": "medium", "params": {"target": ["stock", "uncensored", "fp8", "uncensored-fp8", - "flash", "flash-nvda", "flash-uncensored"]}, + "flash", "flash-nvda", "flash-uncensored", "image"]}, "argv": lambda p: ["bash", str(REPO_DIR / "switch-model.sh"), p["target"]], "timeout": 1800, }, @@ -1618,6 +1656,17 @@ def image_progress(serving: bool) -> dict: return {"kind": "stage", "stage": stage or "working", "label": stage or "working"} +def image_healthy() -> bool: + """The image lane's own /health, on its own port. A 503 is its answer while it + loads, a connection refused its answer while it starts; only a 200 is ready.""" + try: + urllib.request.urlopen(urllib.request.Request(image_base() + "/health"), + timeout=3).read() + return True + except Exception: # noqa: BLE001 (any non-200 is "not yet") + return False + + def image_status() -> dict: """Installed, running, answering. Three different things, and the tab says which.""" out = {"installed": IMAGE_UNIT_PATH.exists(), "port": image_port(), @@ -1756,7 +1805,8 @@ def image_call(payload: dict, editing: bool) -> tuple[int, dict]: return e.code, {"refused": detail, "seconds": round(time.time() - t0, 2)} except Exception as e: # noqa: BLE001 (isolated route) return 502, {"error": f"the image lane did not answer ({type(e).__name__}). " - f"Start it: sudo systemctl start {IMAGE_UNIT}", + f"Switch to Qwen-Image 2.1 in the action bar and start it " + f"(or ./switch-model.sh image)", "seconds": round(time.time() - t0, 2)} finally: IMAGE_LOCK.release() diff --git a/dashboard/lifecycle.py b/dashboard/lifecycle.py index e1a38251..8d440fd4 100644 --- a/dashboard/lifecycle.py +++ b/dashboard/lifecycle.py @@ -33,6 +33,51 @@ REBUILD_RE = re.compile(r"rebuilding the PLE table") STAGES = ("init", "loading-weights", "loading-draft", "allocating-kv", "capturing-graphs", "warming-up") +# ── The image lane speaks another dialect ─────────────────────────────────── +# SGLang Diffusion has no draft, no KV pool and no CUDA graphs, and it writes its +# own timestamps in two formats (the engine "[09-22 17:20:37]", uvicorn "[2026-09-22 +# 17:21:34]"), so its lines are matched on what they say, never on when. Measured on +# the reference box, one boot from process start to fired up, 64 s: +# 0 s Starting server 7 s Loading pipeline modules 18 s Loaded text_encoder +# 51 s Loaded transformer 57 s Loaded vae, Pipeline instantiated 64 s fired up +# The transformer is half a minute with nothing printed in between, which is why the +# component being loaded travels as `detail`: a stage called "weights" for 33 s says +# less than "the 13.3 GB DiT". +IMAGE_STAGES = ("init", "loading-weights", "warming-up") +IMAGE_MARKERS = [ + # (substring, stage it opens, what is being loaded while that line is the latest) + ("Starting server...", "init", "starting the server"), + ("Loading pipeline modules...", "loading-weights", "reading the checkpoint layout"), + ("Loading text_encoder from", "loading-weights", "the 16.5 GB Qwen3-VL encoder"), + ("Loading transformer from", "loading-weights", "the 13.3 GB DiT"), + ("Loading vae from", "loading-weights", "the VAE"), + ("Pipeline instantiated", "loading-weights", "building the pipeline"), + ("Starting FastAPI server", "warming-up", "one throwaway image"), + ("fired up and ready to roll", "warming-up", "ready"), +] + + +def parse_image_boot_log(lines: list[str]) -> dict: + """The image lane's journal, reduced to the same shape parse_boot_log returns. + + Only the latest boot counts: journald keeps every previous life of the unit, + and a "fired up" from yesterday must not make today's boot read as ready.""" + start = 0 + for i, ln in enumerate(lines): + if "Starting server..." in ln: + start = i + stage, detail, fired = None, "", False + for ln in lines[start:]: + for needle, st, what in IMAGE_MARKERS: + if needle in ln: + stage, detail = st, what + if needle == "fired up and ready to roll": + fired = True + done = list(IMAGE_STAGES[:IMAGE_STAGES.index(stage)]) if stage in IMAGE_STAGES else [] + if fired: + done = list(IMAGE_STAGES) + return {"stage": stage, "done": done, "fired_up": fired, "detail": detail} + def parse_boot_log(lines: list[str]) -> dict: """Reduce a container log tail to {stage, done[], fired_up, weight_loads}. @@ -144,7 +189,11 @@ BUSY_STATES = {"starting", "loading-weights", "loading-draft", "allocating-kv", "capturing-graphs", "warming-up", "ready", "degraded", "stopping", "wedged"} TRANSITIONAL = BUSY_STATES - {"ready", "degraded"} -ENGINE_UNITS = ("qwen38-sglang.service", "qwen38-flash.service") +# Every unit that holds the GPU pool while it runs. The image lane is one of them: +# 31 GB of weights, and two engines at once on 121.6 GB of unified memory is the +# livelock this whole module exists to prevent. +ENGINE_UNITS = ("qwen38-sglang.service", "qwen38-flash.service", "qwen38-image.service") +IMAGE_UNIT = "qwen38-image.service" def blocked_reasons(action: str, params: dict, states: dict) -> list[str]: @@ -159,11 +208,13 @@ def blocked_reasons(action: str, params: dict, states: dict) -> list[str]: if action == "unit": unit, verb = params.get("unit", ""), params.get("verb", "") if unit in ENGINE_UNITS and verb in ("start", "restart"): - other = [u for u in ENGINE_UNITS if u != unit][0] - if st(other) in BUSY_STATES: - reasons.append( - f"{other} is {st(other)}: two engines never run at once " - f"on unified memory (stop it first)") + # Every other engine, not "the other one": with three lanes, picking [0] + # checked one of two neighbours and let the third through. + for other in ENGINE_UNITS: + if other != unit and st(other) in BUSY_STATES: + reasons.append( + f"{other} is {st(other)}: two engines never run at once " + f"on unified memory (stop it first)") elif action in ("switch", "update_stack"): for u in ENGINE_UNITS: if st(u) in TRANSITIONAL: @@ -181,6 +232,10 @@ def warn_reasons(action: str, params: dict, states: dict, if unit == "qwen38-flash.service" and state in TRANSITIONAL: warns.append("stopping the flash lane mid-boot marks the PLE " "table dirty: the NEXT boot rebuilds it (~12 min)") + elif unit == IMAGE_UNIT and state == "ready": + # the proxy on :30001 is a text door; nothing reaches this lane through it + warns.append("an image being generated right now is lost, and the Image " + "tab has nothing to talk to until this lane is back (about 70 s)") elif state == "ready": warns.append("clients on :30001 will get errors until an engine " "is back") diff --git a/dashboard/static/app.js b/dashboard/static/app.js index 79c346e9..3ed312a2 100644 --- a/dashboard/static/app.js +++ b/dashboard/static/app.js @@ -41,8 +41,28 @@ const TRANSITIONAL = new Set(['starting', 'loading-weights', 'loading-draft', 'a const STAGE_LABEL = {'init': 'init', 'loading-weights': 'weights', 'loading-draft': 'draft', 'allocating-kv': 'KV', 'capturing-graphs': 'graphs', 'warming-up': 'warmup'}; const ALL_STAGES = Object.keys(STAGE_LABEL); const LANE_NAME = {'qwen38-sglang.service': '27B', 'qwen38-flash.service': 'flash 176B', - 'qwen38-image.service': 'the image lane'}; + 'qwen38-image.service': 'Qwen-Image'}; +// How long each lane takes to answer after a start, before the box has seen one of its +// boots. Measured on the reference box: the text lanes load, compile and capture graphs +// for about nine minutes; the image lane loads 31 GB and warms up in about 70 seconds. +// Once a lane has booted in front of the cockpit, its own median replaces these. +const READY_DEFAULT = {'qwen38-sglang.service': 540, 'qwen38-flash.service': 780, + 'qwen38-image.service': 70}; +function readyIn(unit){ + const e = ((F.life || {}).engines || {})[unit] || {}; + const b = (e.boots || []).slice().sort((a, c) => a - c); + const s = b.length ? b[Math.floor(b.length / 2)] : (READY_DEFAULT[unit] || 540); + return 'about ' + fmtDur(s); +} const IMAGE_UNIT = 'qwen38-image.service'; +// The image lane's live facts. Declared up here, not beside the Image tab's code: the +// lane pill and the action bar read them too, and a const read before its line has run +// is a ReferenceError that takes the whole page down with it. +const IMG_STATE = {port: 30020, host: '127.0.0.1', available: false, busy: false}; +let imgInflight = null; // when this page's own request started, or null +let IMG_RUN = null; // the shape of that request: {w, h, steps, n, editing} +let IMG_RUNPROG = null; // the run bar, held by reference (it moves into the frame) +function imgRunProg(){ return IMG_RUNPROG || (IMG_RUNPROG = $('imgrunprog')); } const AGENT_UNIT = 'opencode-web.service'; // Both lanes have several targets sharing one unit, so the lane name alone ("27B", // "flash") does not say which checkpoint is loaded. Every control that names a lane @@ -50,7 +70,8 @@ const AGENT_UNIT = 'opencode-web.service'; // purpose: it is that lane's default and the lane name already reads right. const TARGET_SHORT = {stock: 'stock', uncensored: 'uncensored', fp8: 'FP8', 'uncensored-fp8': 'FP8 uncensored', flash: '', - 'flash-uncensored': 'uncensored', 'flash-nvda': 'NVIDIA export'}; + 'flash-uncensored': 'uncensored', 'flash-nvda': 'NVIDIA export', + image: '2.1'}; function laneLabel(unit){ if (unit === AGENT_UNIT) return 'the opencode web server'; const base = LANE_NAME[unit] || unit.replace('.service', ''); @@ -62,7 +83,7 @@ function laneLabel(unit){ const t = target && TARGET_SHORT[target] ? ' ' + TARGET_SHORT[target] : ''; return base + t; } -const laneCls = name => name.includes('flash') ? 'flash' : 'lane27'; +const laneCls = name => name.includes('flash') ? 'flash' : name === IMAGE_UNIT ? 'laneimg' : 'lane27'; const stateChipCls = st => (STATE_CHIP[st] ?? 'warn') + (st === 'stopping' || TRANSITIONAL.has(st) ? ' live' : ''); // ── tabs and the collapsible rail ───────────────────────────────────────────── @@ -274,6 +295,16 @@ function servingReady(){ const s = servingEngine(); return !!(s && ['ready', 'degraded', 'wedged'].includes(s[1].state)); } +// A TEXT engine is up. Not the same question once the image lane exists: the pool, +// the context window, Flush cache, Abort all and Smoke all talk to the text engine on +// :30000, and with the image lane serving that port is closed. Asking servingReady() +// there enabled three buttons that would hit a dead port and left the previous LLM's +// facts on screen under an image engine. +function textReady(){ + const s = servingEngine(); + return servingReady() && !!s && s[0] !== IMAGE_UNIT; +} +const imageServing = () => { const s = servingEngine(); return !!s && s[0] === IMAGE_UNIT; }; function rPool(){ const l = F.load || {}; if (!F.pool){ setText('poollab', 'waiting for the engine'); $('poolfill').style.width = '0%'; setText('poolnote', 'the pool size arrives with the engine (max_total_num_tokens at boot)'); return; } @@ -366,6 +397,7 @@ function rKernel(d){ } function rUnits(d){ F.units = d.units || {}; + const sel = $('switchsel'); if (sel) markInstalled(sel); const box = $('unitlist'); clear(box); Object.entries(F.units).filter(([n]) => n.includes('keepalive')).forEach(([name, u]) => { const row = el('div', 'eng'); const top = el('div', 'row'); @@ -553,7 +585,12 @@ function rLanePill(){ setText('lanename', laneLabel(name)); const l = F.load || {}; let sub = ''; - if (e.state === 'ready' || e.state === 'degraded'){ + if ((e.state === 'ready' || e.state === 'degraded') && name === IMAGE_UNIT){ + // no pool and no running count: the image lane serves one request at a time, and + // what is worth a glance is whether it is working on one right now + const busy = IMG_STATE.busy || imgInflight; + sub = (busy ? 'generating' : 'idle, one image at a time') + (e.elapsed ? ` · up ${fmtDur(e.elapsed)}` : ''); + } else if (e.state === 'ready' || e.state === 'degraded'){ sub = (F.pool ? `pool ${Math.round(100 * (l.num_tokens || 0) / F.pool)} %` : '') + ((l.num_reqs || 0) ? ` · ${l.num_reqs} running` : '') + (e.elapsed ? ` · up ${fmtDur(e.elapsed)}` : ''); } else if (TRANSITIONAL.has(e.state)){ const eta = e.eta && e.elapsed ? Math.max(0, e.eta - e.elapsed) : null; @@ -563,18 +600,30 @@ function rLanePill(){ } setText('lanesub', sub); } -function bootBlock(e){ - const doneN = (e.stage_done || []).length, stage = ALL_STAGES[doneN] || 'init'; - const pct = e.eta && e.elapsed ? Math.min(97, 100 * e.elapsed / e.eta) : Math.min(95, 8 + doneN * (84 / ALL_STAGES.length)); - const eta = e.eta && e.elapsed ? Math.max(0, e.eta - e.elapsed) : null; +function bootBlock(e, unit){ + // Each engine names the stages it walks: the image lane has no draft, no KV pool + // and no CUDA graphs, and drawing those as pending would say it is stuck on them. + const stagesOf = e.stages && e.stages.length ? e.stages : ALL_STAGES; + const doneN = (e.stage_done || []).length, stage = stagesOf[doneN] || 'init'; + // Before the cockpit has watched a boot of this lane, the duration measured on the + // reference box stands in: "learning the duration" is true and tells nobody anything. + const learned = !!e.eta; + const etaTotal = e.eta || (unit ? READY_DEFAULT[unit] : null); + const pct = etaTotal && e.elapsed ? Math.min(97, 100 * e.elapsed / etaTotal) : Math.min(95, 8 + doneN * (84 / stagesOf.length)); + const eta = etaTotal && e.elapsed ? Math.max(0, etaTotal - e.elapsed) : null; const boot = el('div', 'boot'); const bar = el('div', 'bbar'); const fill = el('div', 'bfill'); fill.style.width = pct.toFixed(1) + '%'; bar.append(fill); boot.append(bar); const stages = el('div', 'stages'); - ALL_STAGES.forEach((st, i) => stages.append(el('span', 'stage ' + (i < doneN ? 'done' : st === stage ? 'now' : ''), STAGE_LABEL[st]))); + stagesOf.forEach((st, i) => stages.append(el('span', 'stage ' + (i < doneN ? 'done' : st === stage ? 'now' : ''), STAGE_LABEL[st]))); boot.append(stages); const lab = el('div', 'blab'); - lab.append(el('span', null, `${STATE_LABEL[e.state] || stage} · ${fmtDur(e.elapsed)} elapsed`)); - lab.append(el('span', null, eta != null ? `about ${fmtDur(eta)} left (median of ${(e.boots || []).length} boots)` : 'first boot: learning the duration')); + // what it is loading right now, when the engine says: "loading weights" for half a + // minute says less than "the 13.3 GB DiT" + const doing = e.detail && e.detail !== 'ready' ? ` (${e.detail})` : ''; + lab.append(el('span', null, `${STATE_LABEL[e.state] || stage}${doing} · ${fmtDur(e.elapsed)} elapsed`)); + lab.append(el('span', null, eta == null ? 'first boot: learning the duration' + : learned ? `about ${fmtDur(eta)} left (median of ${(e.boots || []).length} boots)` + : `about ${fmtDur(eta)} left (measured on the reference box; this box learns its own)`)); boot.append(lab); if (e.rebuild) boot.append(el('div', 'why warn', 'the flash PLE table is being rebuilt: this boot takes about 12 minutes instead of 9')); if (e.overdue) boot.append(el('div', 'why warn', 'this boot is taking more than twice the usual time: check the Logs tab')); @@ -605,7 +654,9 @@ function engineCard(name){ const on = e.state !== 'stopped' && e.state !== 'failed'; const warns = []; if (on && TRANSITIONAL.has(e.state) && name.includes('flash')) warns.push('stopping the flash lane mid-boot marks the PLE table dirty: the NEXT boot rebuilds it (about 12 min)'); - if (on && e.state === 'ready') warns.push('clients on :30001 get "engine unavailable" until an engine is back (about 9 min after a start)'); + if (on && e.state === 'ready') warns.push(name === IMAGE_UNIT + ? 'an image being generated right now is lost, and the Image tab has nothing to talk to until this lane is back (' + readyIn(name) + ' after a start)' + : 'clients on :30001 get "engine unavailable" until an engine is back (' + readyIn(name) + ' after a start)'); askAction('unit', {verb: on ? 'stop' : 'start', unit: name}, ['sudo', '-n', '/usr/bin/systemctl', on ? 'stop' : 'start', name], warns); }); CARDS.set(name, c); $('enginelist').append(root); @@ -613,6 +664,7 @@ function engineCard(name){ } function rLifecycle(d){ F.life = d; syncSelector(); rLanePill(); renderLaneAction(); + if (typeof imgRenderLane === 'function') imgRenderLane(); const g = d.pool_guard; if (g){ F.poolGuard = g; @@ -652,23 +704,24 @@ function rLifecycle(d){ c.hist.textContent = hist; // the animated block is rebuilt only when its shape changes, its numbers every tick const sig = TRANSITIONAL.has(e.state) ? 'boot' : e.state === 'stopping' ? 'stop' : 'none'; - if (sig !== c.sig || sig !== 'none'){ clear(c.extra); if (sig === 'boot') c.extra.append(bootBlock(e)); if (sig === 'stop') c.extra.append(stoppingBlock(e)); c.sig = sig; } + if (sig !== c.sig || sig !== 'none'){ clear(c.extra); if (sig === 'boot') c.extra.append(bootBlock(e, name)); if (sig === 'stop') c.extra.append(stoppingBlock(e)); c.sig = sig; } }); // overview lane card: the serving engine's card, mirrored const ov = $('ovlane'); clear(ov); const s = servingEngine(); // engine facts belong to a lane that is actually up: while it boots, stops or is gone, // say so rather than showing the previous lane's model, pool and percentages - if (!servingReady()) rEngineInfoDown(s ? 'engine ' + (STATE_LABEL[s[1].state] || s[1].state) : 'no engine running'); + if (!textReady()) rEngineInfoDown(imageServing() ? 'the image lane is serving, so there is no text engine: its facts are in the Image tab' + : s ? 'engine ' + (STATE_LABEL[s[1].state] || s[1].state) : 'no engine running'); if (!s){ - const p = el('p', 'empty', 'No engine is serving. Start the enabled lane from the action bar (about 9 minutes to ready), or switch the target first.'); + const p = el('p', 'empty', `No engine is serving. Start ${laneLabel(enabledUnit())} from the action bar (${readyIn(enabledUnit())} to ready), or switch the target first.`); ov.append(p); } else { const [name, e] = s; const row = el('div', 'row'); row.append(el('span', 'chip ' + stateChipCls(e.state), STATE_LABEL[e.state] || e.state), el('span', 'name', laneLabel(name)), el('span', 'chip ' + laneCls(name), name.replace('.service', '')), el('span', 'since', e.state === 'ready' && e.elapsed ? 'up ' + fmtDur(e.elapsed) : '')); ov.append(row); - if (TRANSITIONAL.has(e.state)) ov.append(bootBlock(e)); + if (TRANSITIONAL.has(e.state)) ov.append(bootBlock(e, name)); else if (e.state === 'stopping') ov.append(stoppingBlock(e)); else if (e.state === 'wedged') ov.append(el('div', 'why warn', 'the engine answers health checks but generates nothing: the autoheal belt restarts it after its grace period (Engines tab, Logs tab for the forensics)')); else if (e.state === 'degraded') ov.append(el('div', 'why warn', 'the engine was serving and stopped answering: probes retry every 2 s')); @@ -690,10 +743,30 @@ function rLifecycle(d){ badge('engines', bad ? (STATE_BADGE[bad] || 'check') : trans ? 'booting' : '', bad ? 'err' : trans ? 'warn' : ''); applyBusy(); } +// Which unit serves a target, and how that lane is installed when it is not. +const TARGET_UNIT = t => t === 'image' ? IMAGE_UNIT : t.startsWith('flash') ? 'qwen38-flash.service' : 'qwen38-sglang.service'; +const LANE_INSTALL = {'qwen38-sglang.service': './install.sh', 'qwen38-flash.service': 'MODEL_CHOICE=flash ./install.sh', + 'qwen38-image.service': './install.sh --with-image'}; +// An option whose lane has no unit file on this box is shown as such and cannot be +// picked. Picking it used to be allowed, and the switch then failed a second later +// with "not installed": the image lane is opt-in, so that was the default on most boxes. +function markInstalled(sel){ + const units = F.units || {}; + if (!Object.keys(units).length) return; // no facts yet: leave it as it is + sel.querySelectorAll('option').forEach(o => { + if (!o.dataset.label) o.dataset.label = o.textContent; + const u = TARGET_UNIT(o.value); + const missing = (units[u] || {}).enabled === ''; + o.disabled = missing; + o.textContent = o.dataset.label + (missing ? ' (not installed)' : ''); + o.title = missing ? `this lane is not installed on this box: ${LANE_INSTALL[u]}` : ''; + }); +} function syncSelector(){ // show the target of the lane that is serving, booting, or enabled: never just the // first option, which read as "stock" through nine minutes of an FP8 boot const sel = $('switchsel'); + if (sel) markInstalled(sel); if (!sel || sel.dataset.touched) return; const eng = (F.life || {}).engines || {}; const s = servingEngine(); @@ -709,7 +782,7 @@ const JOBLINES = {id: null, lines: []}; // as the parameter dict that happens to be its wire format. const ACTION_PHRASE = { unit: p => `${p.verb || 'act on'} ${String(p.unit || '').replace('.service', '')}`, - switch: p => `switch to ${TARGET_SHORT[p.target] || p.target || 'flash 176B'}`, + switch: p => `switch to ${p.target === 'image' ? 'Qwen-Image 2.1' : (TARGET_SHORT[p.target] || p.target || 'flash 176B')}`, flush_cache: () => 'flush the radix cache', abort_all: () => 'abort every generation in flight', smoke: () => 'smoke probe through the proxy', @@ -795,8 +868,10 @@ function applyBusy(){ const busy = !!(F.job && F.job.current); const why = offline ? 'the cockpit is unreachable: actions are disabled until the connection is back' : busy ? `another action is running (${F.job.current.action}); wait for it to finish` : ''; - const engineUp = servingReady(); - const noEngineWhy = engineUp ? '' : 'no engine is serving: start one first (it answers in about 9 minutes)'; + const engineUp = textReady(); + const noEngineWhy = engineUp ? '' : imageServing() + ? 'the image lane is serving: this acts on the text engine, which is not running' + : `no engine is serving: start one first (it answers in ${readyIn(enabledUnit())})`; document.querySelectorAll('[data-act]').forEach(b => { if (b.id === 'lanebtn') return; if (b.dataset.act === 'unit'){ @@ -829,7 +904,7 @@ function renderLaneAction(why){ const name = enabledUnit(); const bl = ((F.life || {}).blocked || {})[`unit:start:${name}`]; b.textContent = `Start ${LANE_NAME[name] || name.replace('.service', '')}`; b.className = 'btn mini low'; b.disabled = !!(why || bl || !F.life); - b.title = why || (bl ? bl[0] : `Start ${laneLabel(name)} (systemctl start ${name}, about 9 minutes to ready)`); + b.title = why || (bl ? bl[0] : `Start ${laneLabel(name)} (systemctl start ${name}, ${readyIn(name)} to ready)`); b.onclick = () => askAction('unit', {verb: 'start', unit: name}, ['sudo', '-n', '/usr/bin/systemctl', 'start', name], []); } } @@ -1058,7 +1133,7 @@ function apply(state){ if (!errors[name]) renderErr[name] = e.message; // a bug here, not a dead source // a timeout on a busy engine is not a lane change: keep the last known facts and // let the panel age visibly. Only lifecycle decides that a lane is gone. - if (name === 'engine_info' && !servingReady()) rEngineInfoDown(); + if (name === 'engine_info' && !textReady()) rEngineInfoDown(); warnOnce(name, e.message); } } @@ -1105,8 +1180,13 @@ function banners(state, errors){ if ((upd.stale_code || []).length) add('warn', 'This cockpit is running older code than the files on disk.', `${upd.stale_code.join(', ')} changed under it, so its controls and its checks no longer agree. Restart it: sudo systemctl restart qwen38-dashboard.service`); const ocf = F.ocfit; + // The limit is the usable share of the pool (the proxy keeps 8% back), which is a + // number printed nowhere else on the page: said alone, "823,193" beside a panel reading + // "KV pool 894,775" reads as the cockpit contradicting itself. So both are named. if (ocf && !ocf.ok) add('warn', 'opencode asks for more than this engine can hold.', - `${ocf.why} (${fmtN(ocf.asked)} asked against ${fmtN(ocf.limit)} on ${ocf.served}): the session would break mid-conversation when the proxy refuses the prompt. Setup tab, "Fit the limits to this engine".`); + `${ocf.why}: opencode declares ${fmtN(ocf.asked)} tokens, and ${ocf.served} can serve ${fmtN(ocf.limit)}` + + (ocf.pool && ocf.limit === ocf.usable ? ` (the ${fmtN(ocf.pool)}-token pool this boot got, less the 8% the proxy keeps back)` : '') + + `. The session would break mid-conversation when the proxy refuses the prompt. Setup tab, "Fit the limits to this engine".`); ((F.life || {}).orphans || []).forEach(o => add('warn', `${LANE_NAME[o.unit] || o.unit} is running outside systemd.`, `The container ${o.container} is serving${o.image ? ` from ${o.image}` : ''}, but its unit is stopped, so the buttons here cannot manage it and a reboot will not bring it back. Stop it from a terminal (docker rm -f ${o.container}) and start the unit instead.`)); @@ -1161,15 +1241,23 @@ function toast(text, cls, ms = 4000){ } function askAction(name, params, argv, warns){ if (offline){ toast('The cockpit is unreachable right now: nothing can be started.', 'err'); return; } - if (NEEDS_ENGINE.has(name) && !servingReady()){ toast('No engine is serving: start one first, then this action has something to talk to.', 'warn'); return; } + if (NEEDS_ENGINE.has(name) && !textReady()){ toast(imageServing() + ? 'The image lane is serving: this action talks to the text engine, which is not running.' + : 'No engine is serving: start one first, then this action has something to talk to.', 'warn'); return; } if (F.job && F.job.current){ toast(`Another action is running (${F.job.current.action}). Wait for the job strip to finish.`, 'warn'); return; } if (!$('modal').hidden) return; - const TARGET_NAME = {stock: 'stock 27B (NVFP4)', uncensored: 'uncensored 27B (NVFP4)', + const TARGET_NAME = {image: 'Qwen-Image 2.1 (images)', + stock: 'stock 27B (NVFP4)', uncensored: 'uncensored 27B (NVFP4)', fp8: 'FP8 27B (Qwen official)', 'uncensored-fp8': 'FP8 27B abliterated', flash: 'flash 176B (NVFP4)', 'flash-uncensored': 'flash 176B uncensored (NVFP4)', 'flash-nvda': 'flash 176B, NVIDIA export'}; const TARGET_NOTE = { + image: 'The image lane: text to image, editing with up to ten references, and native RGBA. ' + + 'It is a third lane with its own unit and its own venv, and like the other two it ' + + 'takes the box alone: 31 GB of weights do not fit beside a serving LLM. It answers in ' + + 'about 70 seconds after a start. The proxy on :30001 and opencode are text clients ' + + 'and are left exactly as they are.', fp8: 'Qwen\u2019s own FP8 release: the most faithful weights of this lane, and the heaviest. ' + '30.9 GB against 21 GB for NVFP4, and SGLang takes that out of the KV pool: expect around ' + '200,000 fewer tokens of context and a slower decode, because this box is bandwidth bound. ' @@ -1190,19 +1278,20 @@ function askAction(name, params, argv, warns){ switch: p => `switch the target model to ${TARGET_NAME[p.target] || p.target}`, flush_cache: () => 'flush the engine cache', abort_all: () => 'abort every in-flight generation', smoke: () => 'run a smoke generation through the proxy', diag_bundle: () => 'write a diagnostics bundle'}; const IMAGE_EXPLAIN = { - start: 'systemd starts the image lane and, through the unit\u2019s own Conflicts=, stops whichever text lane ' - + 'is serving: 31 GB of image weights do not fit beside a serving LLM. It answers in about 70 seconds. ' - + 'Starting a text lane again later stops this one the same way.', - stop: 'systemd stops the image lane. It does NOT bring a text lane back by itself: start the one you want.', - restart: 'systemd restarts the image lane; it reloads 31 GB and answers again in about 70 seconds.'}; + start: `systemd starts the image lane: it loads 31 GB (the Qwen3-VL encoder, the DiT, the VAE) and answers in ${readyIn(IMAGE_UNIT)}. ` + + 'Like every lane it takes the box alone, so this is only offered once no other engine is running.', + stop: 'systemd stops the image lane and the 31 GB come back at once. It does not bring a text lane back by itself: start the one you want.', + restart: `systemd restarts the image lane; it reloads 31 GB and answers again in ${readyIn(IMAGE_UNIT)}.`}; const AGENT_EXPLAIN = {stop: 'systemd stops opencode serve: the Agent tab goes dark until the server is started again.', start: 'systemd starts opencode serve on loopback; the Agent tab is back within seconds.', restart: 'systemd restarts opencode serve, which picks up an upgraded binary; the Agent tab reconnects by itself within seconds.'}; const EXPLAIN = {unit: p => p.unit === AGENT_UNIT ? AGENT_EXPLAIN[p.verb] || '' : p.unit === IMAGE_UNIT ? IMAGE_EXPLAIN[p.verb] || '' - : p.verb === 'stop' ? 'systemd stops the unit; the container gets SIGTERM and disappears in seconds.' : 'systemd starts the unit; the engine loads its weights and is ready in about 9 minutes (watch the boot bar).', + : p.verb === 'stop' ? 'systemd stops the unit; the container gets SIGTERM and disappears in seconds.' : `systemd starts the unit; the engine loads its weights and is ready in ${readyIn(p.unit)} (watch the boot bar).`, switch: p => (TARGET_NOTE[p.target] ? TARGET_NOTE[p.target] + '\n\n' : '') - + 'switch-model.sh rewrites the unit for the chosen target, updates the boot enablement, the proxy ceiling and the opencode default model. It never restarts anything: stop and start the engines afterwards.', + + (p.target === 'image' + ? 'switch-model.sh verifies the checkpoint and makes the image lane the one unit enabled at boot. It never restarts anything: stop the serving lane, then start this one.' + : 'switch-model.sh rewrites the unit for the chosen target, updates the boot enablement, the proxy ceiling and the opencode default model. It never restarts anything: stop and start the engines afterwards.'), flush_cache: () => 'Empties the radix cache. Harmless; refused by the engine if requests are running.', abort_all: () => 'Every running or queued generation ends now; the clients see their stream end.', smoke: () => 'One real 200-token generation through the proxy, the way a client uses it (up to a few minutes while a boot finishes).', @@ -1689,16 +1778,14 @@ const IMG_EXAMPLES = { 'Transparent sticker': {mode: 't2i', bg: 'transparent', prompt: 'This is an RGBA image with transparency. A cute cartoon dragon sticker. The image has an ' + 'alpha channel and the background is transparent.'}, + // the cookbook's own edit example, word for word, and the subject of "Use a sample" 'Local edit': {mode: 'edit', - prompt: 'Change the book cover to blue, keeping its shape, the candle, the table and the lighting unchanged.'}, + prompt: 'Change the red teapot to blue, keeping its shape, table, window, and lighting unchanged.'}, 'Combine two': {mode: 'edit', prompt: 'Combine the subjects from Picture 1 and Picture 2 into one coherent scene, preserving their appearance.'}, }; let imgRefs = []; // [{name, dataUrl, w, h}], in the order the model labels them -// Declared here rather than beside imgLane(), because imgSync() reads `available` and -// runs long before the first status poll comes back. -const IMG_STATE = {port: 30020, host: '127.0.0.1', available: false, busy: false}; -let imgInflight = null; // when this page's own request started, or null + const imgVal = id => ($(id) ? $(id).value.trim() : ''); function imgSize(){ @@ -1731,18 +1818,25 @@ function imgProblem(){ return ''; } -// Fitted to this box, not to the engine's own stage timings: end-to-end seconds against -// steps at 1024x1024 (8/20/40/60 -> 8.4/19.8/38.2/57.3) and against pixels at 40 steps -// (512/768/1024/1664x928 -> 9.0/22.6/38.2/60.4). Both are very nearly linear. Editing -// pays for one more encode: 44.6 s where the same generation costs 38.2. -function imgEstimate(){ +// Fitted to this box, end to end, on six measured sizes at 40 steps: 512x512 9.0 s, +// 768x768 22.6, 1024x1024 36.6-38.2, 1664x928 60.4, 2048x2048 190.9, 2752x1536 193.1. +// Not linear in pixels: four times the pixels of 1024x1024 cost 5.2 times the time, +// because attention grows faster than the token count. A power law fits all six within +// 6%: t = 1 + steps x 0.97 x (pixels / 1024^2)^1.14. Linear in steps, measured at 1024 +// (8/20/40/60 -> 8.4/19.8/38.2/57.3). Editing pays for one more encode: 44.6 s where the +// same generation costs 38.2. +function imgEstimate(req){ + const q = req || imgFormRequest(); + if (!q.w || !q.h || !q.steps) return null; + const px = (q.w * q.h) / (1024 * 1024); + return (1 + q.steps * 0.97 * Math.pow(px, 1.14) + (q.editing ? 6 : 0)) * (q.n || 1); +} +// What the form would send. The request in flight keeps its own copy (IMG_RUN), because +// the form can change under it, and the sample reference is a request of its own. +function imgFormRequest(){ const {w, h} = imgSize(); - const steps = Number($('imgsteps').value) || 0; - const n = Number($('imgn').value) || 1; - if (!w || !h || !steps) return null; - const px = (w * h) / (1024 * 1024); - const editing = $('imgmode-edit').getAttribute('aria-pressed') === 'true'; - return (0.9 + steps * 0.94 * px + (editing ? 6 : 0)) * n; + return {w, h, steps: Number($('imgsteps').value) || 0, n: Number($('imgn').value) || 1, + editing: $('imgmode-edit').getAttribute('aria-pressed') === 'true'}; } function imgCost(){ @@ -1751,7 +1845,7 @@ function imgCost(){ const bits = []; if (secs) bits.push('about ' + fmtDur(secs) + ' on this box'); if (w && h) bits.push((w * h / 1e6).toFixed(2) + ' megapixels'); - if (w >= 2048 || h >= 2048) bits.push('this is four times the verified size: slower, and it has not been measured here'); + if (w * h >= 3.5e6) bits.push('peaks at 44.8 GB instead of 34: four times the pixels, five times the time'); setText('imgcost', bits.join(' · ')); } @@ -1896,6 +1990,7 @@ function imgDraw(out, fmt){ // The format is the one this answer was REQUESTED with, captured by the caller. Read // off the select at click time instead, changing it without regenerating saved PNG // bytes under a .webp name. + imgParkBar(); // before the frame holding it is emptied const box = $('imgout'); clear(box); const imgs = (out.data || []); const shots = el('div', 'shots' + (imgs.length > 1 ? ' multi' : '')); @@ -1937,14 +2032,39 @@ function imgDraw(out, fmt){ // and an empty panel for 38 seconds looks like nothing is happening. function imgFrame(n){ const {w, h} = imgSize(); + imgParkBar(); // before the frame holding it is emptied const box = $('imgout'); clear(box); const wrap = el('div', 'shots' + (n > 1 ? ' multi' : '')); for (let i = 0; i < Math.min(n, 2); i++){ - const f = el('div', 'frame', n > 1 ? `image ${i + 1} of ${n}` : `${w} x ${h}`); + const f = el('div', 'frame'); f.style.aspectRatio = `${w} / ${h}`; + // The progress goes inside the frame of the answer it is producing, where the eye + // already is. Below it, a 1024 square pushed it off a laptop screen. + if (i === 0) f.append(imgRunProg()); + else f.append(el('span', null, `image ${i + 1} of ${n}`)); wrap.append(f); } box.append(wrap); + // On a phone the result panel sits under the form: bring it on screen, or the wait + // happens somewhere the user cannot see. + const panel = box.closest('.panel'); + const r = panel && panel.getBoundingClientRect(); + if (r && (r.top > window.innerHeight * 0.6 || r.bottom < 0)){ + // Offset by the sticky bars as they are right now: on a phone the top bar wraps onto + // two or three rows, so a fixed margin would park the panel's own header under it. + const cover = [...document.querySelectorAll('.top, .jobstrip')] + .reduce((h, e) => h + (e.offsetParent !== null ? e.getBoundingClientRect().height : 0), 0); + window.scrollTo({top: window.scrollY + r.top - cover - 8, behavior: 'smooth'}); + } +} +// The bar has a home under the output, and leaves it only while a request runs. It is +// held by reference because it travels INTO the frame, and emptying the output panel +// (a finished image, a refusal) detaches it: getElementById does not find a detached +// node, so the next generation would have appended null. +function imgParkBar(){ + const p = imgRunProg(); const meta = $('imgmeta'); + if (p && meta && p.nextElementSibling !== meta) meta.before(p); + if (p) p.hidden = true; } async function imgRun(){ @@ -1956,7 +2076,7 @@ async function imgRun(){ setText('imgstatus', editing ? 'editing...' : 'generating...'); setChip('imgtime', est ? '~' + fmtDur(est) : ''); const t0 = Date.now(); - imgInflight = t0; + imgInflight = t0; IMG_RUN = imgFormRequest(); imgFrame(Number($('imgn').value) || 1); clear($('imgmeta')); imgStageAt = {stage: '', at: 0}; @@ -1978,7 +2098,7 @@ async function imgRun(){ if (!r.ok){ const why = out.error || (out.refused ? JSON.stringify(out.refused).slice(0, 300) : 'HTTP ' + r.status); if (r.status === 409){ toast(why, 'warn', 7000); setChip('imgtime', 'lane busy', 'warn'); return; } - clear($('imgout')); $('imgout').append(el('p', 'note', 'Refused with HTTP ' + r.status + ': ' + why)); + imgParkBar(); clear($('imgout')); $('imgout').append(el('p', 'note', 'Refused with HTTP ' + r.status + ': ' + why)); setChip('imgtime', r.status + ' refused', 'err'); return; } @@ -1988,24 +2108,14 @@ async function imgRun(){ toast('The cockpit could not reach the image lane: ' + e.message, 'err'); setChip('imgtime', 'failed', 'err'); } finally { - clearInterval(tick); imgInflight = null; - $('imgrunprog').hidden = true; + clearInterval(tick); imgInflight = null; IMG_RUN = null; + imgParkBar(); imgWatch(false); btn.disabled = false; setText('imgstatus', ''); imgSync(); imgLane(); // the lane may have gone away under the request } } -// The lane is started and stopped from here, through the same modal, job strip and -// sudoers allowlist as every other unit. A tab that tells you to open a terminal is not -// a cockpit, which is the whole point of this page. -function imgUnitButton(verb, label, warns){ - const b = el('button', 'btn mini' + (verb === 'start' ? '' : ' low'), label); - b.addEventListener('click', () => askAction('unit', {verb, unit: IMAGE_UNIT}, - ['sudo', '-n', '/usr/bin/systemctl', verb, IMAGE_UNIT], warns)); - return b; -} - let imgPoll = null; function imgWatch(on, ms = 2500){ // A request in flight is its own reason to keep asking: the lane answering /health is @@ -2025,7 +2135,7 @@ function imgWatch(on, ms = 2500){ // per-step signal: tqdm writes with carriage returns, journald only breaks on newlines, // /metrics is not served and /stats is empty. function imgBar(ids, prog, right, pct){ - const box = $(ids.box); + const box = ids.box === 'imgrunprog' ? imgRunProg() : $(ids.box); if (!prog || !prog.label){ box.hidden = true; return; } box.hidden = false; box.classList.toggle('indet', pct == null); @@ -2036,7 +2146,6 @@ function imgBar(ids, prog, right, pct){ // is a width. Going from a full track to 2% would read as progress running backwards. $(ids.bar).style.width = pct == null ? '100%' : Math.max(2, Math.min(100, pct)) + '%'; } -const IMG_BOOT_BAR = {box: 'imgbootprog', lab: 'imgbootlab', pct: 'imgbootpct', bar: 'imgbootbar'}; const IMG_RUN_BAR = {box: 'imgrunprog', lab: 'imgrunlab', pct: 'imgrunpct', bar: 'imgrunbar'}; // When the engine entered the stage it is in now. The page times the bar from here @@ -2050,14 +2159,20 @@ function imgDrawRunBar(p){ if (p.stage !== 'denoising') return imgBar(IMG_RUN_BAR, p, fmtDur(secs), null); // seconds, no honest fraction // Denoising is nearly all of the cost and is linear in steps, measured on this box. - const steps = Number($('imgsteps').value) || 40; - const budget = Math.max(1, imgEstimate() - 3); + // Timed against the request that is actually running, not the form as it reads now. + const req = IMG_RUN || imgFormRequest(); + const steps = req.steps || 40; + const budget = Math.max(1, imgEstimate(req) - 3); const frac = Math.min(secs / budget, 0.99); imgBar(IMG_RUN_BAR, {label: `denoising, ${steps} steps`}, `about ${Math.round(frac * 100)}%, ~${fmtDur(Math.max(0, budget - secs))} left`, frac * 100); } +// The Image tab reads the SAME lifecycle as the action bar, the lane pill and the +// Engines tab, so the four can never disagree about whether this lane is up. It has no +// start or stop of its own: the image lane is switched to and started exactly like the +// two text lanes, from the one switcher at the top. async function imgLane(){ try{ const r = await fetch('/api/image'); @@ -2066,49 +2181,70 @@ async function imgLane(){ IMG_STATE.port = d.port || 30020; IMG_STATE.host = d.host || '127.0.0.1'; IMG_STATE.available = !!d.available; - setText('imgmodel', d.model || 'Qwen/Qwen-Image-2.1'); - const ctl = $('imgctl'); clear(ctl); - if (!d.installed){ - setChip('imgchip', 'not installed', 'warn'); - ctl.append(el('span', 'chip', 'install it with: ./install.sh --with-image')); - ctl.append(el('span', 'chip', '38 GB, about 25 min, one command')); - imgWatch(false); - } else if (d.available){ - setChip('imgchip', 'serving on :' + IMG_STATE.port, 'ok'); - ctl.append(imgUnitButton('stop', 'Stop the image lane')); - ctl.append(el('span', 'chip', d.llm_lane - ? 'the text lane is stopped while this serves' : 'this lane has the box')); - imgWatch(false); - } else if (d.state === 'loading weights' || d.state === 'starting'){ - setChip('imgchip', 'starting', 'warn'); - ctl.append(el('span', 'chip', 'about a minute; the button turns on by itself')); - ctl.append(imgUnitButton('stop', 'Stop')); - imgWatch(true, 2000); - } else { - setChip('imgchip', d.state || 'stopped', d.state === 'failed' ? 'err' : ''); - ctl.append(imgUnitButton('start', 'Start the image lane', - d.llm_lane ? ['Starting this STOPS ' + d.llm_lane + ': 31 GB of image weights do not fit ' - + 'beside a serving LLM. Bringing the text lane back afterwards is another ' - + '9 minutes of boot.'] : [])); - if (d.llm_lane) ctl.append(el('span', 'chip', 'serving now: ' + d.llm_lane)); - if (d.state === 'failed') ctl.append(el('span', 'chip', 'read why in the Logs tab')); - imgWatch(false); - } + IMG_STATE.installed = !!d.installed; + IMG_STATE.model = d.model || 'Qwen/Qwen-Image-2.1'; const p = d.progress || {}; - imgBar(IMG_BOOT_BAR, p.kind === 'boot' ? p : null, (p.pct || 0) + '%', p.pct); if (imgInflight) imgDrawRunBar(p.kind === 'boot' ? null : p); // Someone else generating counts: this lane serves one at a time, and a second // request does not queue politely, it holds another 60 GB of a 122 GB box. - const busyElsewhere = !imgInflight && p.kind === 'stage'; - IMG_STATE.busy = busyElsewhere; - if (busyElsewhere){ - setChip('imgchip', 'busy: ' + p.label, 'warn'); - imgWatch(true, 2000); - } - $('imgrun').disabled = !d.available || busyElsewhere || !!imgProblem() || !imgVal('imgprompt'); + IMG_STATE.busy = !imgInflight && p.kind === 'stage'; + IMG_STATE.busyLabel = p.label || ''; + if (IMG_STATE.busy) imgWatch(true, 2000); + imgRenderLane(); } catch (e){ setChip('imgchip', 'unknown', 'warn'); } } +// Render only, no request: called from imgLane() and from every lifecycle tick, so a +// boot moves here at the same pace it moves in the Engines tab. +function imgRenderLane(){ + if (!$('imgctl')) return; + setText('imgmodel', IMG_STATE.model || 'Qwen/Qwen-Image-2.1'); + const e = ((F.life || {}).engines || {})[IMAGE_UNIT]; + const ctl = $('imgctl'); clear(ctl); + const boot = $('imgboot'); clear(boot); + const guide = $('imgsteps-guide'); clear(guide); guide.hidden = true; + const say = txt => ctl.append(el('span', 'chip', txt)); + const serving = servingEngine(); + const other = serving && serving[0] !== IMAGE_UNIT ? serving[0] : null; + const otherName = other ? laneLabel(other) : ''; + // The lifecycle only carries this unit when it is installed, so its presence is the + // answer; the fetch's own flag may not have come back yet on a first render. + if (!e){ + setChip('imgchip', 'not installed', 'warn'); + say('install it with: ./install.sh --with-image'); + say('38 GB, about 25 min, one command'); + } else if (e.state === 'ready' || e.state === 'degraded'){ + setChip('imgchip', IMG_STATE.busy ? 'busy: ' + IMG_STATE.busyLabel : 'serving on :' + IMG_STATE.port, + IMG_STATE.busy ? 'warn' : 'ok'); + say(IMG_STATE.busy ? 'someone is generating: one image at a time on this lane' + : 'stop it from the action bar at the top, like any lane'); + } else if (TRANSITIONAL.has(e.state)){ + setChip('imgchip', STATE_LABEL[e.state] || e.state, 'warn'); + boot.append(bootBlock(e, IMAGE_UNIT)); + say('Generate turns on by itself the moment it answers'); + } else if (e.state === 'stopping'){ + setChip('imgchip', 'stopping', 'warn'); + boot.append(stoppingBlock(e)); + } else { + setChip('imgchip', e.state === 'failed' ? 'failed' : 'stopped', e.state === 'failed' ? 'err' : ''); + if (e.state === 'failed') say('the unit failed: its journal is in the Logs tab'); + // The same three moves as for any lane, in the action bar at the top, named exactly + // as its buttons read. Only the steps still to do are shown, the first one marked. + const steps = []; + if (other) steps.push(`Stop ${LANE_NAME[other] || otherName}: ${otherName} is serving, and two engines never run at once`); + if (enabledUnit() !== IMAGE_UNIT) steps.push('Pick Qwen-Image 2.1 in the switcher, then press Switch'); + steps.push(`Press Start Qwen-Image (${readyIn(IMAGE_UNIT)} to ready)`); + guide.hidden = false; + steps.forEach((s, i) => guide.append(el('li', i === 0 ? 'now' : '', s))); + } + // The lifecycle derives ready from the lane's own /health answering 200, every two + // seconds. Trusting it here, rather than the tab's last fetch, is what lets Generate + // turn on by itself at the end of a boot the tab watched from its first second. + const ready = !!e && (e.state === 'ready' || e.state === 'degraded'); + IMG_STATE.available = ready; + $('imgrun').disabled = !ready || IMG_STATE.busy || !!imgProblem() || !imgVal('imgprompt'); +} + function imgInit(){ if (!$('imgsize')) return; IMG_SIZES.forEach(([v, label]) => { @@ -2131,10 +2267,23 @@ function imgInit(){ toast('Back to the model’s own defaults: 1024×1024, 40 steps, one image, CFG off.', 'ok', 2600); }); $('imgrefadd').addEventListener('click', () => $('imgreffile').click()); $('imgreffile').addEventListener('change', e => { imgAddFiles(e.target.files); e.target.value = ''; }); + // The sample is a generation like any other, so it waits like one: the same frame, + // the same bar in it, the same lock on both buttons. It used to run for twenty seconds + // behind a one-line status, with both buttons still live, so a second click was a + // second request the cockpit refused with 409 and a toast that read like a failure. + // The subject is the cookbook's own edit example, a red teapot by a window, so the + // "Local edit" prompt (also the cookbook's) actually describes what is in the picture. $('imgrefsample').addEventListener('click', async () => { if (imgRefs.length >= 10) return toast('Ten references is the maximum.', 'warn'); - setText('imgstatus', 'making a sample to edit...'); - const saved = {prompt: $('imgprompt').value, mode: $('imgmode-edit').getAttribute('aria-pressed')}; + if (imgInflight || IMG_STATE.busy) return toast('The lane is already generating; one image at a time.', 'warn'); + const btns = [$('imgrefsample'), $('imgrun')]; + btns.forEach(b => { b.disabled = true; }); + const t0 = Date.now(); imgInflight = t0; + IMG_RUN = {w: 1024, h: 1024, steps: 20, n: 1, editing: false}; // what the sample asks for + setText('imgstatus', 'making a sample reference: a red teapot by a window'); + imgFrame(1); imgStageAt = {stage: '', at: 0}; + imgBar(IMG_RUN_BAR, {label: 'making the sample reference'}, '', null); + imgWatch(true, 1500); try{ const t = await fetch('/api/csrf', {method: 'POST'}); if (t.status === 401) return login(); const tok = (await t.json()).token; @@ -2143,17 +2292,22 @@ function imgInit(){ + 'next to a window, even natural light', width: 1024, height: 1024, num_inference_steps: 20, n: 1, output_format: 'png', response_format: 'b64_json', generator_device: 'cpu', seed: 42})}); const out = await r.json(); - if (!r.ok) return toast('Could not make a sample: ' + (out.error || r.status), 'err'); + if (!r.ok) return toast(r.status === 409 ? out.error : 'Could not make a sample: ' + (out.error || r.status), + r.status === 409 ? 'warn' : 'err', 7000); const first = ((out.image || out).data || [])[0]; if (!first || !first.b64_json) return toast('The lane answered 200 with no image in it.', 'err'); imgRefs.push({name: 'sample-teapot.png', dataUrl: 'data:image/png;base64,' + first.b64_json, w: 1024, h: 1024}); + imgDraw(out.image || out, 'png'); imgDrawRefs(); - toast('Sample added as Picture ' + imgRefs.length + '. Try the "Local edit" example on it.', 'ok'); + toast('Sample added as Picture ' + imgRefs.length + ': a red teapot. The "Local edit" example turns it blue.', 'ok', 5000); } catch (e){ toast('Could not make a sample: ' + e.message, 'err'); - } finally { setText('imgstatus', ''); $('imgprompt').value = saved.prompt; imgSync(); } + } finally { + imgInflight = null; IMG_RUN = null; imgParkBar(); imgWatch(false); + setText('imgstatus', ''); btns.forEach(b => { b.disabled = false; }); imgSync(); + } }); $('imgrun').addEventListener('click', imgRun); $('imgcopy').addEventListener('click', async () => { diff --git a/dashboard/static/index.html b/dashboard/static/index.html index b8efca59..632c413a 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -25,7 +25,7 @@ clay = broken. Green, orange, blue and neon pink are gone from this app. */ --acc:#d8b161; --acc-hi:#ecd9a4; --ok:#d8b161; --warn:#b5814e; --err:#c9706a; /* the two lanes share the house palette: flash wears the gold, 27B the steel */ - --flash:#d8b161; --lane27:#9d9ea3; + --flash:#d8b161; --lane27:#9d9ea3; --image:#7fa6b8; --shadow:0 10px 30px rgba(0,0,0,.5); --rail:236px; --rail-min:64px; --top:58px; /* One spacing scale for the whole app, so no component invents its own. */ @@ -193,6 +193,7 @@ .chip.warn{color:var(--warn); border-color:color-mix(in srgb, var(--warn) 50%, transparent); background:color-mix(in srgb, var(--warn) 12%, transparent)} .chip.flash{color:var(--flash); border-color:color-mix(in srgb, var(--flash) 50%, transparent); background:color-mix(in srgb, var(--flash) 12%, transparent)} .chip.lane27{color:var(--lane27); border-color:color-mix(in srgb, var(--lane27) 50%, transparent); background:color-mix(in srgb, var(--lane27) 12%, transparent)} + .chip.laneimg{color:var(--image); border-color:color-mix(in srgb, var(--image) 50%, transparent); background:color-mix(in srgb, var(--image) 12%, transparent)} .chip.live::before{content:''; display:inline-block; width:7px; height:7px; border-radius:50%; background:currentColor; margin-right:6px; animation:pulse 1.2s ease-in-out infinite} .skel{color:transparent !important; background:linear-gradient(90deg, var(--soft), var(--line), var(--soft)); background-size:200% 100%; animation:skel 1.2s linear infinite; border-radius:6px} @@ -386,6 +387,15 @@ .img .warn{font-size:12px; color:var(--err); margin:7px 0 0; line-height:1.55} .img .cost{font:400 12px var(--mono); color:var(--mut); margin-top:8px} /* the checkerboard is the instrument: it is what makes an alpha channel visible */ + /* The answer fits the screen: a square 1024 frame at the panel's width is taller than + a laptop viewport, which put the progress bar and then the image's own facts below + the fold, the one place nobody was looking while they waited. */ + .img .shot img{max-height:62vh; object-fit:contain} + .img .frame{max-height:62vh} + .img .frame .prog{width:min(420px, 86%); margin:0; text-align:left} + .img .steps{margin:9px 0 0; padding-left:20px; font-size:13px; line-height:1.7; color:var(--mut)} + .img .steps li.now{color:var(--txt); font-weight:600} + .img .steps li.done{text-decoration:line-through; opacity:.6} .img .shot{border:1px solid var(--line); border-radius:var(--r-ctl); overflow:hidden; line-height:0; background-color:#f3f3f3; background-image:linear-gradient(45deg,#d2d2d2 25%,transparent 25%,transparent 75%,#d2d2d2 75%), @@ -408,7 +418,7 @@ off the engine's own log. The phase name is exact; the bar is real per-step progress once denoising starts. */ .img .prog{margin-top:10px} - .img .prog .lab{display:flex; justify-content:space-between; gap:10px; align-items:baseline; + .img .prog .lab{display:flex; justify-content:space-between; gap:4px 10px; align-items:baseline; flex-wrap:wrap; font:400 12px/1.5 var(--mono); color:var(--mut); margin-bottom:5px} .img .prog .lab b{color:var(--txt); font-weight:600} .img .prog .tr{height:7px; border-radius:5px; overflow:hidden; border:1px solid var(--line); @@ -425,12 +435,12 @@ @keyframes imgpulse{0%,100%{opacity:.45} 50%{opacity:1}} @media (prefers-reduced-motion:reduce){ .img .prog.indet .fl{animation:imgpulse 1.8s ease-in-out infinite; left:0; width:100% !important} - .img .frame{animation:none} } + /* no opacity pulse on the frame itself: it now holds the progress text, and a + fading label is a label nobody can read. The bar inside carries the motion. */ .img .frame{border:1px dashed var(--line); border-radius:var(--r-ctl); display:grid; place-items:center; color:var(--mut); font:400 12px var(--mono); text-align:center; - background:color-mix(in srgb, var(--card2) 40%, transparent); padding:14px; - animation:imgpulse 2s ease-in-out infinite} + background:color-mix(in srgb, var(--card2) 40%, transparent); padding:14px} @media (max-width:900px){ .img .shots.multi{grid-template-columns:1fr} } /* ── modal ── */ @@ -652,13 +662,18 @@
@@ -1065,10 +1080,8 @@
Licence
Qwen Research License: research and evaluation, not commercial use
- + +
@@ -1177,9 +1190,9 @@

What each setting costs measured on this box, 2026-09-22

Every number below came from a request to this lane, not from the cookbook. - Time is dominated by pixels and steps and is very nearly linear in both, which is where the estimate under the - button comes from: about 0.9 s fixed, plus 0.94 s per step at 1024×1024, scaled by megapixels. An edit pays - for one more encode, six seconds.

+ Time is linear in steps and a little faster than linear in pixels: four times the pixels of 1024×1024 cost + 5.2 times the time, because attention grows faster than the token count. The estimate under the button is the + curve through the sizes below, within 6% of every one of them. An edit pays for one more encode, six seconds.

@@ -1188,6 +1201,8 @@ + + diff --git a/dashboard/sudoers-cockpit.template b/dashboard/sudoers-cockpit.template index 2317c077..1dc67649 100644 --- a/dashboard/sudoers-cockpit.template +++ b/dashboard/sudoers-cockpit.template @@ -31,6 +31,8 @@ __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl enable qwen38-sglang.service __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl enable qwen38-flash.service __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl disable qwen38-sglang.service __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl disable qwen38-flash.service +__USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl enable qwen38-image.service +__USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl disable qwen38-image.service __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl daemon-reload __USER__ ALL=(root) NOPASSWD: /usr/bin/install -m 644 __HOME__/.config/qwen38/qwen38-sglang.service.switch-stage /etc/systemd/system/qwen38-sglang.service __USER__ ALL=(root) NOPASSWD: /usr/bin/install -m 644 -D __HOME__/.config/qwen38/keepalive-ceiling.conf.switch-stage /etc/systemd/system/qwen38-keepalive.service.d/ceiling.conf diff --git a/dashboard/tests/fixtures/image-boot.log b/dashboard/tests/fixtures/image-boot.log new file mode 100644 index 00000000..5e4cd7a8 --- /dev/null +++ b/dashboard/tests/fixtures/image-boot.log @@ -0,0 +1,52 @@ +[09-22 17:20:37] Starting server... +[09-22 17:20:43] Scheduler (dp replica 0) bind at endpoint: tcp://127.0.0.1:5563 +[09-22 17:20:43] torch.compile cache: TORCHINDUCTOR_CACHE_DIR=/home/hasan/.cache/sgl_diffusion/torch_compile_cache/inductor TRITON_CACHE_DIR=/home/hasan/.cache/sgl_diffusion/torch_compile_cache/triton +[09-22 17:20:43] Initializing distributed environment with world_size=1, device=cuda:0, timeout=3600 +[09-22 17:20:43] Setting distributed timeout to 3600 seconds +[09-22 17:20:44] No pipeline_class_name specified, using model_index.json +[09-22 17:20:44] Using pipeline from model_index.json: QwenImage21Pipeline +[09-22 17:20:44] Loading pipeline modules... +[09-22 17:20:44] Checking for cached model in Hugging Face Hub cache for Qwen/Qwen-Image-2.1... +[09-22 17:20:44] Found complete model in cache at /home/hasan/.cache/huggingface/hub/models--Qwen--Qwen-Image-2.1/snapshots/790c92633540aa0cb11d9abf19eb46d861714758 +[09-22 17:20:44] Model path: /home/hasan/.cache/huggingface/hub/models--Qwen--Qwen-Image-2.1/snapshots/790c92633540aa0cb11d9abf19eb46d861714758 +[09-22 17:20:44] Diffusers version: 0.37.0.dev0 +[09-22 17:20:44] Loading required components: ['processor', 'text_encoder', 'transformer', 'vae', 'scheduler'] +[09-22 17:20:44] Memory-aware component load order: ['text_encoder', 'transformer', 'vae', 'processor', 'scheduler'] + Loading required modules: 0%| | 0/5 [00:00 "$RENDER" grep -q '__[A-Z_]*__' "$RENDER" && die "the unit template still holds an unsubstituted placeholder: $(grep -o '__[A-Z_]*__' "$RENDER" | sort -u | tr '\n' ' ')" +# 0644 like every other unit, and set explicitly: mktemp creates 0600 and cp keeps the +# mode, which left this unit readable by root alone. systemd did not mind; everything +# else that reads the unit did, and failed quietly. switch-model.sh could not find the +# runtime, and the cockpit's reads of the port, the bind and the model all fell back to +# their defaults, which happened to be right on the reference box and would not have been +# on one installed with IMAGE_PORT= or IMAGE_BIND=. if [ -f "$INSTALLED" ] && sudo cmp -s "$RENDER" "$INSTALLED"; then echo "unit unchanged" + sudo chmod 644 "$INSTALLED" # a unit installed before this fix is still 0600 else - sudo cp "$RENDER" "$INSTALLED"; sudo systemctl daemon-reload + sudo install -m 644 "$RENDER" "$INSTALLED"; sudo systemctl daemon-reload echo "unit installed at $INSTALLED" fi -# Not enabled at boot on purpose: starting it stops the LLM lane, and a box that reboots -# should come back the way its owner left it, not holding 31 GB of image weights. -echo "not enabled at boot (starting it stops the LLM lane). Start it when you want images:" -echo " sudo systemctl start $UNIT" +# Installed, not switched to: the lane this box serves stays the lane it serves. The image +# lane becomes the boot lane the same way the other two do, by a switch, which is also +# what makes it come back after a reboot. +echo "installed as a lane of its own. Switch to it like any lane:" +echo " the cockpit: pick Qwen-Image 2.1 in the switcher, Switch, stop the serving lane, Start" +echo " a terminal : ./switch-model.sh image, then the two commands it prints" if [ "$SMOKE" -eq 0 ]; then step "Done (smoke test skipped)"; exit 0; fi @@ -194,12 +203,16 @@ WAS_LLM="" for u in qwen38-sglang.service qwen38-flash.service; do systemctl is-active --quiet "$u" 2>/dev/null && WAS_LLM="$u" done +# If this lane was already serving, the test leaves it serving: stopping it on the way out +# would turn "re-run the installer" into "take the image lane down". +WAS_IMAGE=0 +systemctl is-active --quiet "$UNIT" 2>/dev/null && WAS_IMAGE=1 [ -n "$WAS_LLM" ] && echo "note: $WAS_LLM is serving and will be stopped for this test, then started again." # From here on the text lane is DOWN, so putting it back cannot live on the happy path: # every die() below would leave the box serving nothing, with the image unit holding # 31 GB, until somebody noticed. The trap runs on success and on every failure alike. restore_text_lane() { - sudo systemctl stop "$UNIT" 2>/dev/null || true + [ "$WAS_IMAGE" -eq 1 ] || sudo systemctl stop "$UNIT" 2>/dev/null || true if [ -n "$WAS_LLM" ]; then echo "starting $WAS_LLM again" sudo systemctl start "$WAS_LLM" || echo "WARNING: could not restart $WAS_LLM. Do it by hand: sudo systemctl start $WAS_LLM" @@ -231,8 +244,7 @@ print(f" {w}x{h} {'RGBA' if raw[25] == 6 else raw[25]}, {len(raw)/1e6:.1f} MB" PY # the trap stops the lane and brings the text lane back, whichever way this ends -step "Done: the image lane serves on $IMAGE_BIND:$PORT" -echo " start : sudo systemctl start $UNIT (this stops the LLM lane)" -echo " stop : sudo systemctl stop $UNIT" -echo " back to text: sudo systemctl start qwen38-sglang.service" -echo " drive it from the cockpit's Image tab, or straight from the API on :$PORT" +step "Done: the image lane is installed and proved it serves on $IMAGE_BIND:$PORT" +echo " switch to it : the cockpit's switcher (Qwen-Image 2.1), or ./switch-model.sh image" +echo " back to text : the switcher again (any text target), or ./switch-model.sh stock" +echo " generate : the cockpit's Image tab, or the API on :$PORT (loopback, no key)" diff --git a/install.sh b/install.sh index 726fe344..1748886d 100755 --- a/install.sh +++ b/install.sh @@ -565,6 +565,18 @@ SGL_READABLE=0; FLASH_READABLE=0 FLASH_ENABLED=0; SGL_ENABLED=0 systemctl is-enabled --quiet qwen38-flash.service 2>/dev/null && FLASH_ENABLED=1 systemctl is-enabled --quiet qwen38-sglang.service 2>/dev/null && SGL_ENABLED=1 +# The image lane is a lane too, and when it is the one enabled at boot it was switched to +# on purpose. A plain re-run must keep that, the same promise it keeps for the target, the +# context mode and the port: without this it fell through to "27b" below, enabled the 27B +# unit beside the image one, and left two engines set to start at the next reboot, with +# only the order systemd happened to pull them in deciding which one came up. +IMAGE_BOOT=0 +if systemctl is-enabled --quiet qwen38-image.service 2>/dev/null \ + && [ "$SGL_ENABLED" -eq 0 ] && [ "$FLASH_ENABLED" -eq 0 ]; then + IMAGE_BOOT=1 + echo "The image lane is this box's boot lane: this run brings the text lane up to date" + echo "without making it the boot lane again. Switch back to text from the cockpit when you want it." +fi if [ "$FLASH_READABLE" -eq 1 ] && [ "$FLASH_ENABLED" -eq 1 ] && [ "$SGL_ENABLED" -eq 1 ]; then echo "NOTE: both qwen38-sglang and qwen38-flash are enabled (only one can serve the port)." echo " Following the 27B unit; run ./switch-model.sh to resolve this cleanly." @@ -1527,7 +1539,24 @@ if [ -f "/etc/systemd/system/$UNIT_NAME.d/warmup.conf" ]; then fi rm -f "$CONFIG_DIR/warmup-claude-code.sh" sudo systemctl daemon-reload -sudo systemctl enable "$UNIT_NAME" +if [ "$IMAGE_BOOT" -eq 0 ]; then + sudo systemctl enable "$UNIT_NAME" +else + # Updated, not switched to. Starting it would stop the image lane that is serving, and + # the cockpit and the image step below only run once a text engine has proved itself, + # so this path finishes here, on its own, instead of waiting for a boot it must not do. + if [ "$COCKPIT" -eq 1 ] && [ -x "$REPO_DIR/dashboard/install-dashboard.sh" ]; then + "$REPO_DIR/dashboard/install-dashboard.sh" \ + || echo "NOTE: the cockpit did not reinstall; retry with ./dashboard/install-dashboard.sh" + fi + # --no-smoke always: the smoke test starts and stops the lane, and this lane is serving. + "$REPO_DIR/install-image.sh" --no-smoke \ + || echo "NOTE: the image lane did not update; retry with ./install-image.sh --no-smoke" + step "Done: the text lane is up to date; the image lane stays this box's serving lane" + echo " text lane : installed as $UNIT_NAME, not enabled at boot" + echo " back to it: the cockpit's switcher, or ./switch-model.sh $MODEL_CHOICE" + exit 0 +fi if [ "$NO_START" -eq 1 ]; then step "Done (service installed and enabled at boot; start it with: sudo systemctl start $UNIT_NAME)" @@ -1722,7 +1751,7 @@ except Exception as e: fi [ "$COCKPIT" -eq 0 ] && echo " cockpit : off (--no-cockpit); ./install.sh --with-cockpit turns it on" if [ "${IMAGE_READY:-0}" -eq 1 ]; then - echo " Images : sudo systemctl start qwen38-image.service (stops the LLM lane; Image tab of the cockpit)" + echo " Images : a third lane; switch to Qwen-Image 2.1 in the cockpit (or ./switch-model.sh image)" elif [ "${IMAGE_ON:-0}" -eq 0 ]; then echo " Images : not installed; ./install.sh --with-image adds the Qwen-Image 2.1 lane (38 GB)" fi diff --git a/switch-model.sh b/switch-model.sh index c5c0eb7b..31f7cce5 100755 --- a/switch-model.sh +++ b/switch-model.sh @@ -8,6 +8,7 @@ # ./switch-model.sh flash # RadixArk/Qwen3.8-Flash-Next-NVFP4 (SGLang) # ./switch-model.sh flash-nvda # nvidia/Qwen3.8-Flash-Next-NVFP4, ModelOpt mixed precision # ./switch-model.sh flash-uncensored # the abliterated build of the same tree +# ./switch-model.sh image # Qwen/Qwen-Image-2.1 (SGLang Diffusion, own venv) # # Within the 27B lane (stock, uncensored, fp8, uncensored-fp8) it does what it # always did: @@ -31,7 +32,8 @@ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" die() { printf '\n\033[1;31mERROR:\033[0m %s\n' "$*" >&2; exit 1; } CHOICE="${1:-${MODEL_CHOICE:-stock}}" -case "$CHOICE" in stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored) ;; *) die "usage: ./switch-model.sh [stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored]" ;; esac +case "$CHOICE" in stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored|image) ;; *) die "usage: ./switch-model.sh [stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored|image]" ;; esac + PINS="$(grep -E '^(IMAGE|STOCK_REPO|STOCK_REV|UNC_REPO|UNC_REV|FP8_REPO|FP8_REV|UNCFP8_REPO|UNCFP8_REV|FLASH_REPO|FLASH_REV|FLASH_NVDA_REPO|FLASH_NVDA_REV|FLASH_UNC_REPO|FLASH_UNC_REV|FLASH_IMAGE|FLASH_SERVE_IMAGE|OVERLAY_FLASH_SERVE_IMAGE|SERVE_IMAGE|MODEL_CHOICE|HF_CACHE|CONFIG_DIR)=' "$REPO_DIR/install.sh" || true)" # A count of matched lines was the old check, and adding a pin broke both scripts @@ -44,6 +46,68 @@ for _v in IMAGE SERVE_IMAGE STOCK_REPO STOCK_REV UNC_REPO UNC_REV FP8_REPO FP8_R done unset _v +IMAGE_UNIT="/etc/systemd/system/qwen38-image.service" +IMAGE_UNIT_NAME="qwen38-image.service" + +# ── The image lane: a third lane, switched to the same way as the other two ───── +# Same contract as a cross-lane switch: verify the checkpoint, make it the one unit +# enabled at boot, never start or stop anything, print the exact commands. What it +# does NOT share with the text lanes is everything that is about text: there is no +# serving image to inspect (it runs from its own venv), no unit to rewrite (one +# checkpoint), no prompt ceiling on the proxy (the proxy is a text door and nothing +# reaches this lane through it), and no opencode default to move (opencode is a text +# client, and pointing it at an image lane would break every session it opens). So +# it is handled here, whole, and exits, instead of threading "unless image" through +# four hundred lines written for SGLang's text server. +if [ "$CHOICE" = "image" ]; then + [ -f "$IMAGE_UNIT" ] || die "the image lane is not installed on this box (no $IMAGE_UNIT). Install it once: ./install.sh --with-image (38 GB)" + IMG_WD="$(grep -m1 -E '^WorkingDirectory=' "$IMAGE_UNIT" | cut -d= -f2- || true)" + IMG_PY="${IMG_WD:-$HOME/.local/share/qwen38-image}/venv/bin/python" + [ -x "$IMG_PY" ] || die "the image lane's runtime is missing ($IMG_PY): re-run ./install-image.sh, it resumes" + IMG_MODEL="$(grep -oE -- '--model-path [^ ]+' "$IMAGE_UNIT" | head -1 | cut -d' ' -f2 || true)" + IMG_MODEL="${IMG_MODEL:-Qwen/Qwen-Image-2.1}" + IMG_HF="$(grep -m1 -E '^Environment=HF_HOME=' "$IMAGE_UNIT" | cut -d= -f3- || true)" + printf '\n\033[1;36m── Verifying %s in the cache (resumable)\033[0m\n' "$IMG_MODEL" + # The same two lessons the text lanes learned: Xet stalls on this box, and an + # unauthenticated pull gets throttled. local_files_only first, so a complete cache + # answers without touching the network at all. + HF_HOME="${IMG_HF:-$HF_CACHE}" HF_HUB_DOWNLOAD_TIMEOUT=30 HF_HUB_DISABLE_XET=1 IMG_MODEL="$IMG_MODEL" \ + "$IMG_PY" - <<'PYIMG' || die "the image checkpoint could not be verified or fetched (re-run to resume; set HF_TOKEN if it stalls)" +import os +from huggingface_hub import snapshot_download +repo = os.environ["IMG_MODEL"] +try: + print(snapshot_download(repo, local_files_only=True)) +except Exception: + print("not complete in the cache, fetching the rest", flush=True) + print(snapshot_download(repo)) +PYIMG + # The loop variable ends in UNIT_NAME on purpose: CI checks every + # `sudo systemctl "$..UNIT_NAME"` against the cockpit's sudoers allowlist, + # and a variable called $u would have walked straight past it. + for TEXT_UNIT_NAME in qwen38-sglang.service qwen38-flash.service; do + if systemctl is-enabled --quiet "$TEXT_UNIT_NAME" 2>/dev/null; then + echo "disabling $TEXT_UNIT_NAME at boot (unit file kept for switching back)" + sudo systemctl disable "$TEXT_UNIT_NAME" + fi + done + sudo systemctl enable "$IMAGE_UNIT_NAME" >/dev/null 2>&1 || sudo systemctl enable "$IMAGE_UNIT_NAME" + sudo systemctl daemon-reload + RUNNING="" + for u in qwen38-sglang.service qwen38-flash.service; do + systemctl is-active --quiet "$u" 2>/dev/null && RUNNING="$u" + done + printf '\n\033[1;32mSwitch queued: %s (%s)\033[0m\n' "$IMG_MODEL" "$IMAGE_UNIT_NAME" + if [ -n "$RUNNING" ]; then + echo "Effective after: sudo systemctl stop $RUNNING && sudo systemctl start $IMAGE_UNIT_NAME (or next reboot)" + else + echo "Effective after: sudo systemctl start $IMAGE_UNIT_NAME (or next reboot; ready in about 70 s)" + fi + echo "The proxy on :30001 and opencode are text clients and were left as they are." + echo "Switch back: ./switch-model.sh stock (or any text target)" + exit 0 +fi + SGL_UNIT="/etc/systemd/system/qwen38-sglang.service" FLASH_UNIT="/etc/systemd/system/qwen38-flash.service" @@ -331,6 +395,12 @@ if [ -f "$OTHER_UNIT" ] && systemctl is-enabled --quiet "$OTHER_UNIT_NAME" 2>/de echo "disabling $OTHER_UNIT_NAME at boot (unit file kept for switching back)" sudo systemctl disable "$OTHER_UNIT_NAME" fi +# The image lane is the third serving unit. Leaving it enabled while a text lane +# is made the boot lane would bring two engines up at the next reboot. +if [ -f "$IMAGE_UNIT" ] && systemctl is-enabled --quiet "$IMAGE_UNIT_NAME" 2>/dev/null; then + echo "disabling $IMAGE_UNIT_NAME at boot (unit file kept for switching back)" + sudo systemctl disable "$IMAGE_UNIT_NAME" +fi sudo systemctl enable "$TARGET_UNIT_NAME" >/dev/null 2>&1 || sudo systemctl enable "$TARGET_UNIT_NAME" sudo systemctl daemon-reload # 4b) the keepalive proxy's one-prompt ceiling follows the lane (v1.5.6 contract, see @@ -424,6 +494,7 @@ fi RUNNING="" systemctl is-active --quiet "$OTHER_UNIT_NAME" 2>/dev/null && RUNNING="$OTHER_UNIT_NAME" +systemctl is-active --quiet "$IMAGE_UNIT_NAME" 2>/dev/null && RUNNING="$IMAGE_UNIT_NAME" printf '\n\033[1;32mSwitch queued: %s (%s)\033[0m\n' "$TARGET_REPO" "$TARGET_UNIT_NAME" if [ -n "$RUNNING" ]; then echo "Effective after: sudo systemctl stop $RUNNING && sudo systemctl start $TARGET_UNIT_NAME (or next reboot)" @@ -440,7 +511,7 @@ fi echo "Then fit them: python3 oc-fit-limits.py (the limits above are this target's" echo " nominal pair; the pool is only known once the engine is up)" case "$CHOICE" in - stock) echo "Switch back: ./switch-model.sh uncensored (or fp8, flash)" ;; + stock) echo "Switch back: ./switch-model.sh uncensored (or fp8, flash, image)" ;; uncensored) echo "Switch back: ./switch-model.sh stock (or fp8, flash)" ;; fp8) echo "Switch back: ./switch-model.sh stock (or uncensored, uncensored-fp8, flash)" ;; uncensored-fp8) echo "Switch back: ./switch-model.sh fp8 (or stock, uncensored, flash)" ;; diff --git a/tests/test_image_lane.py b/tests/test_image_lane.py index ef89bb43..1b18bcd9 100644 --- a/tests/test_image_lane.py +++ b/tests/test_image_lane.py @@ -196,6 +196,14 @@ class TheInstaller(unittest.TestCase): text = (REPO / "uninstall.sh").read_text() self.assertIn("^WorkingDirectory=", text) + def test_a_serving_image_lane_is_left_serving_by_the_smoke_test(self): + """Re-running the installer on a box whose image lane is serving must not end + with it stopped: the trap used to stop the unit unconditionally on the way out.""" + text = INSTALLER.read_text() + self.assertIn('systemctl is-active --quiet "$UNIT" 2>/dev/null && WAS_IMAGE=1', text) + body = text[text.index("restore_text_lane() {"):text.index("trap restore_text_lane EXIT")] + self.assertIn('[ "$WAS_IMAGE" -eq 1 ] || sudo systemctl stop "$UNIT"', body) + def test_the_smoke_test_proves_a_picture_not_a_status_code(self): """An HTTP 200 from this lane can carry an image of the wrong size, or no image. The install ends by reading the PNG header it got back.""" @@ -235,50 +243,120 @@ class TheOneLinerReachesIt(unittest.TestCase): """It is the only step that stops the engine that is already serving, and the only one that costs 38 GB. A lane that will not install must not take down an install that is otherwise finished.""" - i = self.text.index('"$REPO_DIR/install-image.sh"') - self.assertLess(self.text.index("10/10 Spark Cockpit"), i) + # The normal path's call, the one after a text engine proved itself. The other + # call belongs to the image-is-the-boot-lane exit, which ends before step 9 on + # purpose and is held by AnUpdateKeepsTheImageLaneAsTheBootLane. + cockpit = self.text.index("10/10 Spark Cockpit") + i = self.text.index('"$REPO_DIR/install-image.sh"', cockpit) + self.assertLess(cockpit, i) tail = self.text[i:i + 500] self.assertIn("Everything above is up and serving", tail) + self.assertEqual(self.text.count('"$REPO_DIR/install-image.sh"'), 2, + "one call per path, the normal one and the image-boot one") def test_the_help_says_what_it_costs_before_someone_spends_it(self): self.assertIn("--with-image", self.text) self.assertIn("38 GB", self.text) -class TheLaneIsDrivableFromThePage(unittest.TestCase): - """A cockpit whose Image tab tells you to open a terminal is not a cockpit. Starting - and stopping the lane goes through the same modal, job strip and sudoers allowlist as - every other unit on this box.""" +class AnUpdateKeepsTheImageLaneAsTheBootLane(unittest.TestCase): + """install.sh keeps the operator's choices across a re-run: the target, the context + mode, the port. Once the image lane is a lane, which lane the box boots is one of + those choices. Before this, a box switched to images fell through to "27b", got the + 27B unit enabled beside the image one, and was left with two engines set to start at + the next reboot.""" - def test_the_unit_is_one_the_action_layer_accepts(self): - self.assertIn('"qwen38-image.service"', COCKPIT.read_text()) - text = COCKPIT.read_text() - block = text[text.index("SERVING_UNITS = {"):text.index("UNIT_VERBS = {")] - self.assertIn("qwen38-image.service", block) + def setUp(self): + self.text = (REPO / "install.sh").read_text() - def test_every_verb_it_offers_is_in_the_sudoers_allowlist(self): - """The action layer runs sudo -n: a verb the allowlist does not carry fails with - a password prompt nobody can answer.""" + def test_it_is_detected_where_the_other_two_lanes_are(self): + self.assertIn("systemctl is-enabled --quiet qwen38-image.service", self.text) + self.assertIn('[ "$SGL_ENABLED" -eq 0 ] && [ "$FLASH_ENABLED" -eq 0 ]', self.text) + + def test_the_text_unit_is_not_enabled_on_that_path(self): + i = self.text.index('if [ "$IMAGE_BOOT" -eq 0 ]; then') + self.assertIn('sudo systemctl enable "$UNIT_NAME"', self.text[i:i + 120]) + # and that is the ONLY enable of the serving unit: an unguarded one would undo it + self.assertEqual(self.text.count('sudo systemctl enable "$UNIT_NAME"'), 1) + + def test_that_path_ends_before_any_text_engine_is_started(self): + i = self.text.index('if [ "$IMAGE_BOOT" -eq 0 ]; then') + early = self.text[i:self.text.index("exit 0", i)] + self.assertNotIn("systemctl start", early) + self.assertIn("--no-smoke", early, "the smoke test stops and starts the serving lane") + self.assertLess(i, self.text.index('step "9/10 Starting')) + + +class TheImageLaneIsALaneLikeTheOthers(unittest.TestCase): + """Switched to from the one switcher at the top, started and stopped by the action + bar's lane button, gated by the same "never two engines at once" rule, drawn by the + same Engines card. The first version put a Start button inside the Image tab, which + started the lane by a path none of the other lanes use and, through the unit's + Conflicts=, stopped the text lane silently where the cockpit's rule for every other + lane is to refuse and say "stop it first".""" + + def test_it_is_in_the_switcher(self): + html = INDEX.read_text() + sel = re.search(r'
requesttimepeak memoryresult
768×768, 40 steps22.6 s31.9 GBRGBA
1024×1024, 40 steps (the defaults)38.2 s34.8 GBRGBA
1664×928, 40 steps60.4 s34.8 GBRGBA
2048×2048, 40 steps (the model card's own size)190.9 s44.7 GBRGBA
2752×1536, 40 steps (16:9 at the card's base)193.1 s44.8 GBRGBA
1024×1024, 8 / 20 / 60 steps8.4 / 19.8 / 57.3 s31.9 GB8 steps is visibly unfinished
transparent 1024×102439.8 s34.8 GB68% of pixels fully transparent
edit, one reference, 40 steps44.6 s34.8 GBalpha preserved from the reference