diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ba86f67..bd8f2388 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -759,13 +759,14 @@ jobs: # 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 two: `image`, installed by --with-image, and - # `video`, installed by --with-video, each switched to like any other, - # and neither an LLM checkpoint (neither has a recipe, a KV pool - # nor an 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", "video"] + # builds a recipe for. The SWITCH targets are those plus the targets of the + # lanes a flag installs: `image` and its Turbo `image-turbo`, the lane + # --with-image installs, and `video`, installed by --with-video, each + # switched to like any other, and none an LLM checkpoint (none has a + # recipe, a KV pool nor an opencode default). Both sets are asserted, so a + # target added to the switcher and forgotten in the cockpit's enum is + # still caught. + FLAG_LANES = ["image", "image-turbo", "video"] ref = choices switch_ref = sorted(ref + FLAG_LANES) text_lists = {"install.sh MODEL_CHOICE": choices, "recipes BUILTIN_IDS": sorted(builtins)} @@ -1295,7 +1296,7 @@ jobs: script = pathlib.Path("switch-model.sh").read_text() alw = pathlib.Path("dashboard/sudoers-cockpit.template").read_text() allowed = {m.strip() for m in re.findall(r"NOPASSWD:\s*(.+)$", alw, re.M)} - stage = dict(re.findall(r'^(STAGE_UNIT|STAGE_CEIL)="\$CONFIG_DIR/([^"]+)"', script, re.M)) + stage = dict(re.findall(r'^(STAGE_UNIT|STAGE_CEIL|IMG_STAGE)="\$CONFIG_DIR/([^"]+)"', script, re.M)) units = {"qwen38-sglang.service", "qwen38-flash.service"} engines = units | {"qwen38-image.service", "qwen38-video.service"} values = { @@ -1303,8 +1304,10 @@ jobs: "IMAGE_UNIT_NAME": {"qwen38-image.service"}, "VIDEO_UNIT_NAME": {"qwen38-video.service"}, "TARGET_UNIT": {re.search(r'^SGL_UNIT="([^"]+)"', script, re.M).group(1)}, + "IMAGE_UNIT": {re.search(r'^IMAGE_UNIT="([^"]+)"', script, re.M).group(1)}, "STAGE_UNIT": {"__HOME__/.config/qwen38/" + stage["STAGE_UNIT"]}, "STAGE_CEIL": {"__HOME__/.config/qwen38/" + stage["STAGE_CEIL"]}, + "IMG_STAGE": {"__HOME__/.config/qwen38/" + stage["IMG_STAGE"]}, } seen, bad = 0, [] for raw in script.splitlines(): @@ -1357,7 +1360,8 @@ jobs: print("\n".join(" " + b for b in bad)); sys.exit(1) sw = pathlib.Path("switch-model.sh").read_text() for var, tail in (("STAGE_UNIT", "qwen38-sglang.service.switch-stage"), - ("STAGE_CEIL", "keepalive-ceiling.conf.switch-stage")): + ("STAGE_CEIL", "keepalive-ceiling.conf.switch-stage"), + ("IMG_STAGE", "qwen38-image.service.switch-stage")): m = re.search(rf'^{var}="\$CONFIG_DIR/([^"]+)"', sw, re.M) if not m or not m.group(1).endswith(tail): print(f"{var} staging path changed or missing in switch-model.sh"); sys.exit(1) @@ -1435,6 +1439,10 @@ jobs: m = re.search(r'\bMODEL="\$\{MODEL:-([^}]+)\}"', pathlib.Path("install-video.sh").read_text()) if not m or m.group(1) not in un.split('HF_REPOS="', 1)[-1].split('"', 1)[0].split(): bad.append("install-video.sh MODEL") + # and the image lane's second checkpoint, the Turbo of ./switch-model.sh image-turbo + m = re.search(r'^IMAGE_TURBO_PIN="([^"]+)"', pathlib.Path("install-image.sh").read_text(), re.M) + if not m or m.group(1) not in un.split('HF_REPOS="', 1)[-1].split('"', 1)[0].split(): + bad.append("install-image.sh IMAGE_TURBO_PIN") if bad: print("install.sh pins missing from uninstall.sh inventory:") print("\n".join(" " + b for b in bad)); sys.exit(1) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a62e1bb..8d7f948b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,175 @@ # Changelog +## v1.24.0 (2026-10-10): the image lane moves to SGLang v0.5.21 and gains Qwen-Image 2.1 Turbo, a 1024x1024 image in 7.5 s + +**Qwen-Image 2.1 Turbo, a second checkpoint of the image lane.** Qwen published +[Qwen-Image-2.1-Turbo](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo) on 2026-10-09, an +eight-step distillation of the lane's model under the same Qwen Research licence, and SGLang +merged its support on 2026-10-10 +([sgl-project/sglang#43391](https://github.com/sgl-project/sglang/pull/43391)). The Lanes view +offers it next to the base as `Qwen-Image 2.1 Turbo`, and `./switch-model.sh image-turbo` from +a terminal: the switch fetches it at its pinned revision (`d65dbc9a7e8f`, 32.5 GB on the first +switch), points the unit's `--model-path` at it and changes nothing else, and +`./switch-model.sh image` goes back. The base stays the default. Under the Turbo the Image view +shows its eight steps as fixed by the checkpoint, leaves `num_inference_steps` out of the +request as the cookbook says, and counts eight steps in its estimate. + +Measured on the reference box, both checkpoints on the same runtime, seed 42, medians: 1024x1024 +in **7.5 s** against 34.3 s for the base at its 40 steps (the calibration medians, four and +three runs; all eighteen and fifteen requests of the day at that size give 7.5 and 34.4 s), +512x512 in 1.8 against 7.8 s, 2048x2048 in 40.6 against 182.8 s, an edit with one reference in 10.3 against +41.9 s, at the same peak memory (35.6 GB at 1024x1024, 46.6 GB at 2752x1536). Same seed twice +gives the same bytes, and `num_inference_steps: 2` gives the same PNG as leaving it out: the +checkpoint's grid sets the steps. On eight prompts with one seed each (a photograph, a portrait, +a shop sign with French text and prices, a counting prompt, a landscape, a watercolour, an +interior, an infographic) the Turbo is close to the base at 40 steps on the photographs, the +portrait, the illustrations and the short text (`Boulangerie Margot`, `Croissant 2,10 €` and +`Baguette 1,30 €` exact in both); both miscount the fruit, and both garble the infographic's +body text, the Turbo with invented English words, the base with invented Chinese-looking +characters under four numbered steps. The base at eight steps is visibly unfinished on every +prompt. Transparency, asked for by the prompt as for the base: 70.9 % of the Turbo's pixels +under alpha 16, 74.3 % of the base's, same prompt and seed. Compared file by file, the Turbo's +transformer is the distilled one, its text encoder is the base's (all 750 tensors identical, +saved as one file), and its VAE is the base's in bf16. + +**The lane moves to the v0.5.21 release.** Qwen-Image 2.1 arrived in a release with `v0.5.21`, +and the lane now runs that release's commit (`e00930c54890`) with its wheel, instead of the +`main` commit `ddebc52f237a` and the `0.5.20` wheel it ran since 2026-09-22. The base's images +do not change: the same twelve requests gave the same bytes on both runtimes, and the new one +is 4.7 % faster at 1024x1024 (34.40 s against 36.08 s, median of three on each, the same +morning), for 0.8 GB more at the peak. The Turbo's grid needs #43391, which is in no release +yet: its runtime part, 19 lines in three files, is backported as three local patches beside the +lane's two (the idle loop, the 5 s stop), one file each, each checked by CI against the real +files at the pin; the PR's own 58 upstream tests pass on the backport. `install-image.sh` +refuses to serve the Turbo on a runtime they did not reach, and `switch-model.sh image-turbo` +refuses to switch to it. Both ask the same check, `image-sglang/turbo-grid-check.py`, which +checks the three parts one by one, the config by what it does with a grid and the pipeline and +the input stage by the code that carries it: a patch that does not apply to a new pin is only a +note in the installer, and a runtime with the config's field and not the rest would still +sample on a uniform schedule. + +**An existing venv takes the new wheel.** `install-image.sh` installed the wheel only when +`sglang` did not import, so a pin that moved to a new release would have kept the previous +release's dependencies under the new source (here `cache-dit` 1.3.0 under v0.5.21, which asks +for 1.5.1). The installer now writes down the wheel a venv came from (`sglang-wheel` in the +lane's folder, removed by `--uninstall`) and installs the new one over a venv that has another +or no note. On the reference box the update from v1.23.0 took the new wheel's changes +(`cache-dit` 1.5.1, `xgrammar` 0.2.7, `sentencepiece` 0.2.1; torch, the kernels and diffusers +unchanged), checked out the release and applied the five patches in under a minute. + +**The runtime check asks the registry.** The installer's check that the runtime knows +Qwen-Image 2.1 read the registry's source text, and v0.5.21 registers the model from its +pipeline config: that first update on the reference box stopped there, on a runtime that serves +the model. The check now asks the registry whether the exact id maps to Qwen-Image 2.1's own +config; a fuzzy match would also have taken an unknown `Qwen/Qwen-Image-9.9` for an older +Qwen-Image. None of the installer's checks is an `assert` any more: `python -O`, or +`PYTHONOPTIMIZE` in the environment, strips those, and the check then passes whatever it checks. + +**A first install does not trip on a patch merged upstream.** Before checking out a new pin, +the image and video installers take their patches off the source tree by reversing them. A first +install's clone stands on upstream's main, which carries #43391 since 2026-10-10: two of the +Turbo's patches reversed cleanly there, wrote edits, and the checkout of the pin refused to go +over them, so with this version's patches a first install of the image lane died at step 3 +(found before release, by replaying the installer on a fresh venv; v1.23.0's two patches are +not merged upstream, so its first installs were not affected). A patch is now taken off only +from a file that has local edits, in both installers. + +**The image switch fetches the revision the box serves.** `./switch-model.sh image` fetched a +checkpoint that was not complete with no revision, which resolves upstream's tip and, since the +unit runs offline by name, would then have served a push upstream instead of the pin. It now +reads the revision as the video switch does: the checkpoint's `refs/main`, which the offline +unit resolves, so one an install made with `IMAGE_MODEL_REV=` stays served; the installer's +pin when there is no ref, with `refs/main` then pointed at it; never a move of a valid ref. +Room is checked before the first byte: about 34 GB, less what the cache already holds of that +checkpoint. + +**A checkpoint of the unit's own survives the Turbo.** A unit installed with `IMAGE_MODEL=` +serves a checkpoint that is neither the base nor the Turbo; `image-turbo` and back gave the base. +The switch to the Turbo now writes that checkpoint down (`~/.config/qwen38/image-model-before-turbo`) +and `./switch-model.sh image` brings it back. An install that points the unit at another +checkpoint drops the note, and `install-image.sh --uninstall` removes it and names every +checkpoint of the lane the cache holds, the one the note named included, not only the unit's. + +**The page follows what the engine serves.** The unit's file says what the lane's next start +loads, and a switch from a terminal rewrites it under a serving engine, which goes on serving +what it loaded. The cockpit now asks the image engine itself (`/model_info`, once per life of +the unit) and the page goes by its answer: the request, the steps and the estimate are those +of the checkpoint served, Load offers the restart a switch still owes, and the banner the text +lanes have says so; a Load that only points the unit back at what the engine serves restarts +nothing. A Load that restarts the image lane on its other checkpoint warns that a generation in +flight is lost, as a stop did. The Now view's time for a 1024x1024 image follows +the checkpoint (about 34 s or 7.5 s; it said 38 s), the sample reference leaves the steps to +the Turbo's grid like any request, Reset names the Turbo's 8 steps, and the switch's +explanation says what it rewrites for each lane. + +**The estimate and the peak follow the new runtime.** The Image view's estimate was fitted on +the commit before at 40 steps only (`1 + steps x 0.97 x px^1.14`), and on the new runtime it is +up to 43 % high (the Turbo at 512x512). It is now `0.42 + 0.25 x px^2.08 + steps x 0.883 x +px^1.16` seconds (`px` the pixels over 1024^2), a part per image (text encoding, VAE decode) and +a part per step, fitted to the medians of both checkpoints at six sizes from 512x512 to +2752x1536 and within 4.9 % of all twelve; an edit adds `1.6 + 0.15 x steps` seconds per +reference. The largest call admitted (one 2752x1536 image) peaks at 46.6 GB on the new runtime +against 44.8 on the old one, and the page and the refusal say so. + +**A comment put right.** Two comments of `install.sh` said that opencode's static 1M pair +(700,000 + 200,000) can meet a proxy 400 late in a session. The proxy refuses a prompt past 92 % +of the pool, and the largest prompt opencode sends with that pair, its compaction point plus one +worst agent step (680,000 + 43,863 = 723,863), stays under it on every pool the lane booted to +(832,993 the least). What does not fit is that prompt plus a whole answer, one past about +109,000 tokens at the very end of a full session, and the fit that runs after every boot +replaces the pair anyway. Behaviour unchanged. + +**Said as it is.** `docs/video-lane.md` said the two diffusion lanes serve the same SGLang +commit; from this version they do not, and it says what holds either way (the idle patch's loop +is the same at both pins, which CI checks). `ROADMAP.md` stopped at "current: v1.20" and lists +v1.21 to v1.24 now, and `docs/flash-lane.md` named a maintainer's private note as the source of +a measurement instead of its date. `docs/image-lane.md`, the README and the unit's comment give +the peaks, run counts and ratios of the new runtime (35.6 GB at 1024x1024 and 46.5 GB at +2048x2048, about five and a third times the time for four times the pixels), and `MIRROR.md` +counts the twelve checkpoint pins at 1,077 GB from the Hub's file sizes (it said ten, 546 GB: +MiniMax-H3, 498.5 GB whole, and the Turbo were missing from the sum). `install-video.sh` no +longer says its pin is the image lane's. + +**Tests.** The switch's own image block runs in a sandbox (fake unit, cache, hub and runtime; +sudo and systemctl stubs): the rewrite touches `--model-path` alone, the Turbo is fetched at its +pin with `refs/main` on it, a runtime without the grid is refused before anything changes, the +way back leaves no `-Turbo` behind, a custom checkpoint is kept and survives a round trip +through the Turbo, the served `refs/main` is kept and a ref with no commit repaired, the room +check counts what the cache holds, the ref is read in the unit's own cache, a runtime missing +any one of the three parts or with the config's field and not its behaviour is refused, and the +restart hint is given only for a rewrite (24 tests; mutants taking out the grid check, its +behavioural part, `refs/main`, the unit's cache, the room check, the note's cleanup, the +rewrite's flag and the hint's condition, each caught). The +grid check itself ran on a real runtime with each of the three patches taken off in turn: each +time refused, with the part that was missing. The page: the target is a variant of the image lane with a name of its own, +loaded by a switch and a restart from the base or by a switch, a stop and a start from a text +lane; under the Turbo the request has no step count, the slider shows 8 and is disabled, the +estimate counts eight; the base keeps its slider; the view's Load loads the checkpoint the unit +names, the engine's own answer wins over the unit's when they differ and owes no restart when +it already serves the checkpoint asked for, and the Now view and the switch's explanation say +what is true of each checkpoint and lane (18 tests); the cockpit asks the engine once per life +of the unit (4 tests); the uninstall names the noted checkpoint, and an install for another +checkpoint drops the note (3 tests). And: the three patches touch one file each and add what #43391 adds, the +replayed patch block applies all five, the cockpit reads the Turbo from the unit, the estimate +holds the new measurements within 10 %, `check-pins.sh` and `mirror-pins.sh` cover the Turbo, +and CI's gates know its sudoers line, its staging path and its inventory entry; a fresh clone +whose main carries one of the patches checks out the pin. Each test of a change fails on +v1.23.0 or on this branch before its review fixes; the ones that hold what must not change (the +base's slider, a lane serving what its unit names) pass on both. +A first install's runtime was replayed on a fresh venv with the installer's own step 3 (the +whole 0.5.21 wheel, the clone, the pin, the five patches, the registry and Turbo checks): 201 s, +8.1 GB, the wheel's exact dependencies. On the reference box, with the branch: the update of the prod +image lane from v1.23.0 (smoke test, 0.05 CPU cores at rest), the switch to the Turbo and back, +a generation through the branch's cockpit in both modes (7.6 and 34.8 s), and a Stop 6 s into a +2048x2048 generation, stopped in 5.26 s with `Result=success`. + +**What an update does.** `install.sh` updates the image lane in place without starting it (the +new wheel's changes, the release's checkout and the five patches, under a minute on the +reference box); its next start runs the new runtime. Nothing is downloaded for the Turbo until a +switch to it. The cockpit restarts for its new Image view and Lanes card, and its sudoers file +gains the one line the Turbo's switch needs. The text engines, the proxy and the video lane keep +running. + ## v1.23.0 (2026-10-10): the 27B lane moves to SGLang v0.5.21, whose prefix cache no longer resumes a conversation from a stale state The 27B lane serves `lmsysorg/sglang@sha256:b1259f3e...` (`v0.5.21`, 2026-10-01) instead of diff --git a/MIRROR.md b/MIRROR.md index cafd0326..00337ac5 100644 --- a/MIRROR.md +++ b/MIRROR.md @@ -31,6 +31,7 @@ happens to exist. | draft | RadixArk/Qwen3.8-27B-DSpark | not yet checked | | draft2 | maurienne-ai/Qwen3.8-27B-DFlash2-NVFP4-RTNcal | not yet checked: verify both layers | | qwen-image | Qwen/Qwen-Image-2.1 | not yet checked | +| qwen-image-turbo | Qwen/Qwen-Image-2.1-Turbo | not yet checked: same Qwen Research licence as the base | | minimax-h3 | MiniMaxAI/MiniMax-H3 | not yet checked: own licence, read it before any redistribution | | images (2) | lmsysorg/sglang@sha256:... | copied whole by digest: the Apache-2.0 SGLang images carry their license inside; keep it there | @@ -77,9 +78,11 @@ so an install pinned to the index digest would not find it on the mirror. The script copies the index whole with `docker buildx imagetools create`, then asks the mirror for the pinned digest and fails when it does not answer it. -Cost honesty: the ten checkpoint pins are 546 GB at their pinned revisions -(measured 2026-09-24: 106 GB for the four 27B checkpoints, 403 GB for the -three flash ones, 4 GB for the two drafters, 33 GB for Qwen-Image), downloaded and uploaded again +Cost honesty: the twelve checkpoint pins are 1,077 GB at their pinned revisions +(the Hub's file sizes, read 2026-10-10: 106 GB for the four 27B checkpoints, 403 GB for +the three flash ones, 4 GB for the two drafters, 33 GB for Qwen-Image and 32.5 GB for its +Turbo, 498.5 GB for MiniMax-H3 whole, both partitions and its native layout, where the +video lane itself fetches only the 144 GB FL2VA one), downloaded and uploaded again from whatever machine runs this, once to seed and once per re-pin. A cheap cloud box with fast egress does the seeding in hours instead of days, and the plan above is what you hand it. diff --git a/README.md b/README.md index 72ce7e1e..22454580 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ curl -fsSL https://raw.githubusercontent.com/hasso5703/dgx-spark-qwen38/main/get - **Text**: Qwen3.8 27B at 71.4 tok/s with a 1M context by default, and Qwen3.8-Flash-Next 176B on the same box, seven switchable targets, an OpenAI- and Anthropic-compatible API. -- **Images**: Qwen-Image 2.1, a 1024×1024 image in about 38 s. +- **Images**: Qwen-Image 2.1, a 1024×1024 image in about 34 s, or 7.5 s with its eight-step Turbo. - **Video with sound**: MiniMax-H3, a 4 s clip at 480p with its audio in 10 to 13 minutes. - **Agents**: opencode wired to the local model, in a terminal or in the cockpit's Agent view, from a laptop or a phone. @@ -311,16 +311,21 @@ curl -fsSL https://raw.githubusercontent.com/hasso5703/dgx-spark-qwen38/main/get Then it is a third lane, driven like the other two: on the cockpit's Lanes view, pick **Qwen-Image 2.1** and press **Load**: one action that switches the boot, stops the serving lane and starts this one (about a minute to answer). From a terminal, -`./switch-model.sh image` does the switch and prints the rest. +`./switch-model.sh image` does the switch and prints the rest. **Qwen-Image 2.1 Turbo**, Qwen's +eight-step distillation of the same model, is a second checkpoint of the lane, loaded the same +way (`./switch-model.sh image-turbo`, 32.5 GB on its first switch): about four and a half times +faster, close to the base on photographs, portraits, illustrations and short text +([docs/image-lane.md](docs/image-lane.md#the-turbo-checkpoint) shows where it is not). 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, -and a transparent generation that comes back with 68% of its pixels genuinely transparent. Same -seed twice is byte-identical. +**Measured on a Spark, not copied from the cookbook** (SGLang v0.5.21, 2026-10-10): +1024x1024 at 40 steps in **34.3 s** (35.6 GB peak), **7.5 s with the Turbo**, 512x512 in 7.8 s +(1.8 s), 2048x2048 in 182.8 s (40.6 s), an edit with one reference in 41.9 s (10.3 s), and a +transparent generation that comes back with about three quarters of its pixels transparent. +Same seed twice is byte-identical. Three things bite before a client does: **width and height must be multiples of 32** (anything else is a bare HTTP 500), **an output format must always be sent** (left out, the API falls back diff --git a/ROADMAP.md b/ROADMAP.md index 162eef67..32ebd826 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,7 +5,35 @@ so that "on the roadmap" means a checkbox with a definition of done, not a mood. Statuses: shipped, in progress, planned, considered (considered items have a reason they are not yet planned, stated here or in an issue). -## Shipped, current: v1.20 +## Shipped, current: v1.24 + +- **Qwen-Image 2.1 Turbo, and the image lane on a release** (v1.24.0): Qwen's eight-step + distillation as a second checkpoint of the image lane (a 1024x1024 image in 7.5 s against + 34.3 s), loaded like any target; the lane runs the v0.5.21 release with the Turbo's sigma + grid backported, the base's images unchanged byte for byte. + +## Shipped, v1.23 + +- **The 27B lane on SGLang v0.5.21** (v1.23.0), whose prefix cache no longer resumes a + conversation from a stale linear state (sgl-project/sglang#37817, fixed by #37818). + +## Shipped, v1.22 + +- **pi and omp configs** (v1.22.0), generated from the opencode artifact. +- **The proxy hardened** (v1.22.1 to v1.22.14): a stream the engine has not started kept + open and its caller watched, the engine key masked in every `/server_info`, the key + checked before a body is read, the prompts that could wedge the 27B counted, and the + engine's facts dropped at once when a lane switches. +- **The cockpit says what the engine says** (v1.22.3 to v1.22.12): download progress with + bytes, rate and time left, the last 5 minutes of traffic from the engine's own counters. +- **An idle video lane holds no CPU core** (v1.22.10). + +## Shipped, v1.21 + +- **An engine restart no longer ends a session** (v1.21.0), and no engine starts on memory + a dead one still holds. + +## Shipped, v1.20 - **Every lane by default** (v1.20.0): the one-liner installs both text lanes (the 27B serves, Flash-Next 176B beside it), the image lane and the video lane, each proved diff --git a/check-pins.sh b/check-pins.sh index 6a9d72be..30784aee 100755 --- a/check-pins.sh +++ b/check-pins.sh @@ -46,7 +46,7 @@ eval "$pins" # or a commit removed upstream went unseen (found in review, 2026-09-24). more="$(grep -E '^(OPENCODE_VERSION|OPENCODE_SHA256)=' "$REPO_DIR/install.sh")" eval "$more" -lane="$(grep -E '^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV|PIN|WHEEL)=' "$REPO_DIR/install-image.sh")" +lane="$(grep -E '^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV|IMAGE_TURBO_PIN|IMAGE_TURBO_PIN_REV|PIN|WHEEL)=' "$REPO_DIR/install-image.sh")" eval "$lane" IMAGE_PIN="$PIN"; IMAGE_WHEEL="$WHEEL" vline="$(grep -E '^(VIDEO_MODEL_PIN|VIDEO_MODEL_PIN_REV|PIN|WHEEL)=' "$REPO_DIR/install-video.sh")" @@ -212,6 +212,7 @@ check_model dspark-draft "$DRAFT_REPO" "$DRAFT_REV" echo "Image lane and opencode" check_model qwen-image "$IMAGE_MODEL_PIN" "$IMAGE_MODEL_PIN_REV" model_index.json +check_model qwen-image-turbo "$IMAGE_TURBO_PIN" "$IMAGE_TURBO_PIN_REV" model_index.json check_commit sglang-source sgl-project/sglang "$IMAGE_PIN" check_wheel sglang-wheel sglang "$IMAGE_WHEEL" echo "Video lane" diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index 7f68e247..79e48813 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -1273,11 +1273,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 + # the model is read from the unit, so a lane installed with IMAGE_MODEL= reports + # what it really serves; the Turbo is its own target (./switch-model.sh image-turbo) 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} + target = ("image-turbo" if model == IMAGE_TURBO_MODEL else "image") if model else None + return {"model": model, "target": target} if unit == "qwen38-video.service": # one checkpoint, one target, same rule as the image lane model = _video_unit_flag("--model-path", "MiniMaxAI/MiniMax-H3") \ @@ -1641,8 +1642,12 @@ def collect_lifecycle(): eta = lc.eta_for(history, unit) overdue = bool(eta and elapsed and st["state"] in lc.TRANSITIONAL and elapsed > 2 * eta) + # the image engine's own answer to which checkpoint it serves (the unit's file says + # what the NEXT start loads), read once per life of the unit + served = image_served_model(enter_key) if is_image and st["state"] in ("ready", "degraded") else None engines[unit] = {"state": st["state"], **unit_target(unit), + "served_target": ("image-turbo" if served == IMAGE_TURBO_MODEL else "image") if served else None, "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 @@ -1819,7 +1824,8 @@ ACTIONS = { "switch": { "danger": "medium", "params": {"target": ["stock", "uncensored", "fp8", "uncensored-fp8", - "flash", "flash-nvda", "flash-uncensored", "image", "video"]}, + "flash", "flash-nvda", "flash-uncensored", "image", "image-turbo", + "video"]}, "argv": lambda p: ["bash", str(REPO_DIR / "switch-model.sh"), p["target"]], # A switch can download a whole checkpoint: 124 GB for flash take about 23 min at # the 89 MB/s the reference box gets, so 30 min failed it on any slower link, and @@ -2164,6 +2170,9 @@ def systemone_call(payload: dict) -> tuple[int, dict]: # to the lane: it sends a description of the call and this process makes it. IMAGE_UNIT = "qwen38-image.service" IMAGE_UNIT_PATH = Path("/etc/systemd/system/qwen38-image.service") +# The lane's second checkpoint (install-image.sh IMAGE_TURBO_PIN): eight steps fixed by +# the sigma grid in its model_index.json, whatever num_inference_steps a request sends. +IMAGE_TURBO_MODEL = "Qwen/Qwen-Image-2.1-Turbo" # Ten references at the size the browser caps them to, base64 and JSON-escaped, plus the # fields. Everything else on this server stays at the 64 KiB cap. IMAGE_MAX_POST = 40 * 1024 * 1024 @@ -2181,7 +2190,8 @@ IMAGE_LOCK = threading.Lock() # 42 s per denoising step on 2026-09-23 where one takes 4.6, and the memory a batch needs # grows with it. On this box's unified memory running out hangs the machine rather than # failing the request, so a call may not ask for more pixels, all its images together, -# than the largest call measured here: one 2752x1536 image, 44.8 GB at its peak. +# than the largest call measured here: one 2752x1536 image, 46.6 GB at its peak (on the +# v0.5.21 runtime and both checkpoints, 2026-10-10; 44.8 GB on the commit before it). IMAGE_MAX_PIXELS = 2752 * 1536 # How often a call this process gave up on is looked for in the lane's journal (M5 below). IMAGE_END_POLL_S = 5.0 @@ -2233,6 +2243,31 @@ def image_base() -> str: return os.environ.get("COCKPIT_IMAGE", f"http://{host}:{image_port()}") +# What the image engine says it serves, from its own /model_info: ./switch-model.sh run from +# a terminal rewrites the unit under a serving engine, which goes on serving the checkpoint +# it loaded, and the page then sent a Turbo's request to the base and offered no restart +# (found in review, 2026-10-10). Read once per life of the unit (systemd's +# ActiveEnterTimestampMonotonic), retried every 10 s until it answers. +IMAGE_SERVED = {"life": None, "model": None, "asked": 0.0} + + +def image_served_model(life: str): + """The --model-path this life of the image engine was started with, or None until it says.""" + if IMAGE_SERVED["life"] != life: + IMAGE_SERVED.update(life=life, model=None, asked=0.0) + if IMAGE_SERVED["model"] or time.monotonic() - IMAGE_SERVED["asked"] < 10: + return IMAGE_SERVED["model"] + IMAGE_SERVED["asked"] = time.monotonic() + try: + with urllib.request.urlopen(urllib.request.Request(image_base() + "/model_info"), timeout=1) as r: + model = json.loads(r.read(65536) or b"{}").get("model_path") + except Exception: # noqa: BLE001 (an engine still loading answers nothing useful) + return None + if isinstance(model, str) and model: + IMAGE_SERVED["model"] = model + return IMAGE_SERVED["model"] + + IMAGE_JOURNAL_LINES = 300 @@ -2543,7 +2578,7 @@ def image_call(payload: dict, editing: bool) -> tuple[int, dict]: if n * w * h > IMAGE_MAX_PIXELS: return 400, {"error": f"{n} image{'s' if n > 1 else ''} of {w}x{h} in one call is " f"{n * w * h / 1e6:.1f} megapixels, and the largest call measured on this " - f"box is {IMAGE_MAX_PIXELS / 1e6:.1f}: one 2752x1536 image, 44.8 GB at its " + f"box is {IMAGE_MAX_PIXELS / 1e6:.1f}: one 2752x1536 image, 46.6 GB at its " f"peak. The images of a call are generated as one batch, so its memory grows " f"with their total size, and on unified memory running out hangs the machine " f"instead of failing the request. Ask for fewer or smaller images, or make " diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 0acaaa39..f7473ed2 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -356,7 +356,7 @@
-
Steps model default 40 +
Steps model default 40
40
1, fast draft100, slow
Images per call diff --git a/dashboard/static/js/base.js b/dashboard/static/js/base.js index b94831dc..bcef190a 100644 --- a/dashboard/static/js/base.js +++ b/dashboard/static/js/base.js @@ -103,13 +103,13 @@ const LANE_META = { // median of its own boots replaces these. const READY_DEFAULT = {[U27]: 540, [UFLASH]: 780, [IMAGE_UNIT]: 70, [VIDEO_UNIT]: 720}; const TARGET_SHORT = {stock: 'stock', uncensored: 'uncensored', fp8: 'FP8', 'uncensored-fp8': 'FP8 uncensored', - flash: '', 'flash-uncensored': 'uncensored', 'flash-nvda': 'NVIDIA export', image: '2.1', video: 'H3'}; -const TARGET_UNIT = t => t === 'image' ? IMAGE_UNIT : t === 'video' ? VIDEO_UNIT : String(t).startsWith('flash') ? UFLASH : U27; + flash: '', 'flash-uncensored': 'uncensored', 'flash-nvda': 'NVIDIA export', image: '2.1', 'image-turbo': 'Turbo', video: 'H3'}; +const TARGET_UNIT = t => t === 'image' || t === 'image-turbo' ? IMAGE_UNIT : t === 'video' ? VIDEO_UNIT : String(t).startsWith('flash') ? UFLASH : U27; const LANE_TARGETS = {[U27]: ['stock', 'uncensored', 'fp8', 'uncensored-fp8'], [UFLASH]: ['flash', 'flash-uncensored', 'flash-nvda'], - [IMAGE_UNIT]: ['image'], [VIDEO_UNIT]: ['video']}; + [IMAGE_UNIT]: ['image', 'image-turbo'], [VIDEO_UNIT]: ['video']}; const TARGET_NAME = {stock: '27B stock, NVFP4', uncensored: '27B uncensored, NVFP4', fp8: '27B FP8, Qwen official', 'uncensored-fp8': '27B FP8 uncensored', flash: 'flash 176B, NVFP4', 'flash-uncensored': 'flash 176B uncensored', - 'flash-nvda': 'flash 176B, NVIDIA export', image: 'Qwen-Image 2.1', video: 'MiniMax-H3'}; + 'flash-nvda': 'flash 176B, NVIDIA export', image: 'Qwen-Image 2.1', 'image-turbo': 'Qwen-Image 2.1 Turbo', video: 'MiniMax-H3'}; const TARGET_NOTE = { stock: 'The NVFP4 quantization this repo pins by default: smallest and fastest of the 27B targets.', uncensored: 'The abliterated NVFP4 checkpoint: same size and speed as stock, refusals removed.', @@ -119,6 +119,7 @@ const TARGET_NOTE = { 'flash-uncensored': 'The abliterated build of the same 176B tree, byte-identical in layout, so every serving flag is the same. The first switch downloads about 126 GB.', 'flash-nvda': 'NVIDIA’s own mixed-precision export of the same model, served with a pinned MoE runner. The first switch downloads about 124 GB.', image: 'Text to image, editing with up to ten references, native RGBA. 31 GB of weights that do not fit beside a text lane.', + 'image-turbo': 'Qwen’s eight-step distillation of the same model, for the same three uses: a 1024 × 1024 image in 7.5 s against 34 s, at the same memory, the eight steps fixed by the checkpoint. The first switch downloads about 33 GB.', video: 'Text to video with joint audio, plus first and last frame conditioning. The checkpoint does not fit beside a text lane.'}; // What installs a lane this box does not have. Since v1.20 a plain ./install.sh installs // every lane, so one missing here was left out (--no-) or did not fit: --with- @@ -158,10 +159,13 @@ const readyIn = unit => 'about ' + fmtDur(bootSeconds(unit)); const ownTarget = unit => F.target && TARGET_UNIT(F.target) === unit ? F.target : null; // What the serving engine itself says it serves, only from a read taken after this engine // started: the read comes every 30 s and is kept through a restart, so for up to 30 s after -// one it still names the previous engine's checkpoint. null when there is no such read. +// one it still names the previous engine's checkpoint. The image engine's answer is read by +// the cockpit once per life of its unit, so it is never the previous one's. null when there +// is no such read. function servedTarget(unit){ const s = servingEngine(), age = lastAges.engine_info; - if (!s || s[0] !== unit || unit === IMAGE_UNIT || unit === VIDEO_UNIT) return null; + if (!s || s[0] !== unit || unit === VIDEO_UNIT) return null; + if (unit === IMAGE_UNIT) return s[1].served_target || null; return s[1].elapsed != null && age != null && age < s[1].elapsed ? ownTarget(unit) : null; } function laneTarget(unit){ @@ -385,7 +389,8 @@ const EXPLAIN = { return `systemd starts ${lane}: it loads its weights and answers in ${readyIn(p.unit)}. Follow the boot in the dock and on the Now view.`; }, switch: p => (TARGET_NOTE[p.target] ? TARGET_NOTE[p.target] + '\n\n' : '') + - 'switch-model.sh verifies the checkpoint, makes this lane the one enabled at boot and, for a text target, rewrites its unit, the proxy ceiling and the opencode default model. It never restarts anything.', + `switch-model.sh verifies the checkpoint, makes this lane the one enabled at boot and ${TARGET_UNIT(p.target) === VIDEO_UNIT ? 'changes nothing else' + : TARGET_UNIT(p.target) === IMAGE_UNIT ? 'points its unit at this checkpoint' : 'rewrites its unit, the proxy ceiling and the opencode default model'}. It never restarts anything.`, flush_cache: () => 'Empties the radix cache. Harmless; the engine refuses it while requests run.', 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.', @@ -474,9 +479,14 @@ function laneJourneySteps(target){ // next start loads, and the restart is still owed. Read against the unit's file alone, the // journey had no step left and said "already serving" of a checkpoint that was not // (found 2026-10-05: flash served while its unit pointed at flash-uncensored). - const owed = !!(servedTarget(unit) && servedTarget(unit) !== target); - if (serving && serving[0] === unit && (steps.length || owed)) - steps.push({name: 'unit', params: {verb: 'restart', unit}, title: `Restart ${LANE_NAME[unit]} on the new checkpoint`, desc: `It answers again in ${readyIn(unit)}.`}); + const served = servedTarget(unit), owed = !!(served && served !== target); + // The image engine says what it serves (cockpit.py, once per life of its unit): a switch + // that only points the unit at the checkpoint it already serves owes no restart, which + // would end a generation for nothing. + const restart = unit === IMAGE_UNIT && served ? owed : steps.length || owed; + if (serving && serving[0] === unit && restart) + steps.push({name: 'unit', params: {verb: 'restart', unit}, title: `Restart ${LANE_NAME[unit]} on the new checkpoint`, + desc: `It answers again in ${readyIn(unit)}.` + (unit === IMAGE_UNIT || unit === VIDEO_UNIT ? ' A generation in flight is lost.' : '')}); else if (!serving || serving[0] !== unit) steps.push({name: 'unit', params: {verb: 'start', unit}, title: `Start ${LANE_NAME[unit]}`, desc: `It loads and answers in ${readyIn(unit)}.`}); return steps; @@ -496,7 +506,9 @@ function askJourney(target, opts = {}){ const warns = []; if (serving && serving[0] === UFLASH && TRANSITIONAL.has(serving[1].state)) warns.push('Flash is booting: stopping now throws that boot away, and the next start takes a whole boot again.'); if (serving && serving[0] !== unit && (serving[0] === U27 || serving[0] === UFLASH)) warns.push('Agent clients on :30001 lose their engine until a text lane answers again.'); - if (serving && (serving[0] === IMAGE_UNIT || serving[0] === VIDEO_UNIT) && serving[0] !== unit) warns.push('A generation in flight on ' + laneLabel(serving[0]) + ' is lost.'); + // stopped for another lane, or restarted on its other checkpoint: either ends a generation + if (serving && (serving[0] === IMAGE_UNIT || serving[0] === VIDEO_UNIT) && steps.some(s => s.name === 'unit' && s.params.unit === serving[0])) + warns.push('A generation in flight on ' + laneLabel(serving[0]) + ' is lost.'); warns.forEach(x => w.append(el('p', null, x))); w.hidden = !warns.length; const j = $('sh-journey'); clear(j); j.hidden = false; steps.forEach((s, i) => { @@ -690,7 +702,7 @@ function renderBanners(state, errors){ // A switch that is not restarted yet: the unit loads one checkpoint at its next start while // the engine serves another, and nothing else on the page said so. const sv = servingEngine(); - if (sv && (sv[0] === U27 || sv[0] === UFLASH) && sv[1].state === 'ready'){ + if (sv && (sv[0] === U27 || sv[0] === UFLASH || sv[0] === IMAGE_UNIT) && sv[1].state === 'ready'){ const served = servedTarget(sv[0]), next = sv[1].target; if (served && next && served !== next) add('info', `${TARGET_NAME[served]} is serving, and the lane's next start loads ${TARGET_NAME[next]}.`, diff --git a/dashboard/static/js/image.js b/dashboard/static/js/image.js index c656c4dc..bd3bd072 100644 --- a/dashboard/static/js/image.js +++ b/dashboard/static/js/image.js @@ -21,8 +21,15 @@ const IMG_EXAMPLES = { 'Local edit': {mode: 'edit', 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.'}}; // The most pixels one call may ask for, its images together: the largest call measured -// on this box (one 2752x1536 image, 44.8 GB at its peak). cockpit.py refuses the same. +// on this box (one 2752x1536 image, 46.6 GB at its peak). cockpit.py refuses the same. const IMG_MAX_PIXELS = 2752 * 1536; +// The Turbo checkpoint (./switch-model.sh image-turbo) samples on the eight-step sigma grid +// its model_index.json carries, whatever num_inference_steps a request says, so the field is +// left out of its requests (as the cookbook says) and the slider stops offering a choice. +const IMG_TURBO_STEPS = 8; +// what the engine serves when it says so, what its unit's next start loads otherwise +const imgTurbo = () => laneTarget(IMAGE_UNIT) === 'image-turbo'; +const imgSteps = () => imgTurbo() ? IMG_TURBO_STEPS : Number($('img-steps').value); const IS = {mode: 't2i', refs: [], inflight: null, run: null, busy: false, available: false, busyLabel: '', stageAt: {stage: '', at: 0}, watching: null, history: [], port: 30020, host: '127.0.0.1'}; const imgVal = id => ($(id) ? $(id).value.trim() : ''); function imgSize(){ @@ -36,9 +43,9 @@ function imgProblem(){ const {w, h} = imgSize(); if (!w || !h) return 'Set a width and a height.'; if (w % 32 || h % 32) return `${w} × ${h} is not a multiple of 32, which the engine refuses. Nearest: ${Math.max(32, Math.round(w / 32) * 32)} × ${Math.max(32, Math.round(h / 32) * 32)}.`; - const steps = Number($('img-steps').value); if (!(steps >= 1 && steps <= 100)) return 'Steps run from 1 to 100; the model default is 40.'; + const steps = imgSteps(); if (!(steps >= 1 && steps <= 100)) return 'Steps run from 1 to 100; the model default is 40.'; const n = Number($('img-n').value); if (!(n >= 1 && n <= 10)) return 'Between 1 and 10 images per call.'; - if (n * w * h > IMG_MAX_PIXELS) return `${n} image${n > 1 ? 's' : ''} of ${w} × ${h} is ${(n * w * h / 1e6).toFixed(1)} megapixels in one call; the largest measured here is ${(IMG_MAX_PIXELS / 1e6).toFixed(1)} (44.8 GB at its peak). The images of a call run as one batch, and running out of memory hangs this machine. Ask for fewer or smaller images.`; + if (n * w * h > IMG_MAX_PIXELS) return `${n} image${n > 1 ? 's' : ''} of ${w} × ${h} is ${(n * w * h / 1e6).toFixed(1)} megapixels in one call; the largest measured here is ${(IMG_MAX_PIXELS / 1e6).toFixed(1)} (46.6 GB at its peak). The images of a call run as one batch, and running out of memory hangs this machine. Ask for fewer or smaller images.`; const cfg = Number(imgVal('img-cfg') || 1); if (cfg > 1 && !imgVal('img-neg')) return 'A CFG scale above 1 does nothing without a negative prompt: the engine needs both.'; if (imgVal('img-neg') && cfg <= 1) return 'A negative prompt does nothing without a CFG scale above 1: the engine needs both.'; @@ -46,21 +53,24 @@ function imgProblem(){ const seed = imgVal('img-seed'); if (seed && !/^\d+$/.test(seed)) return 'The seed is a whole number, or empty for a random one.'; return ''; } -// Fitted to this box on six measured sizes at 40 steps (512 9.0 s to 2752x1536 193 s): -// t = 1 + steps x 0.97 x (pixels / 1024^2)^1.14, linear in steps; an edit adds about -// 4.8 s per reference. +// Fitted to this box on the v0.5.21 runtime (2026-10-10), to the medians of both checkpoints +// at six sizes, 8 and 40 steps (512x512 at 8 steps in 1.8 s to 2752x1536 at 40 in 185 s), +// within 4.9 % of all twelve: a part per image (the text encoding, the VAE decode) and a part +// per step (the denoiser), px = pixels / 1024^2. An edit adds about 1.6 s per reference and +// 0.15 s per reference and step (one reference measured at 8 and at 40 steps). function imgEstimate(q){ q = q || 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 ? 4.8 * Math.max(1, q.refs || 0) : 0)) * (q.n || 1); + const px = (q.w * q.h) / (1024 * 1024), refs = q.editing ? Math.max(1, q.refs || 0) : 0; + return (0.42 + 0.25 * Math.pow(px, 2.08) + q.steps * 0.883 * Math.pow(px, 1.16) + refs * (1.6 + 0.15 * q.steps)) * (q.n || 1); } -function imgFormRequest(){ const {w, h} = imgSize(); return {w, h, steps: Number($('img-steps').value) || 0, n: Number($('img-n').value) || 1, editing: imgEditing(), refs: IS.refs.length}; } +function imgFormRequest(){ const {w, h} = imgSize(); return {w, h, steps: imgSteps() || 0, n: Number($('img-n').value) || 1, editing: imgEditing(), refs: IS.refs.length}; } function imgPayload(){ const {w, h} = imgSize(); // output_format is always explicit: left out, the engine falls back to JPEG, this model // returns RGBA, and the request 500s const p = {prompt: imgVal('img-prompt'), width: w, height: h, num_inference_steps: Number($('img-steps').value), n: Number($('img-n').value), output_format: $('img-fmt').value, response_format: 'b64_json', generator_device: $('img-dev').value}; + if (imgTurbo()) delete p.num_inference_steps; if ($('img-bg').value !== 'auto') p.background = $('img-bg').value; if (imgVal('img-seed') !== '') p.seed = Number(imgVal('img-seed')); if (imgVal('img-cfg') !== '') p.true_cfg_scale = Number(imgVal('img-cfg')); @@ -91,8 +101,12 @@ function imgSync(){ document.querySelectorAll('#img-mode button').forEach(b => b.setAttribute('aria-checked', String(b.dataset.mode === IS.mode))); show('img-refbox', imgEditing()); setText('img-run', imgEditing() ? 'Edit' : 'Generate'); - setText('img-steps-o', $('img-steps').value); setText('img-n-o', $('img-n').value); - [['img-steps', 1, 100], ['img-n', 1, 10]].forEach(([id, a, b]) => { const e = $(id); e.style.setProperty('--pct', (100 * (Number(e.value) - a) / (b - a)).toFixed(1) + '%'); }); + // Under the Turbo the slider keeps the base's setting for when it comes back, and shows + // the eight steps the checkpoint runs. + const turbo = imgTurbo(); $('img-steps').disabled = turbo; + setText('img-steps-hint', turbo ? 'fixed at 8 by the Turbo checkpoint' : 'model default 40'); + setText('img-steps-o', String(imgSteps())); setText('img-n-o', $('img-n').value); + [['img-steps', 1, 100], ['img-n', 1, 10]].forEach(([id, a, b]) => { const v = id === 'img-steps' ? imgSteps() : Number($(id).value); $(id).style.setProperty('--pct', (100 * (v - a) / (b - a)).toFixed(1) + '%'); }); const problem = imgProblem(); show('img-problem', !!problem && (IS.touched || !!imgVal('img-prompt'))); setText('img-problem', problem); const why = !IS.available ? imgLaneWhy() : IS.inflight ? 'Your image is being made.' : IS.busy ? 'Someone else’s image is being made: one at a time on this lane.' : !imgVal('img-prompt') ? 'Write a prompt first.' : problem; @@ -102,7 +116,7 @@ function imgSync(){ const secs = imgEstimate(), {w, h} = imgSize(); setText('img-cost-v', secs ? 'about ' + fmtDur(secs) : '…'); setText('img-cost-k', w && h ? `${(w * h / 1e6).toFixed(2)} megapixels${Number($('img-n').value) > 1 ? ' each' : ''}` : ''); - setText('img-cost-b', w * h >= 3.5e6 ? 'Peaks at 44.8 GB instead of 34: four times the pixels cost five times the time.' : 'Fitted to six sizes measured on this box.'); + setText('img-cost-b', w * h >= 3.5e6 ? 'Peaks at 46.6 GB instead of 35.6: four times the pixels cost five times the time.' : 'Fitted to six sizes of both checkpoints measured on this box.'); const cnt = imgVal('img-prompt').length; setText('img-count', cnt ? cnt + ' characters' : ''); imgCurl(); } @@ -239,7 +253,7 @@ function imgRenderLane(){ if (sig.startsWith('down')){ const card = el('div', 'banner info'); card.style.alignItems = 'center'; card.append(el('span', 'lamp' + (e.state === 'failed' ? ' err' : ''))); const d = el('div'); d.style.cssText = 'display:flex; flex-wrap:wrap; align-items:center; gap:var(--s-3)'; const t = el('span', null, e.state === 'failed' ? 'The image lane failed. Its journal is in Logs.' : s ? `${laneLabel(s[0])} holds the box. Loading the image lane stops it first.` : 'The image lane is stopped.'); t.style.cssText = 'flex:1; min-width:240px'; - const b = el('button', 'btn primary', 'Load Qwen-Image'); b.type = 'button'; b.addEventListener('click', () => askJourney('image')); + const b = el('button', 'btn primary', 'Load Qwen-Image'); b.type = 'button'; b.addEventListener('click', () => askJourney(laneTarget(IMAGE_UNIT) || 'image')); d.append(t, b); card.append(d); box.append(card); } } if (sig === 'boot'){ const card = box.firstChild, eta = e.eta || READY_DEFAULT[IMAGE_UNIT], pct = eta && e.elapsed ? Math.min(97, 100 * e.elapsed / eta) : 6; @@ -285,11 +299,13 @@ function imgCancel(){ async function imgSample(){ if (IS.refs.length >= 10) return toast('Ten references is the maximum.', 'warn'); if (IS.inflight || IS.busy) return toast('The lane is already making an image; one at a time.', 'warn'); - const t0 = Date.now(); IS.inflight = t0; IS.run = {w: 1024, h: 1024, steps: 20, n: 1, editing: false}; + const t0 = Date.now(); IS.inflight = t0; IS.run = {w: 1024, h: 1024, steps: imgTurbo() ? IMG_TURBO_STEPS : 20, n: 1, editing: false}; imgWorking('Making a sample reference: a red teapot'); imgSync(); imgWatch(true); try{ - const {status, ok, out} = await postJSON('/api/image/generate', {prompt: 'A bright daylight photograph of a red teapot on a wooden table 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 body = {prompt: 'A bright daylight photograph of a red teapot on a wooden table 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}; + if (imgTurbo()) delete body.num_inference_steps; // its grid sets the steps, as for any request + const {status, ok, out} = await postJSON('/api/image/generate', body); if (!ok) return toast(status === 409 ? out.error : 'Could not make a sample: ' + (out.error || status), status === 409 ? 'warn' : 'err', 7000); const first = ((out.image || out).data || [])[0]; if (!first || !first.b64_json) return toast('The lane answered with no image in it.', 'err'); imgShow(out.image || out, 'png'); @@ -305,7 +321,7 @@ function wireImage(){ ['img-size', 'img-w', 'img-h', 'img-steps', 'img-n', 'img-bg', 'img-fmt', 'img-dev', 'img-seed', 'img-cfg', 'img-shift', 'img-neg', 'img-prompt'].forEach(id => { const e = $(id); e.addEventListener('input', () => { if (id !== 'img-prompt') IS.touched = true; imgSync(); }); e.addEventListener('change', imgSync); }); document.querySelectorAll('#img-mode button').forEach(b => b.addEventListener('click', () => { IS.mode = b.dataset.mode; imgSync(); })); - $('img-reset').addEventListener('click', () => { IS.refs = []; imgDrawRefs(); imgReset(); toast('Back to the model’s defaults: 1024 × 1024, 40 steps, one image, CFG off.', 'ok', 2600); }); + $('img-reset').addEventListener('click', () => { IS.refs = []; imgDrawRefs(); imgReset(); toast(`Back to the model’s defaults: 1024 × 1024, ${imgTurbo() ? 'the Turbo’s 8 steps' : '40 steps'}, one image, CFG off.`, 'ok', 2600); }); $('img-reffile').addEventListener('change', e => { imgAddFiles(e.target.files); e.target.value = ''; }); $('img-refsample').addEventListener('click', imgSample); $('img-run').addEventListener('click', imgRun); diff --git a/dashboard/static/js/now.js b/dashboard/static/js/now.js index ada8041d..89ab5877 100644 --- a/dashboard/static/js/now.js +++ b/dashboard/static/js/now.js @@ -137,7 +137,7 @@ function renderRack(){ if (pool) fact('KV pool', fmtK(pool)); if (seated && e && e.elapsed && (st === 'ready' || st === 'degraded')) fact('up', fmtDur(e.elapsed)); if (unit === VIDEO_UNIT) fact('4 s clip', 'about 11 min'); - if (unit === IMAGE_UNIT) fact('1024 image', 'about 38 s'); + if (unit === IMAGE_UNIT) fact('1024 image', laneTarget(IMAGE_UNIT) === 'image-turbo' ? 'about 7.5 s' : 'about 34 s'); const en = (F.units[unit] || {}).enabled; setText(b.note, !has ? LANE_INSTALL[unit] : en === 'enabled' ? 'starts at boot' : en === '?' ? '' : 'manual start'); setText(b.act, !has ? 'Not installed' : seated ? (st === 'ready' || st === 'degraded' ? `Open ${LANE_META[unit].view === 'agent' ? 'the agent' : LANE_META[unit].view}` : 'Details') : 'Load this lane'); diff --git a/dashboard/sudoers-cockpit.template b/dashboard/sudoers-cockpit.template index 946aa34c..caf5d653 100644 --- a/dashboard/sudoers-cockpit.template +++ b/dashboard/sudoers-cockpit.template @@ -41,6 +41,7 @@ __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl disable qwen38-video.service __USER__ ALL=(root) NOPASSWD: /usr/bin/systemctl disable qwen38-llamacpp.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 __HOME__/.config/qwen38/qwen38-image.service.switch-stage /etc/systemd/system/qwen38-image.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 __USER__ ALL=(root) NOPASSWD: /usr/local/bin/qwen38-pyspy-scheduler "" __USER__ ALL=(root) NOPASSWD: /usr/bin/journalctl -k --since -1h --no-pager -o short-iso diff --git a/dashboard/tests/test_image_routes.py b/dashboard/tests/test_image_routes.py index db070b70..b7faafdd 100644 --- a/dashboard/tests/test_image_routes.py +++ b/dashboard/tests/test_image_routes.py @@ -79,8 +79,8 @@ class Sent: outer = self class R: - def read(self_inner): - return outer.payload + def read(self_inner, n=-1): + return outer.payload if n < 0 else outer.payload[:n] def __enter__(self_inner): return self_inner @@ -245,6 +245,89 @@ class TheEditingPath(Base): self.assertNotIn("Authorization", self.spy.headers) +class WhichCheckpointTheLaneServes(Base): + """The lane has two checkpoints (./switch-model.sh image, image-turbo), and the page's + Load, its Turbo controls and the Lanes card all read which one from the unit's own + --model-path, through unit_target.""" + + def _unit(self, model): + unit = self.tmp / f"qwen38-image-{model.replace('/', '_')}.service" + unit.write_text(f"[Service]\nExecStart=/x/sglang serve --model-path {model} \\\n" + " --host 127.0.0.1 --port 30020\n") + self.ck.IMAGE_UNIT_PATH = unit + + def test_the_turbo_is_its_own_target(self): + self._unit("Qwen/Qwen-Image-2.1-Turbo") + self.assertEqual(self.ck.unit_target("qwen38-image.service"), + {"model": "Qwen/Qwen-Image-2.1-Turbo", "target": "image-turbo"}) + + def test_the_base_and_any_other_checkpoint_are_image(self): + for model in ("Qwen/Qwen-Image-2.1", "someone/finetune"): + self._unit(model) + self.assertEqual(self.ck.unit_target("qwen38-image.service"), {"model": model, "target": "image"}) + + def test_no_unit_no_target(self): + self.ck.IMAGE_UNIT_PATH = Path("/nonexistent/qwen38-image.service") + self.assertEqual(self.ck.unit_target("qwen38-image.service"), {"model": None, "target": None}) + + +class WhatTheEngineSaysItServes(Base): + """GET /model_info of the image engine, once per life of its unit: the unit's file says + what the next start loads, and ./switch-model.sh from a terminal rewrites it under a + serving engine, which goes on serving what it loaded.""" + + def setUp(self): + super().setUp() + self.ck.IMAGE_SERVED.update(life=None, model=None, asked=0.0) + self.spy.payload = b'{"model_path": "Qwen/Qwen-Image-2.1-Turbo", "model_type": "diffusion"}' + + def test_it_asks_the_engine_once_per_life(self): + self.assertEqual(self.ck.image_served_model("100"), "Qwen/Qwen-Image-2.1-Turbo") + self.assertEqual(self.spy.url, "http://127.0.0.1:30020/model_info") + self.spy.url = "" + self.assertEqual(self.ck.image_served_model("100"), "Qwen/Qwen-Image-2.1-Turbo") + self.assertEqual(self.spy.url, "", "asked again within the same life") + self.spy.payload = b'{"model_path": "Qwen/Qwen-Image-2.1"}' + self.assertEqual(self.ck.image_served_model("200"), "Qwen/Qwen-Image-2.1") + + def test_an_engine_that_does_not_answer_is_asked_again_later_not_every_tick(self): + calls = [] + + def down(req, timeout=None): + calls.append(req.full_url) + raise ConnectionRefusedError("still loading") + self.ck.urllib.request.urlopen = down + self.assertIsNone(self.ck.image_served_model("300")) + self.assertIsNone(self.ck.image_served_model("300")) + self.assertEqual(len(calls), 1) + self.ck.IMAGE_SERVED["asked"] -= 11 + self.ck.urllib.request.urlopen = self.spy.urlopen + self.assertEqual(self.ck.image_served_model("300"), "Qwen/Qwen-Image-2.1-Turbo") + + def test_an_answer_without_a_model_is_no_answer(self): + self.spy.payload = b'{"detail": "Not Found"}' + self.assertIsNone(self.ck.image_served_model("400")) + + def test_the_lanes_entry_carries_it_beside_the_units_target(self): + unit = self.tmp / "qwen38-image-served.service" + unit.write_text("[Service]\nExecStart=/x/sglang serve --model-path Qwen/Qwen-Image-2.1 \\\n" + " --host 127.0.0.1 --port 30020\n") + saved = (self.ck.IMAGE_UNIT_PATH, self.ck.image_engine_state, self.ck.run) + self.ck.IMAGE_UNIT_PATH = unit + self.ck.image_engine_state = lambda u, **kw: ({"state": "ready"}, {"stage": None, "fired_up": True, "done": []}, True) + self.ck.run = lambda argv, timeout=5.0, merge_err=False: ( + "ActiveState=active\nSubState=running\nActiveEnterTimestampMonotonic=4242\n" + if argv[:3] == ["systemctl", "show", "qwen38-image.service"] else "") + try: + out = self.ck.collect_lifecycle() + finally: + self.ck.IMAGE_UNIT_PATH, self.ck.image_engine_state, self.ck.run = saved + e = out.get("data", out)["engines"]["qwen38-image.service"] + self.assertEqual(e["target"], "image") + self.assertEqual(e["served_target"], "image-turbo") + self.assertEqual(self.spy.url, "http://127.0.0.1:30020/model_info") + + class WhatTheTabIsTold(Base): def test_a_lane_that_is_not_installed_says_so_rather_than_stopped(self): """"Stopped" invites a start button for a unit that does not exist.""" @@ -397,7 +480,7 @@ class ThePixelBudget(Base): 2026-09-23, ten times one image's 4.6, and nobody has measured where that batch's memory ends. On unified memory running out hangs the machine, so a call may not ask for more pixels, all its images together, than the largest call measured here: one - 2752x1536 image, 44.8 GB at its peak. Nothing past it reaches the lane.""" + 2752x1536 image, 46.6 GB at its peak. Nothing past it reaches the lane.""" def ask(self, **fields): return self.call({"prompt": "p", "output_format": "png", **fields}) @@ -406,7 +489,7 @@ class ThePixelBudget(Base): code, out = self.ask(width=2048, height=2048, n=10, num_inference_steps=60) self.assertEqual(code, 400) self.assertIn("41.9 megapixels", out["error"]) - self.assertIn("one 2752x1536 image, 44.8 GB", out["error"]) + self.assertIn("one 2752x1536 image, 46.6 GB", out["error"]) self.assertIsNone(self.spy.body, "a refused call reached the lane") def test_the_largest_measured_call_still_goes_through(self): diff --git a/dashboard/tests/test_image_turbo_page.py b/dashboard/tests/test_image_turbo_page.py new file mode 100644 index 00000000..3528a444 --- /dev/null +++ b/dashboard/tests/test_image_turbo_page.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""The image lane's Turbo target on the page: a variant of the lane like flash-nvda of the +flash, loaded the same way, and an Image view that stops offering a step count the +checkpoint ignores (its eight-step sigma grid is in its model_index.json; the cookbook says +to leave num_inference_steps out). Same harness as test_page_behaviour.py.""" +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from test_page_behaviour import run # noqa: E402 + +IMG = "'qwen38-image.service'" + + +def lanes(image_state, image_target, text_state="stopped"): + return (f"feed({{units: UNITS, lifecycle: life({{'qwen38-sglang.service': eng('{text_state}'), " + f"'qwen38-flash.service': eng('stopped', {{target: 'flash'}}), " + f"{IMG}: eng('{image_state}', {{target: '{image_target}'}})}})}});\n") + + +class TheTargetIsALaneVariant(unittest.TestCase): + def test_it_belongs_to_the_image_lane_and_has_a_name_of_its_own(self): + r = run(self, r""" + report({unit: TARGET_UNIT('image-turbo'), base: TARGET_UNIT('image'), list: LANE_TARGETS[IMAGE_UNIT], + name: TARGET_NAME['image-turbo'], short: TARGET_SHORT['image-turbo'], note: TARGET_NOTE['image-turbo'] || ''}); + """) + self.assertEqual(r["unit"], "qwen38-image.service") + self.assertEqual(r["base"], "qwen38-image.service") + self.assertEqual(r["list"], ["image", "image-turbo"]) + self.assertEqual(r["name"], "Qwen-Image 2.1 Turbo") + self.assertEqual(r["short"], "Turbo") + self.assertIn("eight", r["note"]) + + def test_the_switch_phrase_names_it(self): + r = run(self, r""" + report([actionPhrase('switch', {target: 'image'}), actionPhrase('switch', {target: 'image-turbo'})]); + """) + self.assertNotEqual(r[0], r[1]) + self.assertIn("Turbo", r[1]) + + +class LoadingIt(unittest.TestCase): + """The journey is the lanes' own: point the unit at the checkpoint, then restart it when + it serves the other one, or stop the serving lane and start it.""" + + def test_from_the_base_serving_it_is_a_switch_then_a_restart(self): + r = run(self, lanes("ready", "image") + r""" + report(laneJourneySteps('image-turbo').map(s => s.name + (s.params.verb ? ':' + s.params.verb : ''))); + """) + self.assertEqual(r, ["switch", "unit:restart"]) + + def test_from_a_text_lane_it_is_a_switch_a_stop_and_a_start(self): + r = run(self, lanes("stopped", "image", text_state="ready") + r""" + report(laneJourneySteps('image-turbo').map(s => s.name + (s.params.verb ? ':' + s.params.verb + ' ' + s.params.unit : ''))); + """) + self.assertEqual(r, ["switch", "unit:stop qwen38-sglang.service", "unit:start qwen38-image.service"]) + + def test_already_serving_it_is_nothing_to_do(self): + r = run(self, r""" + feed({units: {units: Object.assign({}, UNITS.units, {'qwen38-sglang.service': {active: 'inactive', enabled: 'disabled'}, + 'qwen38-image.service': {active: 'active', enabled: 'enabled'}})}, + lifecycle: life({'qwen38-sglang.service': eng('stopped'), 'qwen38-image.service': eng('ready', {target: 'image-turbo'})})}); + report(laneJourneySteps('image-turbo').length); + """) + self.assertEqual(r, 0) + + +class TheImageViewUnderTheTurbo(unittest.TestCase): + def test_the_request_leaves_the_step_count_out_and_the_slider_says_why(self): + r = run(self, lanes("ready", "image-turbo") + r""" + $('img-prompt').value = 'a cat'; $('img-steps').value = '40'; imgSync(); + report({payload: imgPayload(), steps: imgFormRequest().steps, disabled: $('img-steps').disabled, + shown: txt('img-steps-o'), hint: txt('img-steps-hint'), problem: imgProblem()}); + """) + self.assertNotIn("num_inference_steps", r["payload"]) + self.assertEqual(r["steps"], 8) + self.assertTrue(r["disabled"]) + self.assertEqual(r["shown"], "8") + self.assertIn("fixed at 8", r["hint"]) + self.assertEqual(r["problem"], "") + + def test_the_estimate_counts_eight_steps(self): + r = run(self, lanes("ready", "image-turbo") + r""" + $('img-steps').value = '40'; const turbo = imgEstimate(); + feed({lifecycle: life({'qwen38-sglang.service': eng('stopped'), 'qwen38-image.service': eng('ready', {target: 'image'})})}); + const base = imgEstimate(); + report({turbo, base}); + """) + self.assertLess(r["turbo"], r["base"] / 4) + + def test_the_base_keeps_its_slider_and_its_setting(self): + r = run(self, lanes("ready", "image") + r""" + $('img-prompt').value = 'a cat'; $('img-steps').value = '33'; imgSync(); + report({payload: imgPayload(), disabled: $('img-steps').disabled, shown: txt('img-steps-o'), hint: txt('img-steps-hint')}); + """) + self.assertEqual(r["payload"]["num_inference_steps"], 33) + self.assertFalse(r["disabled"]) + self.assertEqual(r["shown"], "33") + self.assertEqual(r["hint"], "model default 40") + + def test_the_load_button_loads_the_checkpoint_the_unit_names(self): + r = run(self, lanes("stopped", "image-turbo", text_state="ready") + r""" + const asked = []; askJourney = t => asked.push(t); + imgRenderLane(); + const b = [...document.querySelectorAll('button')].find(x => x.textContent === 'Load Qwen-Image'); + if (b) b.click(); + report(asked); + """) + self.assertEqual(r, ["image-turbo"]) + + +class WhatTheEngineServes(unittest.TestCase): + """The unit's file says what the lane's next start loads; the engine's own /model_info, + read by the cockpit once per life of the unit (served_target), says what it serves. A + switch from a terminal rewrites the unit under a serving engine: the page sent the + Turbo's request to the base and found no restart owed (found in review, 2026-10-10).""" + + def served(self, unit_target, served_target, body): + return run(self, r""" + feed({units: {units: Object.assign({}, UNITS.units, {'qwen38-sglang.service': {active: 'inactive', enabled: 'disabled'}, + 'qwen38-image.service': {active: 'active', enabled: 'enabled'}})}, + lifecycle: life({'qwen38-sglang.service': eng('stopped'), + 'qwen38-image.service': eng('ready', {target: '%s', served_target: '%s'})})}); + """ % (unit_target, served_target) + body) + + def test_a_unit_switched_under_the_engine_owes_its_restart(self): + r = self.served("image-turbo", "image", r""" + report({steps: laneJourneySteps('image-turbo').map(s => s.name + (s.params.verb ? ':' + s.params.verb : '')), + banners: txt('banners'), turbo: imgTurbo()}); + """) + self.assertEqual(r["steps"], ["unit:restart"]) + self.assertIn("Qwen-Image 2.1 is serving, and the lane's next start loads Qwen-Image 2.1 Turbo.", r["banners"]) + self.assertFalse(r["turbo"], "the page took the unit's word over the engine's") + + def test_the_page_follows_the_engine(self): + r = self.served("image", "image-turbo", r""" + $('img-prompt').value = 'a cat'; $('img-steps').value = '40'; imgSync(); + report({payload: imgPayload(), turbo: imgTurbo(), steps: laneJourneySteps('image').map(s => s.name + (s.params.verb ? ':' + s.params.verb : ''))}); + """) + self.assertTrue(r["turbo"]) + self.assertNotIn("num_inference_steps", r["payload"]) + self.assertEqual(r["steps"], ["unit:restart"]) + + def test_serving_what_the_unit_names_owes_nothing(self): + r = self.served("image-turbo", "image-turbo", r""" + report({n: laneJourneySteps('image-turbo').length, banners: txt('banners')}); + """) + self.assertEqual(r["n"], 0) + self.assertNotIn("next start loads", r["banners"]) + + def test_pointing_the_unit_at_what_the_engine_serves_restarts_nothing(self): + """The terminal switch the other way: the engine serves the Turbo, its unit names the + base. Loading the Turbo points the unit back at it, and a restart would only end a + generation in flight.""" + r = self.served("image", "image-turbo", r""" + report(laneJourneySteps('image-turbo').map(s => s.name + (s.params.verb ? ':' + s.params.verb : ''))); + """) + self.assertEqual(r, ["switch"]) + + def test_restarting_it_on_the_other_checkpoint_says_a_generation_is_lost(self): + r = self.served("image", "image", r""" + askJourney('image-turbo'); + report({warns: txt('sh-warns'), steps: [...$('sh-journey').children].map(li => li.textContent)}); + """) + self.assertIn("A generation in flight on Qwen-Image", r["warns"]) + self.assertTrue(any("A generation in flight is lost." in s for s in r["steps"]), r["steps"]) + + +class TheSampleAndTheResetUnderTheTurbo(unittest.TestCase): + def test_the_sample_leaves_the_steps_to_the_grid_and_the_reset_says_eight(self): + r = run(self, lanes("ready", "image-turbo") + r""" + let sent = null; + __fetch = async (url, init) => url === '/api/csrf' ? __response(200, {token: 't'}) + : url === '/api/image/generate' ? (sent = JSON.parse(init.body), __response(200, {data: [{b64_json: 'AAAA'}]})) + : url === '/api/image' ? __response(200, {available: true, installed: true, progress: {}}) : new Promise(() => {}); + await imgSample(); + $('img-reset').click(); + report({sent, toast: toastText()}); + """) + self.assertIsNotNone(r["sent"]) + self.assertNotIn("num_inference_steps", r["sent"]) + self.assertIn("the Turbo’s 8 steps", r["toast"]) + self.assertNotIn("40 steps", r["toast"]) + + def test_the_base_sample_keeps_its_twenty_steps(self): + r = run(self, lanes("ready", "image") + r""" + let sent = null; + __fetch = async (url, init) => url === '/api/csrf' ? __response(200, {token: 't'}) + : url === '/api/image/generate' ? (sent = JSON.parse(init.body), __response(200, {data: [{b64_json: 'AAAA'}]})) + : url === '/api/image' ? __response(200, {available: true, installed: true, progress: {}}) : new Promise(() => {}); + await imgSample(); + $('img-reset').click(); + report({sent, toast: toastText()}); + """) + self.assertEqual(r["sent"]["num_inference_steps"], 20) + self.assertIn("40 steps", r["toast"]) + + +class WhatThePageSaysOfEach(unittest.TestCase): + def test_the_now_card_times_the_checkpoint_it_loads(self): + r = run(self, lanes("stopped", "image-turbo", text_state="ready") + r""" + renderRack(); const turbo = txt('view-now'); + feed({lifecycle: life({'qwen38-sglang.service': eng('ready'), 'qwen38-image.service': eng('stopped', {target: 'image'})})}); + renderRack(); report({turbo, base: txt('view-now')}); + """) + self.assertIn("1024 image about 7.5 s", r["turbo"]) + self.assertIn("1024 image about 34 s", r["base"]) + self.assertNotIn("38 s", r["turbo"] + r["base"]) + + def test_the_switch_says_what_it_rewrites_for_each_lane(self): + r = run(self, r""" + report(['stock', 'image', 'image-turbo', 'video'].map(t => EXPLAIN.switch({target: t}).split('\n\n').pop())); + """) + self.assertIn("rewrites its unit, the proxy ceiling and the opencode default model", r[0]) + for x in r[1:3]: + self.assertIn("points its unit at this checkpoint", x) + self.assertNotIn("proxy", x) + self.assertIn("changes nothing else", r[3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/dashboard/tests/test_page_details.py b/dashboard/tests/test_page_details.py index 8ebc09c7..730ecce1 100644 --- a/dashboard/tests/test_page_details.py +++ b/dashboard/tests/test_page_details.py @@ -267,13 +267,14 @@ class SwitchPhrasesNameTheLane(unittest.TestCase): def test_every_target_reads_differently(self): r = run(self, r""" - const ts = ['stock', 'uncensored', 'fp8', 'uncensored-fp8', 'flash', 'flash-uncensored', 'flash-nvda', 'image', 'video']; + const ts = ['stock', 'uncensored', 'fp8', 'uncensored-fp8', 'flash', 'flash-uncensored', 'flash-nvda', 'image', 'video', 'image-turbo']; report(ts.map(t => actionPhrase('switch', {target: t}))); """) self.assertEqual(len(set(r)), len(r), r) self.assertIn("27B", r[1]) self.assertIn("flash", r[5]) self.assertIn("MiniMax-H3", r[8]) + self.assertIn("Turbo", r[9]) class GibibytesAreSaidAsSuch(unittest.TestCase): @@ -510,17 +511,23 @@ class ThePhonesSessionCardIsNotRewrittenForNothing(unittest.TestCase): class TheEditEstimateCountsItsReferences(unittest.TestCase): """U39: an edit cost six seconds more than a generation whatever it carried: ten - references at 20 steps were announced at 26 s and measured at 69.6.""" + references at 20 steps were announced at 26 s and measured at 69.6. Since v1.24.0 the + estimate is the v0.5.21 runtime's, for both checkpoints (measured 2026-10-10: the base's + edit 41.9 s and generation 34.3 s at 40 steps, the Turbo's 10.3 and 7.5 at its 8; ten + references were measured on the runtime before, which was about 5 % slower).""" - def test_the_two_measured_edits(self): + def test_the_measured_edits_and_generations(self): r = run(self, r""" report([imgEstimate({w: 1024, h: 1024, steps: 40, n: 1, editing: true, refs: 1}), imgEstimate({w: 1024, h: 1024, steps: 20, n: 1, editing: true, refs: 10}), - imgEstimate({w: 1024, h: 1024, steps: 40, n: 1, editing: false})]); + imgEstimate({w: 1024, h: 1024, steps: 40, n: 1, editing: false}), + imgEstimate({w: 1024, h: 1024, steps: 8, n: 1, editing: true, refs: 1}), + imgEstimate({w: 1024, h: 1024, steps: 8, n: 1, editing: false}), + imgEstimate({w: 2048, h: 2048, steps: 40, n: 1, editing: false}), + imgEstimate({w: 512, h: 512, steps: 8, n: 1, editing: false})]); """) - self.assertAlmostEqual(r[0], 44.6, delta=44.6 * 0.1) - self.assertAlmostEqual(r[1], 69.6, delta=69.6 * 0.1) - self.assertAlmostEqual(r[2], 38.2, delta=38.2 * 0.1) + for got, measured in zip(r, (41.9, 69.6, 34.3, 10.3, 7.5, 182.8, 1.82)): + self.assertAlmostEqual(got, measured, delta=measured * 0.1) class TheUpdateCommandsNameThisCheckout(unittest.TestCase): diff --git a/docs/flash-lane.md b/docs/flash-lane.md index cafab835..eef8dd93 100644 --- a/docs/flash-lane.md +++ b/docs/flash-lane.md @@ -81,7 +81,7 @@ silently caps `--max-running-requests` to what the mamba pool admits while Both speculative tiers are the cookbook's own verified single-Spark cells, which score **GSM8K 97.1-97.3% on the full 1,319-question set** upstream. `concurrency` became the default on 2026-09-30 with `--mamba-max-states-per-path 2` added, -after the campaign measured it on this box (memory flash_palier8_nightly_2026_09_29: +after the campaign measured it on this box (2026-09-29, on the nightly it was pinned to: canaries 4/4, needle 120k/200k 2/2, prefix cache 99.5 to 99.9% on repeated prefixes, the pool never saturated, mamba peaked at 22 of 40). The per-path cap halves the state each speculative path holds, which is what makes 8 requests fit diff --git a/docs/image-lane.md b/docs/image-lane.md index e8815b47..8a4492dc 100644 --- a/docs/image-lane.md +++ b/docs/image-lane.md @@ -36,8 +36,15 @@ same single Load control, and it obeys the same rule. Back to text is the same three moves the other way. From a terminal the switch is `./switch-model.sh image` (or `stock`), and it prints the two commands that follow. +**Two checkpoints, one lane.** The Lanes card offers `Qwen-Image 2.1` and `Qwen-Image 2.1 +Turbo`, Qwen's eight-step distillation of the same model (`./switch-model.sh image-turbo` from +a terminal). The base stays the default. The Turbo is about four and a half times faster for +the same uses, and its first switch downloads 32.5 GB; switching between the two rewrites the +unit's `--model-path` and nothing else, then restarts the lane (about 80 s). See +[The Turbo checkpoint](#the-turbo-checkpoint) below. + **Never two engines at once.** 31 GB of weights do not fit beside a serving LLM, and a -request takes the lane to 34.8 GB at 1024x1024 (44.7 GB at 2048x2048). The cockpit refuses to start any engine while +request takes the lane to 35.6 GB at 1024x1024 (46.5 GB at 2048x2048). The cockpit refuses to start any engine while another one is busy, and says which one to stop, for all three lanes alike: starting the image lane while the 27B serves comes back `409 blocked`, and so does starting the 27B while the image lane loads. That gate used to pick "the other engine" with `[0]`, which @@ -59,16 +66,23 @@ serves: they talk to the text engine on :30000, which is closed then. They used ## Why a venv and not the docker image The cookbook is explicit for this model: *"This integration currently uses the -Python/source command; no published Docker image is verified."* Qwen-Image 2.1 is in no -SGLang release either, so the lane runs a pinned source checkout -(`ddebc52f237a1dbb56533469ab2ec2a7b856c4ab`). The checkpoint is pinned too, at the revision -the lane was measured with (`790c92633540aa0cb11d9abf19eb46d861714758`, `IMAGE_MODEL_REV` -overrides it), and `./check-pins.sh` asks upstream daily whether the checkpoint, the commit -and the `0.5.20` wheel still resolve. +Python/source command; no published Docker image is verified."* So the lane runs a pinned +source checkout: the `v0.5.21` release (its tag's commit, +`e00930c5489053f26d86b179cee0d087f846acbb`), the first that carries Qwen-Image 2.1, with the +local patches below. From 2026-09-22 to 2026-10-10 it ran the `main` commit `ddebc52f237a`, +which no release held yet. The checkpoints are pinned too, at the revisions the lane was +measured with (`790c92633540aa0cb11d9abf19eb46d861714758` for the base, `d65dbc9a7e8f` for the +Turbo; `IMAGE_MODEL_REV` overrides them), and `./check-pins.sh` asks upstream daily whether +both checkpoints, the commit and the `0.5.21` wheel still resolve. The released wheel still goes in **first**, and the order is not cosmetic: it carries `sglang-kernel` built for aarch64, which a source tree does not build. Source first -leaves a runtime with no native kernels that dies on the first request. The editable +leaves a runtime with no native kernels that dies on the first request. The wheel also sets +the versions of everything the runtime imports, so a pin that moves to a new release takes +that release's wheel too: the installer writes down the wheel a venv came from +(`sglang-wheel` in the lane's folder) and installs the new one over a venv that has another, +or no note at all. Until v1.24.0 it only checked that `sglang` imported, which would have +left a v0.5.20 venv's `cache-dit` 1.3.0 under v0.5.21, which asks for 1.5.1. The editable overlay then goes on with `--no-deps`, because letting the source tree resolve again pulls a `transformers` that breaks the encoder this model needs. @@ -78,9 +92,13 @@ pulls a `transformers` that breaks the encoder this model needs. ### The local changes to the pinned source -Two, neither about images, both applied by `install-image.sh` from `image-sglang/`, both -checked against the real upstream files at the pin by a CI step, and both skipped with a -note if a future pin no longer fits them (the lane serves either way). +Five, all applied by `install-image.sh` from `image-sglang/`, all checked against the real +upstream files at the pin by a CI step, and all skipped with a note if a future pin no longer +fits them. The first two are not about images, and the lane serves either way. The other +three are [sgl-project/sglang#43391](https://github.com/sgl-project/sglang/pull/43391), merged +upstream on 2026-10-10 and in no release yet, one file each, which the Turbo cannot do +without (the installer refuses to serve it on a runtime they did not reach); the next pin +that carries #43391 drops them. #### An idle lane no longer holds a CPU core @@ -143,7 +161,7 @@ how a verified recipe quietly stops being one. The unit adds `--output-path ""` with `--input-save-path ""`. By default this server writes every image it makes **and every reference anyone uploads** under its working directory, forever: 103 MB accumulated in one afternoon of testing. Empty string is read -back as `None` (`server_args.py:828`), the cockpit and the API take their pixels from the +back as `None` (`runtime/server_args/server_args.py:851` at the pin), the cockpit and the API take their pixels from the response, and nothing needs the copy. Point them at a directory if you want an archive, and watch it grow. @@ -165,32 +183,85 @@ authenticated door in front of it. That bind does not follow `ENGINE_BIND`, whic to the lane that does have a key; `IMAGE_BIND=` overrides it, and the installer says out loud what that costs. +## The Turbo checkpoint + +[`Qwen/Qwen-Image-2.1-Turbo`](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo), published by +Qwen on 2026-10-09 under the same Qwen Research licence as the base, is an eight-step +distillation of the same model. Compared file by file with the base: the transformer is the +distilled one (14.2 GB, same architecture and same index), the text encoder is the base's saved +again as one file (17.5 GB; only its `transformers_version` and a `pad_token_id: null` differ in +its config), the VAE comes in bf16 (0.7 GB against 1.35), and `model_index.json` carries an +eight-value `sample_sigmas` grid with `use_dynamic_shifting` off in the scheduler's config. + +That grid is the whole point. A request runs on it whatever `num_inference_steps` says: on the +reference box `num_inference_steps: 2` gave the same PNG as leaving the field out. Without +sgl-project/sglang#43391 the runtime loads the Turbo's weights all the same and samples them on +a uniform schedule built from `num_inference_steps`, which is not what they were trained for; +with it (the three patches above) the grid reaches the sampler, and the base, which has no grid, +samples exactly as before. + +**Measured on the reference box on 2026-10-10**, both checkpoints on the same runtime (v0.5.21 +and the five patches), seed 42, CPU generator: see the table below. Same seed twice gave the +same bytes. The quality was looked at on eight prompts with one seed each, the Turbo against the +base at its 40 steps and at eight: a photograph, a portrait, a shop sign with French text and +prices, a counting prompt (three apples, two pears), a landscape, a watercolour, an interior +and an infographic. The Turbo is close to the base at 40 steps on the photographs, the portrait, +the illustrations and the short text (`Boulangerie Margot`, `Croissant 2,10 €` and +`Baguette 1,30 €` exact in both); both miscount the fruit (two apples and two pears for the +Turbo, four and three for the base); both garble the infographic's body text, the Turbo with +invented English words under unnumbered panels, the base with invented Chinese-looking +characters under its four numbered steps. The base at eight steps, for comparison, is visibly +unfinished on every prompt: what the distillation buys. A sample to look at, not a benchmark. + +Transparency works the same way, asked for by the prompt: 70.9 % of the Turbo's pixels came +back under alpha 16 for a perfume bottle, 74.3 % of the base's for the same prompt and seed. +An edit with one reference takes 10.3 s. + +The cockpit knows which checkpoint the unit names. Under the Turbo the Image view's step slider +shows 8 and is disabled, the request leaves `num_inference_steps` out (as the cookbook says), +and the estimate counts eight steps. Loading it from the Lanes card is the same journey as any +lane's: the switch rewrites `--model-path`, then the lane restarts (about 80 s). + ## What it costs, measured here -Every number is a request made against this lane on a DGX Spark on 2026-09-22, not a -figure from the cookbook. Peak memory is what the server reports for itself. +Every number is a request made against this lane on a DGX Spark, not a figure from the +cookbook: the server's own time and peak memory, on the v0.5.21 runtime and its five patches, +2026-10-10, the median of the calibration runs: three for each size of the base, four of the +Turbo, five at 2048x2048, where one Turbo run took 52.0 s with a slow VAE decode against 38.9 +to 41.0 s for the others. All fifteen requests of the base at 1024x1024 that day give 34.4 s, +all eighteen of the Turbo 7.5 s. The transparent and edit rows are one request each, the base +at 8 steps eight. -| request | time | peak | -|---|---:|---:| -| 512x512, 40 steps | 9.0 s | 31.9 GB | -| 768x768, 40 steps | 22.6 s | 31.9 GB | -| **1024x1024, 40 steps (the defaults)** | **38.2 s** | 34.8 GB | -| 1664x928, 40 steps | 60.4 s | 34.8 GB | -| 2048x2048, 40 steps (the model card's own size) | 190.9 s | 44.7 GB | -| 1024x1024 at 8 / 20 / 60 steps | 8.4 / 19.8 / 57.3 s | 31.9 GB | -| transparent 1024x1024 | 39.8 s | 34.8 GB | -| edit, one reference, 40 steps | 44.6 s | 34.8 GB | -| edit, ten references, 20 steps | 69.6 s | 34.8 GB | -| two images in one call, 8 steps | 16.8 s | 31.9 GB | +| request | base, 40 steps (the defaults) | Turbo, its 8 steps | peak, either | +|---|---:|---:|---:| +| 512x512 | 7.8 s | 1.8 s | 32.8 GB | +| 768x768 | 19.5 s | 4.3 s | 34.1 GB | +| **1024x1024** | **34.3 s** | **7.5 s** | 35.6 GB | +| 1664x928 | 54.6 s | 11.9 s | 37.4 GB | +| 2048x2048 (the model card's own size) | 182.8 s | 40.6 s | 46.5 GB | +| 2752x1536 (the largest call admitted) | 185.2 s | 40.5 s | 46.6 GB | +| transparent 1024x1024 | 34.9 s | 7.6 s | 35.6 GB | +| edit, one reference | 41.9 s | 10.3 s | 35.7 GB | +| the base at 8 steps, 1024x1024 | 7.5 s | | 35.6 GB | -The cookbook publishes 35.36 s for this machine at 1024x1024/40; 38.2 s here. Cost is -linear in steps, and a little worse than linear in pixels: four times the 1024x1024 -time would be 153 s at 2048x2048, and it takes 190.9 s. The cockpit's estimate is -`1 + steps x 0.97 x (pixels / 1024^2)^1.14` seconds, within 6.5 % of all nine measured -requests. Startup is 60 to 72 s from a warm page cache. At rest the lane costs about -0.05 CPU cores (see the idle-loop fix above). +The cookbook publishes 35.36 s for this machine at 1024x1024/40; 34.3 s here. Cost is linear +in steps and worse than linear in pixels: four times the 1024x1024 pixels cost about five and +a third times the time (5.3 for the base, 5.4 for the Turbo). The cockpit's estimate is `0.42 + 0.25 x px^2.08 + steps x 0.883 x px^1.16` +seconds with `px` the pixels over 1024^2, a part per image (the text encoding and the VAE +decode) and a part per step (the denoiser), within 4.9 % of all twelve medians of both +checkpoints; an edit adds about `1.6 + 0.15 x steps` seconds per reference (one reference +measured, at 8 and at 40 steps). The GPU throttles itself on heat (`SW thermal slowdown`, seen +at 86 °C during the 40-step runs at 2048x2048), which is part of the spread between runs. +Startup is 60 to 90 s from a warm page cache, its one warm-up request included. -Same seed, twice: byte-identical. 8 steps is visibly unfinished and not worth the 8.4 s. +On the runtime before (the `main` commit `ddebc52f237a`, 2026-09-22), 1024x1024 at 40 steps +took 38.2 s; measured again the morning of 2026-10-10 beside the new one, 36.08 s against +34.40 s (median of three on each), the same twelve requests giving the same bytes on both, for +0.8 GB more at the peak on the new one. Also measured on that runtime only: ten references at +20 steps in 69.6 s, two images in one call at 8 steps in 16.8 s. + +Same seed, twice: byte-identical. The base at 8 steps is visibly unfinished and not worth its +7.5 s; the Turbo's 8 steps are finished (see above). ## One image at a time, and what happens if you ignore that @@ -227,7 +298,8 @@ denoising step on 2026-09-23, where one image takes 4.6: the pipeline runs them and the memory that needs grows with them. Where it ends for a call that size has not been measured, and on this box running out of unified memory hangs the machine instead of failing the request. So the cockpit refuses a call whose images add up to more pixels than -the largest call measured here: one 2752x1536 image (4.2 megapixels, 44.8 GB at its peak). +the largest call measured here: one 2752x1536 image (4.2 megapixels, 46.6 GB at its peak on +the v0.5.21 runtime with either checkpoint; 44.8 GB on the commit before). Four 1024x1024 images fit under it, ten 512x512 too; two 2048x2048 do not. The Image view says so before sending, and the server refuses the same with the numbers. diff --git a/docs/video-lane.md b/docs/video-lane.md index d04e0a8f..57eae50b 100644 --- a/docs/video-lane.md +++ b/docs/video-lane.md @@ -66,8 +66,8 @@ not dubbed afterwards, so the two stay in sync. This lane serves the cookbook's MiniMax-H3 recipe as upstream wrote it at the pinned commit, with **one local source patch**: the image lane's idle-loop wait -(`image-sglang/scheduler-idle-poll.patch`, one file for both lanes, which serve the same -SGLang commit). The diffusion scheduler's loop never waits, so a lane with nothing to do +(`image-sglang/scheduler-idle-poll.patch`, one file for both lanes: the loop it patches is +the same at both lanes' pinned commits, which CI checks against the real files). The diffusion scheduler's loop never waits, so a lane with nothing to do held one CPU core at 100%, which kept the box's hottest zone near 61 °C at rest (43 °C with no lane loaded) and its fans loud. Measured on the reference box (2026-10-06), 3 min after the lane was ready: 1.05 cores without the patch, 0.05 with it, the hottest zone 67 diff --git a/image-sglang/qwen-image21-turbo-sigma-config.patch b/image-sglang/qwen-image21-turbo-sigma-config.patch new file mode 100644 index 00000000..bef1bba7 --- /dev/null +++ b/image-sglang/qwen-image21-turbo-sigma-config.patch @@ -0,0 +1,30 @@ +diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/qwen_image21.py b/python/sglang/multimodal_gen/configs/pipeline_configs/qwen_image21.py +index f69371f6da..030ab7caec 100644 +--- a/python/sglang/multimodal_gen/configs/pipeline_configs/qwen_image21.py ++++ b/python/sglang/multimodal_gen/configs/pipeline_configs/qwen_image21.py +@@ -26,13 +26,16 @@ class QwenImage21PipelineConfig(ImagePipelineConfig): + vae_config: QwenImage21VAEConfig = field(default_factory=QwenImage21VAEConfig) + text_encoder_configs: tuple = field(default_factory=lambda: (Qwen3VLConfig(),)) + text_encoder_precisions: tuple[str, ...] = ("bf16",) ++ sample_sigmas: list[float] | None = None + + def supports_dynamic_batching(self): + # the scheduler excludes reference-image requests from cross-request merging + return True + + def prepare_sigmas(self, sigmas, num_inference_steps): +- return self._prepare_sigmas(sigmas, num_inference_steps) ++ if sigmas is None: ++ sigmas = self.sample_sigmas ++ return list(self._prepare_sigmas(sigmas, num_inference_steps)) + + def get_classifier_free_guidance_scale(self, batch, guidance_scale): + return ( +@@ -97,6 +100,6 @@ def register(): + register_configs( + sampling_param_cls=QwenImage21SamplingParams, + pipeline_config_cls=QwenImage21PipelineConfig, +- hf_model_paths=["Qwen/Qwen-Image-2.1"], ++ hf_model_paths=["Qwen/Qwen-Image-2.1", "Qwen/Qwen-Image-2.1-Turbo"], + model_detectors=[lambda hf_id: "qwen-image-2.1" in hf_id.lower()], + ) diff --git a/image-sglang/qwen-image21-turbo-sigma-pipeline.patch b/image-sglang/qwen-image21-turbo-sigma-pipeline.patch new file mode 100644 index 00000000..1d6b16e3 --- /dev/null +++ b/image-sglang/qwen-image21-turbo-sigma-pipeline.patch @@ -0,0 +1,18 @@ +diff --git a/python/sglang/multimodal_gen/runtime/pipelines/qwen_image21.py b/python/sglang/multimodal_gen/runtime/pipelines/qwen_image21.py +index d69904e6c3..c74eee4139 100644 +--- a/python/sglang/multimodal_gen/runtime/pipelines/qwen_image21.py ++++ b/python/sglang/multimodal_gen/runtime/pipelines/qwen_image21.py +@@ -22,6 +22,13 @@ class QwenImage21Pipeline(LoRAPipeline, ComposedPipelineBase): + "scheduler", + ] + ++ def _load_config(self): ++ model_index = super()._load_config() ++ sample_sigmas = model_index.pop("sample_sigmas", None) ++ if self.server_args.pipeline_config.sample_sigmas is None: ++ self.server_args.pipeline_config.sample_sigmas = sample_sigmas ++ return model_index ++ + def create_pipeline_stages(self, server_args): + self.add_stage(QwenImage21InputValidationStage()) + self.add_stage_factory( diff --git a/image-sglang/qwen-image21-turbo-sigma-stage.patch b/image-sglang/qwen-image21-turbo-sigma-stage.patch new file mode 100644 index 00000000..0776fe81 --- /dev/null +++ b/image-sglang/qwen-image21-turbo-sigma-stage.patch @@ -0,0 +1,18 @@ +diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/qwen_image21.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/qwen_image21.py +index db178e10fe..c491469f13 100644 +--- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/qwen_image21.py ++++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/qwen_image21.py +@@ -55,6 +55,13 @@ class QwenImage21InputValidationStage(InputValidationStage): + batch = super().forward(batch, server_args) + if batch.height % 32 or batch.width % 32: + raise ValueError("Qwen-Image 2.1 height and width must be divisible by 32") ++ batch.sigmas = server_args.pipeline_config.prepare_sigmas( ++ batch.sigmas, batch.num_inference_steps ++ ) ++ if not batch.sigmas: ++ raise ValueError("Qwen-Image 2.1 requires a non-empty sigma schedule") ++ # the preset or explicit sigma grid determines the denoising step count ++ batch.num_inference_steps = len(batch.sigmas) + return batch + + diff --git a/image-sglang/turbo-grid-check.py b/image-sglang/turbo-grid-check.py new file mode 100644 index 00000000..6bf678b8 --- /dev/null +++ b/image-sglang/turbo-grid-check.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Can this runtime serve Qwen-Image 2.1 Turbo as it was trained? Run with the image lane's +own python: exit 0 if it can, 1 with the reason on stderr if it cannot. + +The Turbo samples on the eight-step sigma grid its model_index.json carries, which a runtime +follows only with sgl-project/sglang#43391 (the three qwen-image21-turbo-sigma-*.patch files +beside this one): the pipeline takes the grid from model_index.json, the pipeline config +keeps it, and the input stage samples on it. Without any one of the three the Turbo loads, +answers 200 and samples on a uniform schedule it was not trained for. A patch that does not +apply to a new pin is a note in the installer, not a failure, so the three are checked here +one by one: the config by what it does with a grid, the pipeline and the stage by the code +that carries it. A release that carries #43391 as merged passes as well. +""" +import dataclasses +import inspect +import sys + + +def missing() -> str: + try: + from sglang.multimodal_gen.configs.pipeline_configs.qwen_image21 import ( + QwenImage21PipelineConfig as Config, + ) + from sglang.multimodal_gen.runtime.pipelines.qwen_image21 import ( + QwenImage21Pipeline as Pipeline, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.qwen_image21 import ( + QwenImage21InputValidationStage as Stage, + ) + except Exception as e: # noqa: BLE001 (any import failure means the same thing here) + return f"the runtime has no Qwen-Image 2.1 pipeline to check ({type(e).__name__}: {e})" + if "sample_sigmas" not in {f.name for f in dataclasses.fields(Config)}: + return "its pipeline config has no place for a sigma grid" + grid = [1.0, 0.75, 0.5, 0.25] + if list(Config(sample_sigmas=grid).prepare_sigmas(None, 50)) != grid: + return "its pipeline config does not sample on the grid it holds" + if "sample_sigmas" not in inspect.getsource(Pipeline): + return "its pipeline does not read the grid from model_index.json" + if "prepare_sigmas" not in inspect.getsource(Stage): + return "its input stage does not take the steps from the grid" + return "" + + +if __name__ == "__main__": + why = missing() + if why: + print(why, file=sys.stderr) + sys.exit(1 if why else 0) diff --git a/install-image.sh b/install-image.sh index de735f06..833a7c49 100755 --- a/install-image.sh +++ b/install-image.sh @@ -14,9 +14,10 @@ # # WHY IT IS A VENV AND NOT DOCKER. The cookbook is explicit for this model: "This # integration currently uses the Python/source command; no published Docker image is -# verified." Qwen-Image 2.1 is in no SGLang release either, so the runtime is a pinned -# source checkout. The release wheel goes in first all the same, because it carries the -# prebuilt aarch64 native kernels that a source tree does not build. +# verified." So the runtime is a pinned source checkout: the v0.5.21 release, the first +# that carries Qwen-Image 2.1, with local patches (step 3). The release wheel goes in +# first all the same, because it carries the prebuilt aarch64 native kernels that a source +# tree does not build. # # ONE ENGINE AT A TIME. 31 GB of weights do not fit beside a serving LLM. The unit says # so with Conflicts=, so starting this stops the LLM lane and starting an LLM lane stops @@ -50,6 +51,7 @@ CONFIG_DIR="$HOME/.config/qwen38" LANE_DIR="${IMAGE_LANE_DIR:-$(installed WorkingDirectory)}"; LANE_DIR="${LANE_DIR:-$HOME/.local/share/qwen38-image}" VENV="$LANE_DIR/venv" SRC="$LANE_DIR/sglang" +WHEEL_NOTE="$LANE_DIR/sglang-wheel" # the wheel release the venv's dependencies come from (step 3) PORT="${IMAGE_PORT:-$(unit_flag --port)}"; PORT="${PORT:-30020}" # The checkpoint and its revision, pinned like the rest: the revision this lane was # measured with on 2026-09-22 (its main then, and on 2026-09-24). It was fetched at main, @@ -58,8 +60,17 @@ PORT="${IMAGE_PORT:-$(unit_flag --port)}"; PORT="${PORT:-30020}" # IMAGE_MODEL_REV, or main. IMAGE_MODEL_PIN="Qwen/Qwen-Image-2.1" IMAGE_MODEL_PIN_REV="790c92633540aa0cb11d9abf19eb46d861714758" +# The Turbo variant (./switch-model.sh image-turbo): Qwen's eight-step distillation of the +# same model, at the revision measured on the reference box on 2026-10-10. A box that +# serves it keeps it, like any target of the unit. +IMAGE_TURBO_PIN="Qwen/Qwen-Image-2.1-Turbo" +IMAGE_TURBO_PIN_REV="d65dbc9a7e8f6b5479e33dee6030eaab2a906509" MODEL="${IMAGE_MODEL:-$(unit_flag --model-path)}"; MODEL="${MODEL:-Qwen/Qwen-Image-2.1}" # = IMAGE_MODEL_PIN -if [ "$MODEL" = "$IMAGE_MODEL_PIN" ]; then MODEL_REV="${IMAGE_MODEL_REV:-$IMAGE_MODEL_PIN_REV}"; else MODEL_REV="${IMAGE_MODEL_REV:-main}"; fi +case "$MODEL" in + "$IMAGE_MODEL_PIN") MODEL_REV="${IMAGE_MODEL_REV:-$IMAGE_MODEL_PIN_REV}" ;; + "$IMAGE_TURBO_PIN") MODEL_REV="${IMAGE_MODEL_REV:-$IMAGE_TURBO_PIN_REV}" ;; + *) MODEL_REV="${IMAGE_MODEL_REV:-main}" ;; +esac # The installed unit's cache, then the one the text lane mounts, then the default: an # update that ignored the unit downloaded 31 GB again into ~/.cache and rewrote HF_HOME on # a box whose lane lived on another disk, and a first install beside a text lane on a @@ -73,12 +84,14 @@ text_cache(){ } HF_CACHE="${HF_CACHE:-$(installed_env HF_HOME)}"; HF_CACHE="${HF_CACHE:-$(text_cache)}" HF_CACHE="${HF_CACHE:-$HOME/.cache/huggingface}" -# Qwen-Image 2.1 is in no SGLang release. This is the commit the lane on the reference -# box was measured against, end to end, on 2026-09-22. SGLANG_DIFFUSION_PIN overrides it +# The v0.5.21 release (its tag's commit), the first that carries Qwen-Image 2.1, measured +# end to end on the reference box on 2026-10-10. From 2026-09-22 until then the lane ran +# the main commit ddebc52, which no release held yet. SGLANG_DIFFUSION_PIN overrides it # only for someone deliberately testing another one. -PIN="${SGLANG_DIFFUSION_PIN:-ddebc52f237a1dbb56533469ab2ec2a7b856c4ab}" -# The released wheel that carries the prebuilt aarch64 kernels the source tree reuses. -WHEEL="${SGLANG_DIFFUSION_WHEEL:-0.5.20}" +PIN="${SGLANG_DIFFUSION_PIN:-e00930c5489053f26d86b179cee0d087f846acbb}" +# The released wheel that carries the prebuilt aarch64 kernels the source tree reuses, and +# the versions of everything else the runtime imports. +WHEEL="${SGLANG_DIFFUSION_WHEEL:-0.5.21}" # Loopback, and not from ENGINE_BIND: that variable belongs to the LLM lane, which has a # key. This one has none (the diffusion parser has no --api-key at all), so a non-loopback # bind puts an unauthenticated image generator on that interface. IMAGE_BIND overrides it @@ -124,12 +137,25 @@ if [ "$ACTION" = uninstall ]; then # Only what this script put there: LANE_DIR can be a directory shared with other work, # and removing it whole took the rest with it (found in review, 2026-09-24). if [ -d "$LANE_DIR" ]; then - rm -rf "$VENV" "$SRC" + rm -rf "$VENV" "$SRC" "$WHEEL_NOTE" echo "runtime removed: $VENV and $SRC" rmdir "$LANE_DIR" 2>/dev/null || echo "kept $LANE_DIR: it holds files the image lane did not put there" fi - echo "the 31 GB checkpoint is left in $HF_CACHE; delete it yourself if you want the space:" - echo " rm -rf $HF_CACHE/hub/models--${MODEL//\//--}" + # ./switch-model.sh's note of a checkpoint to come back to from the Turbo goes with the + # lane, read first: the checkpoint it names is the lane's too + BEFORE_TURBO="$(cat "$CONFIG_DIR/image-model-before-turbo" 2>/dev/null || true)" + rm -f "$CONFIG_DIR/image-model-before-turbo" + # every checkpoint of the lane the cache holds: the unit's, the other one a switch fetched, + # and the one the note named + KEPT=() + for R in "$MODEL" "$IMAGE_MODEL_PIN" "$IMAGE_TURBO_PIN" ${BEFORE_TURBO:+"$BEFORE_TURBO"}; do + D="$HF_CACHE/hub/models--${R//\//--}" + [ -d "$D" ] && [[ " ${KEPT[*]} " != *" $D "* ]] && KEPT+=("$D") + done + if [ "${#KEPT[@]}" -gt 0 ]; then + echo "the lane's checkpoints are left in $HF_CACHE (about 31 GB each); delete them yourself if you want the space:" + for D in "${KEPT[@]}"; do echo " rm -rf $D"; done + fi exit 0 fi @@ -190,16 +216,22 @@ step "3/6 SGLang Diffusion (released wheel first, then the pinned source over it # Order matters and is not cosmetic. The wheel resolves the whole dependency tree AND # ships sglang-kernel built for aarch64; installing the source tree first leaves the # runtime without those kernels and the server dies on the first request. -if ! "$VENV/bin/python" -c 'import sglang' 2>/dev/null; then - echo "installing sglang[diffusion]==$WHEEL (~10 min on this box: torch and the kernels are large)" +# The wheel is also what sets the versions of everything the runtime imports, so a pin +# that moves to a new release takes that release's wheel too: a venv that only checked +# whether sglang imported kept the previous release's dependencies under the new source +# (cache-dit 1.3.0 under v0.5.21, which asks for 1.5.1). The version installed is written +# down; a venv from before this has no note and takes the wheel once. +if ! "$VENV/bin/python" -c 'import sglang' 2>/dev/null || [ "$(cat "$WHEEL_NOTE" 2>/dev/null)" != "$WHEEL" ]; then + echo "installing sglang[diffusion]==$WHEEL (~10 min on a new venv: torch and the kernels are large; an existing one only takes what changed)" "$VENV/bin/pip" install --quiet --pre "sglang[diffusion]==$WHEEL" \ || die "the released wheel would not install. Re-run: pip resumes. If it keeps failing, SGLANG_DIFFUSION_WHEEL= picks another." + printf '%s\n' "$WHEEL" > "$WHEEL_NOTE" fi if [ ! -d "$SRC/.git" ]; then git clone --quiet https://github.com/sgl-project/sglang "$SRC" || die "could not clone SGLang." fi -# Two local changes to the pinned source, neither about images, both measured on the -# reference box (docs/image-lane.md, "The local changes to the pinned source"): +# Local changes to the pinned source, each measured on the reference box (docs/image-lane.md, +# "The local changes to the pinned source"). The first two are not about images: # scheduler-idle-poll: the diffusion scheduler's loop never waits. recv_reqs() polls its # socket without blocking and nothing else in the loop sleeps, so a lane with nothing # to do held one CPU core at 100% (1.047 cores, against 0.029 for the 27B lane, which @@ -210,16 +242,30 @@ fi # and a generation holds one for as long as it runs. A Stop during a 2048x2048 request # sat 60 s in "stopping" until systemd killed the lane and marked the unit failed # (2026-09-23). Now 5 s, then the requests in flight are cancelled and it stops clean. -PATCHES=(scheduler-idle-poll http-graceful-timeout) +# The other three are sgl-project/sglang#43391, merged upstream on 2026-10-10 and in no +# release yet, one file each: the Turbo checkpoint's eight-step sigma grid, which its +# model_index.json carries, reaches the sampler. Without them the Turbo weights load and +# sample on a uniform schedule from num_inference_steps, which is not how it was trained; +# with them the base checkpoint, which has no grid, samples exactly as before. +# One line: CI reads this list with a one-line pattern. +PATCHES=(scheduler-idle-poll http-graceful-timeout qwen-image21-turbo-sigma-config qwen-image21-turbo-sigma-pipeline qwen-image21-turbo-sigma-stage) declare -A PATCH_FIXES=( [scheduler-idle-poll]="an idle lane no longer holds a CPU core" [http-graceful-timeout]="a stop during a generation takes 5 s instead of timing out" + [qwen-image21-turbo-sigma-config]="the Turbo's sigma grid has a place in the pipeline config" + [qwen-image21-turbo-sigma-pipeline]="the Turbo's sigma grid is read from its model_index.json" + [qwen-image21-turbo-sigma-stage]="a Turbo request samples on that grid, eight steps" ) CURRENT="$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)" if [ "$CURRENT" != "$PIN" ]; then # they are the only local edits in this tree: take them off, or the checkout trips on them + # Only from a file that has local edits: a fresh clone stands on upstream's main, where a + # patch merged upstream reverses cleanly too, and taking it off there wrote the very edit + # that then blocked the checkout (a first install, 2026-10-10, once main carried #43391). for P in "${PATCHES[@]}"; do - git -C "$SRC" apply --reverse "$HERE/image-sglang/$P.patch" >/dev/null 2>&1 || true + PF="$HERE/image-sglang/$P.patch" + git -C "$SRC" diff --quiet -- "$(grep -m1 '^+++ b/' "$PF" | cut -c7-)" 2>/dev/null && continue + git -C "$SRC" apply --reverse "$PF" >/dev/null 2>&1 || true done git -C "$SRC" fetch --quiet origin "$PIN" 2>/dev/null || git -C "$SRC" fetch --quiet origin git -C "$SRC" checkout --quiet "$PIN" \ @@ -253,13 +299,29 @@ if ! "$VENV/bin/python" -c 'import sglang, pathlib, sys; sys.exit(0 if str(pathl SGLANG_BUILD_RUST_EXTS=none "$VENV/bin/pip" install --quiet --no-deps -e "$SRC/python" \ || die "the editable overlay failed. The venv still holds the released wheel; re-run to retry." fi +# Asked of the registry itself, not of its source text: v0.5.21 registers the model from its +# pipeline config module, and the text check that held at ddebc52 failed there although the +# runtime served it (2026-10-10). The exact id must map to Qwen-Image 2.1's own config; a +# fuzzy match would also take an unknown "Qwen/Qwen-Image-9.9" for an older Qwen-Image. "$VENV/bin/python" - <<'PY' || die "the runtime does not know Qwen-Image 2.1. The pin may be wrong for this checkout." -import inspect, pathlib, sglang +import pathlib, sglang from sglang.multimodal_gen import registry +from sglang.multimodal_gen.configs.pipeline_configs.qwen_image21 import QwenImage21PipelineConfig +getattr(registry, "_ensure_registry_initialized", lambda: None)() +info = registry._CONFIG_REGISTRY.get(registry._MODEL_HF_PATH_TO_NAME.get("Qwen/Qwen-Image-2.1", "")) +if info is None or info.pipeline_config_cls is not QwenImage21PipelineConfig: + raise SystemExit("Qwen/Qwen-Image-2.1 does not map to Qwen-Image 2.1's own config in the model registry") src = pathlib.Path(sglang.__file__).parent -assert "Qwen/Qwen-Image-2.1" in inspect.getsource(registry), "Qwen-Image-2.1 is not in the model registry" print(f" runtime: {src}") PY +# A Turbo the runtime cannot read the grid of would load, answer 200 and sample on a +# uniform schedule it was not trained for: refused here rather than served degraded. The +# three parts are checked one by one (image-sglang/turbo-grid-check.py). +if [ "$MODEL" = "$IMAGE_TURBO_PIN" ]; then + TURBO_WHY="$("$VENV/bin/python" "$HERE/image-sglang/turbo-grid-check.py" 2>&1)" \ + || die "this lane serves $IMAGE_TURBO_PIN, and the runtime at ${PIN:0:12} cannot sample on its eight-step grid: ${TURBO_WHY:-no reason given} (a qwen-image21-turbo-sigma patch above did not apply?). Serve the base with ./switch-model.sh image, or pin a commit that carries sgl-project/sglang#43391." + echo " the runtime samples on the Turbo's eight-step sigma grid" +fi step "4/6 Checkpoint ($MODEL at ${MODEL_REV:0:12}, ~31 GB, one-time, resumable)" # The same two lessons the LLM lane learned the hard way: the Hub's Xet backend stalls @@ -312,6 +374,13 @@ grep -q '__[A-Z][A-Z0-9_]*__' "$RENDER" && die "the unit template still holds an # 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=. +# A unit installed for another checkpoint than it named (IMAGE_MODEL=) is not the one +# ./switch-model.sh image-turbo left: the note of the way back from the Turbo goes, or a +# later `./switch-model.sh image` would bring back a checkpoint from before this install. +INSTALLED_MODEL="$(unit_flag --model-path)" +if [ -n "$INSTALLED_MODEL" ] && [ "$INSTALLED_MODEL" != "$MODEL" ]; then + rm -f "$CONFIG_DIR/image-model-before-turbo" +fi 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 @@ -379,9 +448,11 @@ fi import base64, json, struct, sys d = json.load(open(sys.argv[1]))["data"][0] raw = base64.b64decode(d["b64_json"]) -assert raw[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" +if raw[:8] != b"\x89PNG\r\n\x1a\n": + raise SystemExit("not a PNG") w, h = struct.unpack(">II", raw[16:24]) -assert (w, h) == (512, 512), f"got {w}x{h}" +if (w, h) != (512, 512): + raise SystemExit(f"got {w}x{h}") print(f" {w}x{h} {'RGBA' if raw[25] == 6 else raw[25]}, {len(raw)/1e6:.1f} MB") PY # What the lane costs with nothing to do, from its own cgroup: the CPU time systemd @@ -400,6 +471,6 @@ fi # the trap stops the lane and brings the text lane back, whichever way this ends step "Done: the image lane is installed and proved it serves on $IMAGE_BIND:$PORT" -echo " switch to it : Load on Qwen-Image 2.1 in the cockpit's Lanes view, or ./switch-model.sh image" +echo " switch to it : Load on Qwen-Image 2.1 (or its Turbo) in the cockpit's Lanes view, or ./switch-model.sh image (image-turbo)" echo " back to text : Load on a text lane there, or ./switch-model.sh stock" echo " generate : the cockpit's Image view, or the API on :$PORT (loopback, no key)" diff --git a/install-video.sh b/install-video.sh index 3bacfe76..3d683868 100755 --- a/install-video.sh +++ b/install-video.sh @@ -82,8 +82,8 @@ text_cache(){ } HF_CACHE="${HF_CACHE:-$(installed_env HF_HOME)}"; HF_CACHE="${HF_CACHE:-$(text_cache)}" HF_CACHE="${HF_CACHE:-$HOME/.cache/huggingface}" -# The SGLang source this lane was developed against: the same pin as the image lane, -# whose installed runtime already registers MiniMaxH3Pipeline (checked 2026-09-25). +# The SGLang source this lane was developed against, the image lane's pin until v1.24 (that +# lane moved to the v0.5.21 release), which registers MiniMaxH3Pipeline (checked 2026-09-25). # SGLANG_DIFFUSION_PIN overrides it only for someone deliberately testing another one. PIN="${SGLANG_DIFFUSION_PIN:-ddebc52f237a1dbb56533469ab2ec2a7b856c4ab}" # The released wheel that carries the prebuilt aarch64 kernels the source tree reuses. @@ -208,7 +208,7 @@ if [ ! -d "$SRC/.git" ]; then git clone --quiet https://github.com/sgl-project/sglang "$SRC" || die "could not clone SGLang." fi # One local change to the pinned source, the image lane's scheduler-idle-poll (one file -# in image-sglang/ for both lanes, which serve the same SGLang commit). The diffusion +# in image-sglang/ for both lanes, which applies to the pin of each). The diffusion # scheduler's loop never waits: recv_reqs() polls its socket without blocking and nothing # else in the loop sleeps, so a lane with nothing to do held one CPU core at 100%, kept # the box's hottest zone near 61 C at rest (43 C with no lane loaded) and its fans @@ -228,8 +228,13 @@ declare -A PATCH_FIXES=( CURRENT="$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)" if [ "$CURRENT" != "$PIN" ]; then # it is the only local edit in this tree: take it off, or the checkout trips on it + # Only from a file that has local edits: a fresh clone stands on upstream's main, where a + # patch merged upstream reverses cleanly too, and taking it off there wrote the very edit + # that then blocked the checkout (a first install, 2026-10-10, once main carried #43391). for P in "${PATCHES[@]}"; do - git -C "$SRC" apply --reverse "$HERE/image-sglang/$P.patch" >/dev/null 2>&1 || true + PF="$HERE/image-sglang/$P.patch" + git -C "$SRC" diff --quiet -- "$(grep -m1 '^+++ b/' "$PF" | cut -c7-)" 2>/dev/null && continue + git -C "$SRC" apply --reverse "$PF" >/dev/null 2>&1 || true done git -C "$SRC" fetch --quiet origin "$PIN" 2>/dev/null || git -C "$SRC" fetch --quiet origin git -C "$SRC" checkout --quiet "$PIN" \ diff --git a/mirror-pins.sh b/mirror-pins.sh index 7aa83c7e..dafaa2fd 100755 --- a/mirror-pins.sh +++ b/mirror-pins.sh @@ -49,7 +49,7 @@ img="$(grep -E '^(IMAGE|FLASH_IMAGE)=' "$REPO_DIR/install.sh")" eval "$img" # the image lane's checkpoint, pinned in install-image.sh like the rest (check-pins.sh # reads the same lines) -lane="$(grep -E '^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV)=' "$REPO_DIR/install-image.sh")" +lane="$(grep -E '^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV|IMAGE_TURBO_PIN|IMAGE_TURBO_PIN_REV)=' "$REPO_DIR/install-image.sh")" eval "$lane" # the video lane's checkpoint, pinned in install-video.sh like the rest vline="$(grep -E '^(VIDEO_MODEL_PIN|VIDEO_MODEL_PIN_REV)=' "$REPO_DIR/install-video.sh")" @@ -170,6 +170,7 @@ if [ "$MODE" != "--images" ]; then mirror_model "draft" "$DRAFT_REPO" "$DRAFT_REV" mirror_model "draft2" "$DRAFT2_REPO" "$DRAFT2_REV" mirror_model "qwen-image" "$IMAGE_MODEL_PIN" "$IMAGE_MODEL_PIN_REV" + mirror_model "qwen-image-turbo" "$IMAGE_TURBO_PIN" "$IMAGE_TURBO_PIN_REV" mirror_model "minimax-h3" "$VIDEO_MODEL_PIN" "$VIDEO_MODEL_PIN_REV" fi if [ "$MODE" != "--models" ]; then diff --git a/qwen38-image.service.template b/qwen38-image.service.template index 4310bda8..abb7b9ef 100644 --- a/qwen38-image.service.template +++ b/qwen38-image.service.template @@ -3,7 +3,7 @@ Description=Qwen-Image 2.1 (SGLang Diffusion, native venv), OpenAI images API :_ Wants=network-online.target # One engine at a time on this box, and systemd is where that is said rather than in a # wrapper someone can bypass: the image checkpoint is 31 GB of weights and peaks at -# 34.8 GB during a 1024px request (measured), while the LLM lane holds its pool for the +# 35.6 GB during a 1024px request (measured), while the LLM lane holds its pool for the # life of the process. Starting this stops the LLM lane; starting an LLM lane stops this. Conflicts=qwen38-sglang.service qwen38-flash.service qwen38-video.service qwen38-llamacpp.service # Conflicts= alone orders nothing: the old lane's stop and the new lane's start ran side diff --git a/switch-model.sh b/switch-model.sh index 79876cab..a4f65c96 100755 --- a/switch-model.sh +++ b/switch-model.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Surgical target-model switch on a live install, between the five targets: +# Surgical target-model switch on a live install, between these targets: # # ./switch-model.sh stock # RadixArk/Qwen3.8-27B-NVFP4 (SGLang) # ./switch-model.sh uncensored # edp1096/Huihui-...-abliterated-NVFP4 (SGLang) @@ -9,6 +9,7 @@ # ./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) +# ./switch-model.sh image-turbo # Qwen/Qwen-Image-2.1-Turbo, its eight-step distillation # ./switch-model.sh video # MiniMaxAI/MiniMax-H3 (SGLang Diffusion, own venv) # # Within the 27B lane (stock, uncensored, fp8, uncensored-fp8) it does what it @@ -45,7 +46,7 @@ _ENV_HF_CACHE="${HF_CACHE:-}" # before the pins below give it install.sh's # 27B lane and restarting what follows it, where the usage was all anyone wanted (found # in review, 2026-09-24). MODEL_CHOICE= still names one, as install.sh takes it. CHOICE="${1:-${MODEL_CHOICE:-}}" -case "$CHOICE" in stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored|image|video) ;; *) printf 'usage: ./switch-model.sh \n' >&2; [ -z "$CHOICE" ] && exit 2; die "unknown target: $CHOICE" ;; esac +case "$CHOICE" in stock|uncensored|fp8|uncensored-fp8|flash|flash-nvda|flash-uncensored|image|image-turbo|video) ;; *) printf 'usage: ./switch-model.sh \n' >&2; [ -z "$CHOICE" ] && exit 2; die "unknown target: $CHOICE" ;; 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|SERVE_IMAGE|MODEL_CHOICE|HF_CACHE|CONFIG_DIR)=' "$REPO_DIR/install.sh" || true)" @@ -61,6 +62,10 @@ unset _v IMAGE_UNIT="/etc/systemd/system/qwen38-image.service" IMAGE_UNIT_NAME="qwen38-image.service" +# The image unit is rewritten between its two checkpoints (image, image-turbo) with sudo, +# so it is staged at a fixed path the cockpit's exact-argv sudoers allowlist names, as the +# 27B unit is below. +IMG_STAGE="$CONFIG_DIR/qwen38-image.service.switch-stage" VIDEO_UNIT="/etc/systemd/system/qwen38-video.service" VIDEO_UNIT_NAME="qwen38-video.service" @@ -88,25 +93,69 @@ disable_rollback_lane(){ # 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 +# serving image to inspect (it runs from its own venv), nothing in the unit to rewrite but +# its --model-path (between the lane's checkpoints), 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" ] || [ "$CHOICE" = "image-turbo" ]; then [ -f "$IMAGE_UNIT" ] || die "the image lane is not installed on this box (no $IMAGE_UNIT). Install it once: ./install.sh --with-image (40 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}" + # The lane's two checkpoints and their pinned revisions, from install-image.sh, the one + # place they are declared. + eval "$(grep -E '^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV|IMAGE_TURBO_PIN|IMAGE_TURBO_PIN_REV)=' "$REPO_DIR/install-image.sh" || true)" + for _v in IMAGE_MODEL_PIN IMAGE_MODEL_PIN_REV IMAGE_TURBO_PIN IMAGE_TURBO_PIN_REV; do + eval "[ -n \"\${$_v:-}\" ]" || die "install-image.sh no longer defines $_v (repo layout changed?)" + done + unset _v + IMG_CUR="$(grep -oE -- '--model-path [^ ]+' "$IMAGE_UNIT" | head -1 | cut -d' ' -f2 || true)" + IMG_CUR="${IMG_CUR:-$IMAGE_MODEL_PIN}" + # image-turbo serves the Turbo; image serves the base, or the checkpoint the unit was + # installed with (IMAGE_MODEL=) when it is neither, written down on the way to the Turbo + # so that the way back finds it. + IMG_BEFORE_TURBO="$CONFIG_DIR/image-model-before-turbo" + if [ "$CHOICE" = "image-turbo" ]; then + IMG_MODEL="$IMAGE_TURBO_PIN" + elif [ "$IMG_CUR" = "$IMAGE_TURBO_PIN" ]; then + IMG_MODEL="$(cat "$IMG_BEFORE_TURBO" 2>/dev/null || true)"; IMG_MODEL="${IMG_MODEL:-$IMAGE_MODEL_PIN}" + else + IMG_MODEL="$IMG_CUR" + fi + # The revision this box serves of that checkpoint, as the video lane reads it: the unit + # names the repo with HF_HUB_OFFLINE=1, so its refs/main IS the served commit, and one an + # install made with IMAGE_MODEL_REV= stays served. The installer's pin answers when the ref + # is missing or holds no commit, and main for a checkpoint of the unit's own. 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" + IMG_MODEL_DIR="${IMG_HF:-$HF_CACHE}/hub/models--${IMG_MODEL//\//--}" + IMG_REV="" + if [ -f "$IMG_MODEL_DIR/refs/main" ]; then IMG_REV="$(cat "$IMG_MODEL_DIR/refs/main")"; fi + [[ "$IMG_REV" =~ ^[0-9a-f]{40}$ ]] || IMG_REV="" + if [ -z "$IMG_REV" ]; then + case "$IMG_MODEL" in + "$IMAGE_MODEL_PIN") IMG_REV="$IMAGE_MODEL_PIN_REV" ;; + "$IMAGE_TURBO_PIN") IMG_REV="$IMAGE_TURBO_PIN_REV" ;; + *) IMG_REV=main ;; + esac + fi + if [ "$IMG_MODEL" = "$IMAGE_TURBO_PIN" ]; then + # The Turbo samples on the eight-step grid its model_index.json carries, which only a + # runtime with sgl-project/sglang#43391 follows; one without it loads the weights and + # samples on a uniform schedule instead, answering 200 with worse images. + IMG_WHY="$("$IMG_PY" "$REPO_DIR/image-sglang/turbo-grid-check.py" 2>&1)" \ + || die "the image lane's runtime cannot sample on the Turbo's eight-step grid (${IMG_WHY:-no reason given}). Update it first: ./install.sh (or ./install-image.sh), then switch again." + fi + printf '\n\033[1;36m── Verifying %s @ %s in the cache (resumable)\033[0m\n' "$IMG_MODEL" "$IMG_REV" # 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" \ + # answers without touching the network at all. A revision is fetched as such and + # refs/main pointed at it when it had none, because the unit runs offline by name, which + # resolves refs/main: fetched at main, a push upstream would have changed what the lane + # serves (the same lesson as install-image.sh, 2026-09-24). + HF_HOME="${IMG_HF:-$HF_CACHE}" HF_HUB_DOWNLOAD_TIMEOUT=30 HF_HUB_DISABLE_XET=1 IMG_MODEL="$IMG_MODEL" IMG_REV="$IMG_REV" \ + IMG_NEED_GB=34 IMG_FREE_GB="$(dl_free_gb "${IMG_HF:-$HF_CACHE}")" \ HF_HUB_DISABLE_PROGRESS_BARS="$DL_NO_BARS" QWEN38_REPO_DIR="$REPO_DIR" \ "$IMG_PY" - <<'PYIMG' || die "the image checkpoint could not be verified or fetched (re-run to resume; set HF_TOKEN if it stalls)" import contextlib @@ -127,14 +176,53 @@ def reporting(*args, **kwargs): return contextlib.nullcontext() -repo = os.environ["IMG_MODEL"] +repo, rev = os.environ["IMG_MODEL"], os.environ["IMG_REV"] try: - print(snapshot_download(repo, local_files_only=True)) + path = snapshot_download(repo, revision=rev, local_files_only=True) except Exception: + # Both checkpoints of this lane are about 33 GB; refused before the first byte rather + # than stopped by a full disk halfway. What the cache already holds of the repo comes + # off the need: a fetch that stopped resumes from there. + from huggingface_hub import constants + blobs = os.path.join(constants.HF_HUB_CACHE, "models--" + repo.replace("/", "--"), "blobs") + have = sum(e.stat().st_size for e in os.scandir(blobs) if e.is_file()) if os.path.isdir(blobs) else 0 + free = int(os.environ.get("IMG_FREE_GB") or 0) + need = max(int(os.environ["IMG_NEED_GB"]) - have // 2**30, 1) + if free and free < need: + raise SystemExit(f"{free} GB free in the cache, and {repo} needs about {need} GB more: free some space first") print("not complete in the cache, fetching the rest", flush=True) - with reporting(repo): - print(snapshot_download(repo)) + with reporting(repo, revision=rev): + path = snapshot_download(repo, revision=rev) +print(path) +sha = os.path.basename(path.rstrip("/")) +if rev != "main" and sha == rev: + ref = os.path.join(os.path.dirname(os.path.dirname(path.rstrip("/"))), "refs", "main") + os.makedirs(os.path.dirname(ref), exist_ok=True) + old = open(ref).read().strip() if os.path.exists(ref) else "" + if old != sha: + with open(ref, "w") as f: + f.write(sha) + print(f"refs/main -> {sha[:12]}" + (f" (was {old[:12]})" if old else ""), flush=True) PYIMG + # The unit names one checkpoint; a switch between the lane's two rewrites that name and + # nothing else. + IMG_REWRITTEN="" + if [ "$IMG_CUR" != "$IMG_MODEL" ]; then + IMG_UNIT_TEXT="$(cat "$IMAGE_UNIT")" + printf '%s\n' "${IMG_UNIT_TEXT//"--model-path $IMG_CUR "/"--model-path $IMG_MODEL "}" > "$IMG_STAGE" + if ! grep -q -- "--model-path $IMG_MODEL " "$IMG_STAGE"; then + rm -f "$IMG_STAGE"; die "the image unit's rewrite to $IMG_MODEL failed (hand-edited unit?): re-run ./install-image.sh" + fi + diff "$IMG_STAGE" "$IMAGE_UNIT" || true # show exactly what changes + sudo install -m 644 "$IMG_STAGE" "$IMAGE_UNIT" + rm -f "$IMG_STAGE" + IMG_REWRITTEN=1 + if [ "$IMG_MODEL" = "$IMAGE_TURBO_PIN" ] && [ "$IMG_CUR" != "$IMAGE_MODEL_PIN" ]; then + printf '%s\n' "$IMG_CUR" > "$IMG_BEFORE_TURBO" + else + rm -f "$IMG_BEFORE_TURBO" + fi + fi # Which text lane this box served, written down before it is disabled: install.sh # updates that lane on a later run, and enablement cannot tell it once both are off. for TEXT_UNIT_NAME in qwen38-flash.service qwen38-sglang.service qwen38-video.service; do @@ -161,6 +249,12 @@ PYIMG 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)" + elif systemctl is-active --quiet "$IMAGE_UNIT_NAME" 2>/dev/null; then + if [ -n "$IMG_REWRITTEN" ]; then + echo "Effective after: sudo systemctl restart $IMAGE_UNIT_NAME (it serves the previous checkpoint until then)" + else + echo "Its unit already named this checkpoint. Started before it did, the lane serves what it loaded: sudo systemctl restart $IMAGE_UNIT_NAME" + fi else echo "Effective after: sudo systemctl start $IMAGE_UNIT_NAME (or next reboot; ready in about 70 s)" fi diff --git a/tests/test_check_pins.py b/tests/test_check_pins.py index 3fac90cc..07dd82e1 100644 --- a/tests/test_check_pins.py +++ b/tests/test_check_pins.py @@ -120,7 +120,7 @@ class TheCheckPins(PinsBase): rc, out = self.run_pins(None, "hf_secretvalue123") self.assertEqual(rc, 0, out) hf = [c for c in self.calls() if c["url"].startswith("https://huggingface.co/")] - self.assertEqual(len(hf), 11, hf) # nine checkpoints and the two diffusion lanes' + self.assertEqual(len(hf), 12, hf) # nine checkpoints and the diffusion lanes' three for c in hf: self.assertIn("Authorization: Bearer hf_secretvalue123", c["stdin"], c) self.assertFalse(any("hf_secretvalue123" in a for a in c["argv"]), c["argv"]) @@ -179,10 +179,12 @@ class ThePinsOutsideThePinBlock(PinsBase): def test_they_are_all_checked(self): rc, out = self.run_pins() self.assertEqual(rc, 0, out) - for label in ("qwen-image", "sglang-source", "sglang-wheel", "opencode"): + for label in ("qwen-image", "qwen-image-turbo", "sglang-source", "sglang-wheel", "opencode"): self.assertIn("ok", self.line(out, label), out) self.assertTrue(any("Qwen/Qwen-Image-2.1/raw/790c9263" in c["url"] and c["url"].endswith("/model_index.json") for c in self.calls()), "the image checkpoint is asked for at its pinned revision") + self.assertTrue(any("Qwen/Qwen-Image-2.1-Turbo/raw/d65dbc9a" in c["url"] and c["url"].endswith("/model_index.json") + for c in self.calls()), "the Turbo checkpoint is asked for at its pinned revision") def test_a_removed_source_commit_fails(self): rc, out = self.run_pins({"api.github.com/repos/sgl-project/sglang/commits/": [422, ""]}) @@ -192,7 +194,7 @@ class ThePinsOutsideThePinBlock(PinsBase): def test_a_wheel_gone_or_yanked_fails(self): rc, out = self.run_pins({"bodies": {"pypi.org": '{"message": "Not Found"}'}}) self.assertIn("FAIL", self.line(out, "sglang-wheel"), out) - rc, out = self.run_pins({"bodies": {"pypi.org": json.dumps({"info": {"version": "0.5.20"}, + rc, out = self.run_pins({"bodies": {"pypi.org": json.dumps({"info": {"version": "0.5.21"}, "urls": [{"yanked": True}]})}}) self.assertIn("every file yanked", self.line(out, "sglang-wheel"), out) @@ -231,7 +233,7 @@ class TheEndpointsThatDoNotAnswer(PinsBase): for label in self.GITHUB: self.assertIn("HTTP 504 from the GitHub API, so not checked", self.line(out, label), out) self.assertNotIn("no such", self.line(out, label), out) - self.assertIn("3 of 18 pins could not be asked about", out) + self.assertIn("3 of 19 pins could not be asked about", out) self.assertIn("run it again before re-pinning anything", out) self.assertNotIn("A removed upstream revision", out) diff --git a/tests/test_hf_progress.py b/tests/test_hf_progress.py index bcb92a29..4ea2a63a 100644 --- a/tests/test_hf_progress.py +++ b/tests/test_hf_progress.py @@ -278,7 +278,7 @@ class SwitchModelWiresIt(unittest.TestCase): their bytes, and each keeps its download if the count cannot load.""" def test_each_fetch_runs_inside_the_count(self): - self.assertRegex(heredoc("PYIMG"), r"with reporting\(repo\):\n\s+print\(snapshot_download\(repo\)\)") + self.assertRegex(heredoc("PYIMG"), r"with reporting\(repo, revision=rev\):\n\s+path = snapshot_download\(repo, revision=rev\)") self.assertRegex(heredoc("PYVID"), r"with reporting\(repo, revision=rev, allow_patterns=allow\):\n" r"\s+path = snapshot_download\(repo, revision=rev, allow_patterns=allow\)") text = heredoc("PYEOF") diff --git a/tests/test_image_lane.py b/tests/test_image_lane.py index a473f296..afdd273f 100644 --- a/tests/test_image_lane.py +++ b/tests/test_image_lane.py @@ -15,8 +15,8 @@ to discover, which is the whole reason they are gates rather than documentation: needs both), so a tab that offers one without the other offers a dead control. The rest holds the shape of the install: one engine at a time is a systemd Conflicts= -rather than a convention, the runtime pin is a full commit because Qwen-Image 2.1 is in -no SGLang release, and the sizes the cockpit offers are the seven ratios Qwen publishes. +rather than a convention, the runtime pin is a full commit (the v0.5.21 release's, plus +local patches), and the sizes the cockpit offers are the seven ratios Qwen publishes. """ import pathlib import re @@ -186,12 +186,24 @@ class TheInstaller(unittest.TestCase): self.assertIn("SGLANG_BUILD_RUST_EXTS=none", pip[0]) def test_the_runtime_pin_is_a_full_commit(self): - """Qwen-Image 2.1 is in no SGLang release, so the lane runs a source checkout. A - branch name would make two boxes install two different runtimes from one command.""" + """The lane runs a source checkout with local patches over it (no verified image + exists for this model). A branch or tag name would make two boxes install two + different runtimes from one command.""" m = re.search(r'PIN="\$\{SGLANG_DIFFUSION_PIN:-([^}]+)\}"', INSTALLER.read_text()) self.assertIsNotNone(m, "the pin is no longer assigned the way this test reads it") self.assertRegex(m.group(1), r"^[0-9a-f]{40}$") + def test_a_new_wheel_is_taken_by_a_venv_that_has_another(self): + """The wheel sets the versions of everything the runtime imports. A venv that only + checked whether sglang imported kept the previous release's dependencies under the + new source: cache-dit 1.3.0 under v0.5.21, which asks for 1.5.1.""" + text = INSTALLER.read_text() + self.assertRegex(text, r'(?m)^WHEEL_NOTE="\$LANE_DIR/sglang-wheel"') + self.assertIn('[ "$(cat "$WHEEL_NOTE" 2>/dev/null)" != "$WHEEL" ]', text) + self.assertLess(text.index('pip" install --quiet --pre "sglang[diffusion]==$WHEEL"'), + text.index('printf \'%s\\n\' "$WHEEL" > "$WHEEL_NOTE"')) + self.assertIn('rm -rf "$VENV" "$SRC" "$WHEEL_NOTE"', text, "uninstall leaves the note behind") + def test_the_wheel_goes_in_before_the_source(self): """Order is not cosmetic: the released wheel carries sglang-kernel built for aarch64, which a source tree does not build. Source first leaves a runtime with @@ -306,6 +318,79 @@ def added_code(patch: pathlib.Path) -> list: if ln.startswith("+") and not ln.startswith("+++") and not ln[1:].strip().startswith("#")] +TURBO_PATCHES = {name: REPO / "image-sglang" / f"{name}.patch" for name in + ("qwen-image21-turbo-sigma-config", "qwen-image21-turbo-sigma-pipeline", + "qwen-image21-turbo-sigma-stage")} + + +def pre_image(patch: pathlib.Path) -> str: + """The text of the patched file as each hunk expects to find it, hunks one after the + other: what `git apply` needs to see to apply the patch (it allows the offsets).""" + out = [] + for ln in patch.read_text().splitlines(): + if ln.startswith(("diff --git", "index ", "--- ", "+++ ", "@@")): + continue + if ln.startswith((" ", "-")) or ln == "": + out.append(ln[1:] if ln else "") + return "\n".join(out) + "\n" + + +class TheTurboPatches(unittest.TestCase): + """sgl-project/sglang#43391 (merged 2026-10-10, in no release yet), its runtime part + backported to the v0.5.21 pin, one file per patch as CI requires: the Turbo's + eight-step sigma grid goes from its model_index.json to the sampler. The upstream tests + of that PR passed on the backport (58 of 58, 2026-10-10).""" + + def _patched(self, name): + return re.findall(r"^\+\+\+ b/(.+)$", TURBO_PATCHES[name].read_text(), re.M) + + def test_one_file_each(self): + base = "python/sglang/multimodal_gen/" + self.assertEqual(self._patched("qwen-image21-turbo-sigma-config"), + [base + "configs/pipeline_configs/qwen_image21.py"]) + self.assertEqual(self._patched("qwen-image21-turbo-sigma-pipeline"), + [base + "runtime/pipelines/qwen_image21.py"]) + self.assertEqual(self._patched("qwen-image21-turbo-sigma-stage"), + [base + "runtime/pipelines_core/stages/model_specific_stages/qwen_image21.py"]) + + def test_what_they_change(self): + cfg = added_code(TURBO_PATCHES["qwen-image21-turbo-sigma-config"]) + self.assertIn("sample_sigmas: list[float] | None = None", cfg) + self.assertIn("sigmas = self.sample_sigmas", cfg) + self.assertIn('hf_model_paths=["Qwen/Qwen-Image-2.1", "Qwen/Qwen-Image-2.1-Turbo"],', cfg) + pipe = added_code(TURBO_PATCHES["qwen-image21-turbo-sigma-pipeline"]) + self.assertIn('sample_sigmas = model_index.pop("sample_sigmas", None)', pipe) + stage = added_code(TURBO_PATCHES["qwen-image21-turbo-sigma-stage"]) + self.assertIn("batch.num_inference_steps = len(batch.sigmas)", stage) + + def test_a_turbo_on_a_runtime_without_them_is_refused(self): + text = INSTALLER.read_text() + self.assertIn('if [ "$MODEL" = "$IMAGE_TURBO_PIN" ]; then', text) + # the same check as ./switch-model.sh image-turbo, each part of the fix for what it does + self.assertIn('TURBO_WHY="$("$VENV/bin/python" "$HERE/image-sglang/turbo-grid-check.py" 2>&1)"', text) + self.assertIn('"$IMG_PY" "$REPO_DIR/image-sglang/turbo-grid-check.py"', (REPO / "switch-model.sh").read_text()) + self.assertLess(text.index("the runtime does not know Qwen-Image 2.1"), + text.index("cannot sample on its eight-step grid")) + + def test_no_check_rests_on_an_assert(self): + """python -O (PYTHONOPTIMIZE in the environment) strips assert statements: a check + written as one passes whatever it checks.""" + text = INSTALLER.read_text() + for m in re.finditer(r"<<'PY'.*?\nPY\n", text, re.S): + self.assertNotRegex(m.group(0), r"(?m)^\s*assert ", m.group(0)[:120]) + self.assertNotIn("assert ", (REPO / "image-sglang/turbo-grid-check.py").read_text()) + + def test_the_registry_maps_the_id_to_its_own_config(self): + text = INSTALLER.read_text() + self.assertIn('info.pipeline_config_cls is not QwenImage21PipelineConfig', text) + + def test_the_turbo_pin_is_kept_on_a_box_that_serves_it(self): + text = INSTALLER.read_text() + self.assertRegex(text, r'(?m)^IMAGE_TURBO_PIN="Qwen/Qwen-Image-2\.1-Turbo"$') + self.assertRegex(text, r'(?m)^IMAGE_TURBO_PIN_REV="[0-9a-f]{40}"$') + self.assertIn('"$IMAGE_TURBO_PIN") MODEL_REV="${IMAGE_MODEL_REV:-$IMAGE_TURBO_PIN_REV}" ;;', text) + + class TheLocalPatches(unittest.TestCase): """Two local changes to the pinned SGLang source, both measured on the reference box. The idle loop: an idle lane held one CPU core at 100% (1.047 cores, against 0.029 for @@ -349,7 +434,9 @@ class TheLocalPatches(unittest.TestCase): def _repo(self, sched=CONTEXT_AT_PIN, http=HTTP_CONTEXT_AT_PIN): d = pathlib.Path(tempfile.mkdtemp(prefix="img-src-")) self._git(d, "init", "-q") - for rel, text in ((PATCHED, sched), (HTTP_PATCHED, http)): + turbo = [(re.search(r"^\+\+\+ b/(.+)$", f.read_text(), re.M).group(1), pre_image(f)) + for f in TURBO_PATCHES.values()] + for rel, text in [(PATCHED, sched), (HTTP_PATCHED, http)] + turbo: (d / rel).parent.mkdir(parents=True, exist_ok=True) (d / rel).write_text(text) self._git(d, "add", "-A") @@ -370,6 +457,9 @@ class TheLocalPatches(unittest.TestCase): self.assertEqual(rc, 0, out) self.assertIn("scheduler-idle-poll: applied", out) self.assertIn("http-graceful-timeout: applied", out) + for name in TURBO_PATCHES: + self.assertIn(f"{name}: applied", out) + self.assertNotIn("NOTE:", out) rc, out = self._install(src, pin) self.assertEqual(rc, 0, out) self.assertIn("scheduler-idle-poll: already applied", out) @@ -397,6 +487,21 @@ class TheLocalPatches(unittest.TestCase): self.assertIn("scheduler-idle-poll: applied", out) self.assertIn("http-graceful-timeout: applied", out) + def test_a_fresh_clone_on_a_main_that_carries_a_patch_checks_out_the_pin(self): + """A first install clones upstream's main, where a patch merged upstream reverses + cleanly too: taking it off there wrote the very edit that then blocked the checkout + of the pin (a first install, 2026-10-10, once main carried #43391). Only a file with + local edits holds anything of ours to take off.""" + src = self._repo() + pin = self._git(src, "rev-parse", "HEAD") + self._git(src, "apply", str(TURBO_PATCHES["qwen-image21-turbo-sigma-stage"])) + self._git(src, "commit", "-qam", "upstream merges the patch") # main moves on + self.assertNotEqual(self._git(src, "rev-parse", "HEAD"), pin) + rc, out = self._install(src, pin) + self.assertEqual(rc, 0, out) + self.assertEqual(self._git(src, "rev-parse", "HEAD"), pin) + self.assertIn("qwen-image21-turbo-sigma-stage: applied", out) + def test_a_pin_one_no_longer_fits_is_a_note_not_a_failure(self): src = self._repo(http=HTTP_CONTEXT_AT_PIN.replace("reload=False", "reload=True")) rc, out = self._install(src, self._git(src, "rev-parse", "HEAD")) @@ -544,7 +649,11 @@ class ThePageNeverShowsAStaleOrRacingState(unittest.TestCase): def test_the_text_engines_target_never_labels_the_image_lane(self): # the text engine's target, and only when it is one of this unit's (ownTarget); a # diffusion lane never takes it (servedTarget, which laneTarget reads first) - self.assertIn("unit === IMAGE_UNIT || unit === VIDEO_UNIT) return null", self.js) + self.assertIn("unit === VIDEO_UNIT) return null", self.js) + # the image lane's served target is its own engine's answer (cockpit.py, /model_info), + # returned before the text engine's is ever read + image = self.js.index("if (unit === IMAGE_UNIT) return s[1].served_target || null;") + self.assertLess(image, self.js.index("? ownTarget(unit) : null;")) self.assertIn("return servedTarget(unit) || (engines()[unit] || {}).target || null", self.js) self.assertIn("F.target && TARGET_UNIT(F.target) === unit", self.js) # every lifecycle snapshot restates the served target, so a text engine's @@ -605,12 +714,14 @@ class TheImageLaneIsALaneLikeTheOthers(unittest.TestCase): def test_it_is_a_lane_the_switch_can_load(self): js = PAGE_JS() targets = re.search(r"const LANE_TARGETS = \{(.*?)\};", js, re.S).group(1) - self.assertIn("[IMAGE_UNIT]: ['image']", targets) + self.assertIn("[IMAGE_UNIT]: ['image', 'image-turbo']", targets) # and named apart: it is not one more LLM checkpoint names = re.search(r"const TARGET_NAME = \{(.*?)\};", js, re.S).group(1) self.assertIn("image: 'Qwen-Image 2.1'", names) - # reached through the one journey, never its own start path - self.assertIn("askJourney('image')", js) + self.assertIn("'image-turbo': 'Qwen-Image 2.1 Turbo'", names) + # reached through the one journey, never its own start path, on the checkpoint + # the unit names (the base or the Turbo) + self.assertIn("askJourney(laneTarget(IMAGE_UNIT) || 'image')", js) def test_the_journey_keeps_the_order_the_readme_gives(self): """Stopped first, the boot still points at the old lane and the card offers a @@ -651,7 +762,7 @@ class TheImageLaneIsALaneLikeTheOthers(unittest.TestCase): # the one journey, and stopping is the Lanes card's. calls = re.findall(r"askAction\('unit', \{verb: '(\w+)'", tab) self.assertEqual(calls, ["restart"], "the Image view starts or stops a lane again") - self.assertIn("askJourney('image')", tab) + self.assertIn("askJourney(laneTarget(IMAGE_UNIT) || 'image')", tab) self.assertIn("show('img-cancel', !!(IS.inflight || IS.busy));", tab) self.assertNotIn("function imgUnitButton", tab) @@ -665,7 +776,7 @@ class TheImageLaneIsALaneLikeTheOthers(unittest.TestCase): """The proxy is a text door and opencode a text client: pointing opencode's default model at an image lane would break every session it opened.""" sw = (REPO / "switch-model.sh").read_text() - branch = sw[sw.index('if [ "$CHOICE" = "image" ]; then'):sw.index("exit 0\nfi")] + branch = sw[sw.index('if [ "$CHOICE" = "image" ] || [ "$CHOICE" = "image-turbo" ]; then'):sw.index("exit 0\nfi")] self.assertNotIn("oc-point-default", branch) self.assertNotIn("PROMPT_CEILING_TOKENS", branch) # it runs from its own venv: no serving image to inspect, no container to download with diff --git a/tests/test_image_lane_install_paths.py b/tests/test_image_lane_install_paths.py index 4547d69c..9cf123d3 100644 --- a/tests/test_image_lane_install_paths.py +++ b/tests/test_image_lane_install_paths.py @@ -103,8 +103,12 @@ class TheSpaceWhereItLands(unittest.TestCase): class RemovingTheLaneThatBooted(unittest.TestCase): UNINSTALL = block('if [ "$ACTION" = uninstall ]; then', ' exit 0') - def run_uninstall(self, image_enabled, text_enabled, before="qwen38-sglang.service"): + def run_uninstall(self, image_enabled, text_enabled, before="qwen38-sglang.service", cached=(), note=None): d = pathlib.Path(tempfile.mkdtemp(prefix="img-uninst-")) + if note: + (d / "image-model-before-turbo").write_text(note + "\n") + for repo in cached: + (d / "hf/hub" / ("models--" + repo.replace("/", "--"))).mkdir(parents=True) units = d / "etc" units.mkdir() (units / "qwen38-image.service").write_text("[Service]\n") @@ -127,9 +131,11 @@ class RemovingTheLaneThatBooted(unittest.TestCase): script = ('set -euo pipefail\nstep(){ :; }\nACTION=uninstall; UNIT=qwen38-image.service\n' f'INSTALLED="{units}/qwen38-image.service"; CONFIG_DIR="{d}"; LANE_DIR="{d}/lane"; ' f'VENV="{d}/lane/venv"; SRC="{d}/lane/sglang"; HF_CACHE="{d}/hf"; MODEL=Qwen/Qwen-Image-2.1\n' + 'IMAGE_MODEL_PIN=Qwen/Qwen-Image-2.1; IMAGE_TURBO_PIN=Qwen/Qwen-Image-2.1-Turbo\n' + text + "\nfi\n") rc, out = bash(script, {"HOME": str(d)}, [stub]) calls = (d / "calls").read_text() if (d / "calls").exists() else "" + self.dir = d return rc, out, calls def test_the_lane_before_images_is_enabled_again(self): @@ -146,6 +152,57 @@ class RemovingTheLaneThatBooted(unittest.TestCase): rc, out, calls = self.run_uninstall(image_enabled=False, text_enabled=True) self.assertNotIn("systemctl enable", calls) + def test_every_checkpoint_of_the_lane_in_the_cache_is_named(self): + """A box that tried the Turbo holds both; the message named the unit's alone.""" + rc, out, calls = self.run_uninstall(image_enabled=False, text_enabled=True, + cached=("Qwen/Qwen-Image-2.1", "Qwen/Qwen-Image-2.1-Turbo")) + self.assertEqual(rc, 0, out) + self.assertIn(f"rm -rf {self.dir}/hf/hub/models--Qwen--Qwen-Image-2.1\n", out) + self.assertIn(f"rm -rf {self.dir}/hf/hub/models--Qwen--Qwen-Image-2.1-Turbo\n", out) + self.assertEqual(out.count("rm -rf "), 2, out) + + def test_the_checkpoint_the_switch_note_names_is_named_too(self): + """A unit installed with IMAGE_MODEL= and switched to the Turbo: the note names the + checkpoint of the unit's own, 31 GB in the cache the message must not forget.""" + rc, out, calls = self.run_uninstall(image_enabled=False, text_enabled=True, note="someone/finetune", + cached=("Qwen/Qwen-Image-2.1-Turbo", "someone/finetune")) + self.assertEqual(rc, 0, out) + self.assertIn(f"rm -rf {self.dir}/hf/hub/models--someone--finetune\n", out) + self.assertIn(f"rm -rf {self.dir}/hf/hub/models--Qwen--Qwen-Image-2.1-Turbo\n", out) + + def test_nothing_in_the_cache_nothing_to_name_and_the_switch_note_goes(self): + rc, out, calls = self.run_uninstall(image_enabled=False, text_enabled=True, note="someone/finetune") + self.assertEqual(rc, 0, out) + self.assertNotIn("rm -rf", out) + self.assertFalse((self.dir / "image-model-before-turbo").exists(), "the switch note outlived the lane") + + +class TheSwitchNoteAndAnInstall(unittest.TestCase): + """./switch-model.sh image-turbo writes down the checkpoint of the unit's own it leaves, + for `image` to bring back. An install that points the unit at another checkpoint makes + that note a stale one: `image` would then bring back a checkpoint from before it.""" + BLOCK = block("# A unit installed for another checkpoint", 'fi\nif [ -f "$INSTALLED" ] && sudo cmp -s "$RENDER"') + + def run_block(self, installed_model, model): + d = pathlib.Path(tempfile.mkdtemp(prefix="img-note-")) + (d / "unit").write_text(f"ExecStart=/x/sglang serve --model-path {installed_model} \\\n --port 30020\n") + (d / "image-model-before-turbo").write_text("someone/finetune\n") + unit_flag = next(ln for ln in TEXT.splitlines() if ln.startswith("unit_flag(){")) + script = (f'set -euo pipefail\nINSTALLED="{d}/unit"; CONFIG_DIR="{d}"; MODEL="{model}"\n' + + unit_flag + "\n" + self.BLOCK) + rc, out = bash(script, {"HOME": str(d)}) + return rc, out, (d / "image-model-before-turbo").exists() + + def test_another_checkpoint_drops_the_note(self): + rc, out, kept = self.run_block("Qwen/Qwen-Image-2.1-Turbo", "Qwen/Qwen-Image-2.1") + self.assertEqual(rc, 0, out) + self.assertFalse(kept) + + def test_an_update_of_the_same_checkpoint_keeps_it(self): + rc, out, kept = self.run_block("Qwen/Qwen-Image-2.1-Turbo", "Qwen/Qwen-Image-2.1-Turbo") + self.assertEqual(rc, 0, out) + self.assertTrue(kept) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_image_lane_removal.py b/tests/test_image_lane_removal.py index 69f64bc2..156ea241 100644 --- a/tests/test_image_lane_removal.py +++ b/tests/test_image_lane_removal.py @@ -33,6 +33,8 @@ def lane_dir(extra=True): for sub in ("venv/bin", "sglang/python"): (d / sub).mkdir(parents=True) (d / sub / "f").write_text("x") + # the wheel note install-image.sh writes beside them since v1.24 + (d / "sglang-wheel").write_text("0.5.21\n") if extra: (d / "my-other-project").mkdir() (d / "my-other-project/thesis.tex").write_text("years of work") @@ -52,7 +54,7 @@ class BothPathsRemoveOnlyTheLane(unittest.TestCase): ("uninstall.sh", lambda: removal(UNINSTALL, 'if [ -d "$IMAGE_LANE_DIR" ] && '), lambda d: {"IMAGE_LANE_DIR": d, "PRIV": "0", "PRIV_DONE": "0"}), ("install-image.sh --uninstall", lambda: removal(INSTALL_IMAGE, 'if [ -d "$LANE_DIR" ]; then'), - lambda d: {"LANE_DIR": d, "VENV": f"{d}/venv", "SRC": f"{d}/sglang"}), + lambda d: {"LANE_DIR": d, "VENV": f"{d}/venv", "SRC": f"{d}/sglang", "WHEEL_NOTE": f"{d}/sglang-wheel"}), ) def test_a_shared_directory_keeps_everything_else(self): @@ -63,6 +65,7 @@ class BothPathsRemoveOnlyTheLane(unittest.TestCase): self.assertEqual(rc, 0, out) self.assertFalse((d / "venv").exists()) self.assertFalse((d / "sglang").exists()) + self.assertFalse((d / "sglang-wheel").exists()) self.assertEqual((d / "my-other-project/thesis.tex").read_text(), "years of work") self.assertIn("did not put there", out) diff --git a/tests/test_image_turbo_switch.py b/tests/test_image_turbo_switch.py new file mode 100644 index 00000000..ece3279b --- /dev/null +++ b/tests/test_image_turbo_switch.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +"""./switch-model.sh image-turbo, and back: the image lane's two checkpoints. + +The Turbo (Qwen/Qwen-Image-2.1-Turbo) is Qwen's eight-step distillation of the lane's model. +A switch between the two rewrites the unit's --model-path and nothing else, fetches the +checkpoint at the revision the box serves of it (its refs/main; the installer's pin when +there is none) and points refs/main at a revision it fetched (the unit runs offline by +name), keeps a checkpoint the unit was installed with across a round trip through the +Turbo, and refuses the Turbo on a runtime that cannot read its sigma grid: there it would +load, answer 200 and sample on a uniform schedule it was not trained for. + +The script's own image block runs here, whole, against a fake unit, a fake cache, a fake +huggingface_hub and a fake runtime; sudo and systemctl are stubs that write down every call. +""" +import pathlib +import re +import subprocess +import tempfile +import textwrap +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +TEXT = (REPO / "switch-model.sh").read_text() +START = TEXT.index('if [ "$CHOICE" = "image" ] || [ "$CHOICE" = "image-turbo" ]; then') +END = TEXT.index("\n exit 0\nfi\n", START) + len("\n exit 0\nfi\n") +BLOCK = TEXT[START:END] +_lines = TEXT.splitlines(keepends=True) +_at = next(i for i, ln in enumerate(_lines) if ln.startswith("dl_free_gb(){")) +DLFREE = "".join(_lines[_at:_at + 2]) +PINS = dict(re.findall(r'^(IMAGE_MODEL_PIN|IMAGE_MODEL_PIN_REV|IMAGE_TURBO_PIN|IMAGE_TURBO_PIN_REV)="([^"]+)"', + (REPO / "install-image.sh").read_text(), re.M)) +BASE, TURBO = PINS["IMAGE_MODEL_PIN"], PINS["IMAGE_TURBO_PIN"] + +FAKE_HUB = ''' +import os, pathlib +def snapshot_download(repo, revision=None, local_files_only=False, **kw): + hub = pathlib.Path(os.environ["HF_HOME"]) / "hub" / ("models--" + repo.replace("/", "--")) + rev = revision or "main" + snap = hub / "snapshots" / (rev if len(rev) == 40 else "f" * 40) + with open(os.environ["FAKE_LOG"], "a") as f: + f.write(f"hub {repo} {rev} local={local_files_only}\\n") + if local_files_only and not snap.exists(): + raise FileNotFoundError(repo) + snap.mkdir(parents=True, exist_ok=True) + return str(snap) +''' +FAKE_CONSTANTS = ''' +import os +HF_HUB_CACHE = os.path.join(os.environ["HF_HOME"], "hub") +''' +# The runtime's three parts of sgl-project/sglang#43391, each present when FAKE_PARTS names +# it: image-sglang/turbo-grid-check.py reads them as the real runtime has them. +FAKE_CONFIG = ''' +import dataclasses, os +@dataclasses.dataclass +class QwenImage21PipelineConfig: + vae_precision: str = "bf16" + def prepare_sigmas(self, sigmas, n): + return sigmas if sigmas is not None else [1.0 - i / n for i in range(n)] +if "config" in os.environ.get("FAKE_PARTS", "").split(","): + @dataclasses.dataclass + class QwenImage21PipelineConfig(QwenImage21PipelineConfig): + sample_sigmas: list = None + def prepare_sigmas(self, sigmas, n): + return list(sigmas if sigmas is not None else self.sample_sigmas) +elif "config-field" in os.environ.get("FAKE_PARTS", "").split(","): + # the field without the behaviour: the grid kept and never sampled on + @dataclasses.dataclass + class QwenImage21PipelineConfig(QwenImage21PipelineConfig): + sample_sigmas: list = None +''' +FAKE_PART = ''' +import os +if "{part}" in os.environ.get("FAKE_PARTS", "").split(","): + from ._with import {cls} +else: + from ._without import {cls} +''' +FAKE_PIPELINE = ("class QwenImage21Pipeline:\n def _load_config(self):\n return {\"sample_sigmas\": None}\n", + "class QwenImage21Pipeline:\n def _load_config(self):\n return {}\n") +FAKE_STAGE = ("class QwenImage21InputValidationStage:\n def forward(self, batch, args):\n" + " return args.pipeline_config.prepare_sigmas(None, 8)\n", + "class QwenImage21InputValidationStage:\n def forward(self, batch, args):\n return batch\n") + + +def sandbox(model, *, grid=True, cached=(), free_gb=500, enabled=(), active=(), refs=(), blobs=(), unit_hf="hf"): + d = pathlib.Path(tempfile.mkdtemp(prefix="sw-img-")) + fake = d / "fake" + (fake / "huggingface_hub").mkdir(parents=True) + (fake / "huggingface_hub" / "__init__.py").write_text(FAKE_HUB) + (fake / "huggingface_hub" / "constants.py").write_text(FAKE_CONSTANTS) + cfg = fake / "sglang/multimodal_gen/configs/pipeline_configs" + cfg.mkdir(parents=True) + for p in (fake / "sglang", fake / "sglang/multimodal_gen", fake / "sglang/multimodal_gen/configs", cfg): + (p / "__init__.py").write_text("") + (cfg / "qwen_image21.py").write_text(FAKE_CONFIG) + rt = fake / "sglang/multimodal_gen/runtime" + for part, cls, pkg, (with_, without) in ( + ("pipeline", "QwenImage21Pipeline", rt / "pipelines/qwen_image21", FAKE_PIPELINE), + ("stage", "QwenImage21InputValidationStage", + rt / "pipelines_core/stages/model_specific_stages/qwen_image21", FAKE_STAGE)): + pkg.mkdir(parents=True) + q = pkg + while q != fake / "sglang/multimodal_gen": + (q / "__init__.py").exists() or (q / "__init__.py").write_text("") + q = q.parent + (pkg / "__init__.py").write_text(FAKE_PART.format(part=part, cls=cls)) + (pkg / "_with.py").write_text(with_) + (pkg / "_without.py").write_text(without) + venv = d / "lane/venv/bin" + venv.mkdir(parents=True) + (venv / "python").write_text(f'#!/bin/sh\nPYTHONPATH="{fake}" exec /usr/bin/python3 "$@"\n') + (venv / "python").chmod(0o755) + for repo, rev in cached: + (d / unit_hf / "hub" / ("models--" + repo.replace("/", "--")) / "snapshots" / rev).mkdir(parents=True) + for repo, ref in refs: + r = d / unit_hf / "hub" / ("models--" + repo.replace("/", "--")) / "refs/main" + r.parent.mkdir(parents=True, exist_ok=True) + r.write_text(ref) + # (repo, GiB): a sparse blob of that apparent size, what a fetch that stopped leaves + for repo, gib in blobs: + b = d / unit_hf / "hub" / ("models--" + repo.replace("/", "--")) / "blobs" + b.mkdir(parents=True, exist_ok=True) + with open(b / ("0" * 64 + ".incomplete"), "wb") as f: + f.truncate(gib * 2**30) + unit = d / "etc/qwen38-image.service" + unit.parent.mkdir() + unit.write_text(textwrap.dedent(f"""\ + [Service] + WorkingDirectory={d}/lane + Environment=HF_HOME={d}/{unit_hf} + ExecStart={d}/lane/venv/bin/sglang serve \\ + --model-path {model} \\ + --performance-mode speed \\ + --host 127.0.0.1 --port 30020 + """)) + bin_ = d / "bin" + bin_.mkdir() + (bin_ / "sudo").write_text(textwrap.dedent(f"""\ + #!/bin/sh + echo "sudo $*" >> "{d}/log" + if [ "$1" = install ]; then cp "$4" "$5"; fi + exit 0 + """)) + en = " ".join(enabled) or "none" + ac = " ".join(active) or "none" + (bin_ / "systemctl").write_text(textwrap.dedent(f"""\ + #!/bin/sh + case "$1" in + is-enabled) for u in {en}; do [ "$3" = "$u" ] || [ "$2" = "$u" ] && exit 0; done; exit 1 ;; + is-active) for u in {ac}; do [ "$3" = "$u" ] || [ "$2" = "$u" ] && exit 0; done; exit 1 ;; + esac + exit 0 + """)) + (bin_ / "df").write_text(f"#!/bin/sh\necho Avail; echo {free_gb}G\n") + for f in ("sudo", "systemctl", "df"): + (bin_ / f).chmod(0o755) + return d, unit, grid + + +def run(d, unit, grid, choice): + script = ('set -euo pipefail\ndie(){ echo "DIE: $*"; exit 1; }\n' + f'CHOICE={choice}; REPO_DIR="{REPO}"; CONFIG_DIR="{d}/cfg"; HF_CACHE="{d}/hf"; DL_NO_BARS=1\n' + f'IMAGE_UNIT="{unit}"; IMAGE_UNIT_NAME=qwen38-image.service\n' + f'IMG_STAGE="$CONFIG_DIR/qwen38-image.service.switch-stage"\n' + 'mkdir -p "$CONFIG_DIR"\ndisable_rollback_lane(){ :; }\n' + + DLFREE + BLOCK) + parts = grid if isinstance(grid, str) else "config,pipeline,stage" if grid else "" + env = {"PATH": f"{d}/bin:/usr/bin:/bin", "HOME": str(d), "FAKE_LOG": str(d / "log"), + "FAKE_PARTS": parts} + r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60, env=env) + log = (d / "log").read_text() if (d / "log").exists() else "" + return r.returncode, r.stdout + r.stderr, log + + +def model_of(unit): + return re.search(r"--model-path (\S+)", unit.read_text()).group(1) + + +class TheTurboTarget(unittest.TestCase): + def test_the_pins_are_full_commits(self): + for k in ("IMAGE_MODEL_PIN_REV", "IMAGE_TURBO_PIN_REV"): + self.assertRegex(PINS[k], r"^[0-9a-f]{40}$", k) + self.assertEqual(TURBO, "Qwen/Qwen-Image-2.1-Turbo") + + def test_base_to_turbo_rewrites_the_model_path_and_nothing_else(self): + d, unit, g = sandbox(BASE) + before = unit.read_text() + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), TURBO) + self.assertEqual(unit.read_text(), before.replace(f"--model-path {BASE} ", f"--model-path {TURBO} ")) + self.assertIn(f"sudo install -m 644 {d}/cfg/qwen38-image.service.switch-stage {unit}", log) + self.assertIn("sudo systemctl daemon-reload", log) + self.assertFalse((d / "cfg/qwen38-image.service.switch-stage").exists(), "the stage is left behind") + + def test_the_turbo_is_fetched_at_its_pin_and_served_by_that_ref(self): + d, unit, g = sandbox(BASE) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {TURBO} {PINS['IMAGE_TURBO_PIN_REV']} local=True", log) + self.assertIn(f"hub {TURBO} {PINS['IMAGE_TURBO_PIN_REV']} local=False", log) + ref = d / "hf/hub/models--Qwen--Qwen-Image-2.1-Turbo/refs/main" + self.assertEqual(ref.read_text(), PINS["IMAGE_TURBO_PIN_REV"]) + + def test_a_cached_turbo_is_not_fetched_again(self): + d, unit, g = sandbox(BASE, cached=[(TURBO, PINS["IMAGE_TURBO_PIN_REV"])]) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertNotIn("local=False", log) + + def test_a_runtime_without_the_grid_is_refused_before_anything_changes(self): + d, unit, _ = sandbox(BASE) + before = unit.read_text() + rc, out, log = run(d, unit, False, "image-turbo") + self.assertNotEqual(rc, 0) + self.assertIn("cannot sample on the Turbo's eight-step grid", out) + self.assertIn("its pipeline config has no place for a sigma grid", out) + self.assertEqual(unit.read_text(), before) + self.assertNotIn("sudo", log) + self.assertNotIn("hub ", log) + + def test_each_part_of_the_fix_is_needed(self): + """A patch that does not apply to a new pin is only a note in the installer: a runtime + with the config's field and not the rest would still sample on a uniform schedule.""" + for parts, why in (("config", "its pipeline does not read the grid from model_index.json"), + ("config,pipeline", "its input stage does not take the steps from the grid"), + ("pipeline,stage", "its pipeline config has no place for a sigma grid"), + ("config-field,pipeline,stage", "its pipeline config does not sample on the grid it holds")): + d, unit, _ = sandbox(BASE) + rc, out, log = run(d, unit, parts, "image-turbo") + self.assertNotEqual(rc, 0, parts) + self.assertIn(why, out, parts) + self.assertEqual(model_of(unit), BASE, parts) + + def test_turbo_back_to_base(self): + """The base's name is a prefix of the Turbo's: the rewrite must not leave '-Turbo'.""" + d, unit, g = sandbox(TURBO) + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), BASE) + self.assertNotIn("Turbo", unit.read_text()) + self.assertIn(f"hub {BASE} {PINS['IMAGE_MODEL_PIN_REV']} local=True", log) + + def test_base_to_base_writes_no_unit(self): + d, unit, g = sandbox(BASE, cached=[(BASE, PINS["IMAGE_MODEL_PIN_REV"])]) + before = unit.read_text() + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertEqual(unit.read_text(), before) + self.assertNotIn("sudo install", log) + self.assertIn("sudo systemctl enable qwen38-image.service", log) + + def test_a_custom_checkpoint_is_kept_by_image_and_fetched_at_main(self): + d, unit, g = sandbox("someone/finetune") + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), "someone/finetune") + self.assertIn("hub someone/finetune main local=True", log) + self.assertNotIn("sudo install", log) + + def test_no_room_stops_before_the_first_byte(self): + d, unit, g = sandbox(BASE, free_gb=20) + before = unit.read_text() + rc, out, log = run(d, unit, g, "image-turbo") + self.assertNotEqual(rc, 0) + self.assertIn("needs about 34 GB", out) + self.assertNotIn("local=False", log) + self.assertEqual(unit.read_text(), before) + + def test_a_serving_image_lane_is_told_to_restart(self): + d, unit, g = sandbox(BASE, active=("qwen38-image.service",)) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertIn("sudo systemctl restart qwen38-image.service (it serves the previous checkpoint until then)", out) + self.assertNotIn("already named this checkpoint", out) + + def test_from_a_text_lane_the_text_lane_is_disabled_and_remembered(self): + d, unit, g = sandbox(BASE, enabled=("qwen38-sglang.service",), active=("qwen38-sglang.service",)) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertIn("sudo systemctl disable qwen38-sglang.service", log) + self.assertEqual((d / "cfg/lane-before-image").read_text().strip(), "qwen38-sglang.service") + self.assertIn("sudo systemctl stop qwen38-sglang.service && sudo systemctl start qwen38-image.service", out) + + +class TheServedRevision(unittest.TestCase): + """refs/main is what the offline unit serves: an install made with IMAGE_MODEL_REV= stays + served through a switch, and the pin answers only when there is no ref to read.""" + OTHER = "a" * 40 + + def test_a_ref_the_box_serves_is_kept_not_moved_to_the_pin(self): + d, unit, g = sandbox(TURBO, cached=[(BASE, self.OTHER)], refs=[(BASE, self.OTHER)]) + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {BASE} {self.OTHER} local=True", log) + self.assertNotIn(PINS["IMAGE_MODEL_PIN_REV"], log) + self.assertNotIn("local=False", log) + self.assertEqual((d / "hf/hub/models--Qwen--Qwen-Image-2.1/refs/main").read_text(), self.OTHER) + self.assertEqual(model_of(unit), BASE) + + def test_the_ref_is_read_where_the_unit_keeps_its_cache(self): + """The unit's own HF_HOME, which can be another disk than the switch's HF_CACHE.""" + d, unit, g = sandbox(TURBO, unit_hf="hf2", cached=[(BASE, self.OTHER)], refs=[(BASE, self.OTHER)]) + elsewhere = d / "hf/hub/models--Qwen--Qwen-Image-2.1/refs/main" + elsewhere.parent.mkdir(parents=True) + elsewhere.write_text("b" * 40) + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {BASE} {self.OTHER} local=True", log) + self.assertNotIn("b" * 40, log) + + def test_the_turbo_too(self): + d, unit, g = sandbox(BASE, cached=[(TURBO, self.OTHER)], refs=[(TURBO, self.OTHER)]) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {TURBO} {self.OTHER} local=True", log) + self.assertNotIn(PINS["IMAGE_TURBO_PIN_REV"], log) + + def test_a_ref_that_holds_no_commit_falls_back_to_the_pin_and_is_repaired(self): + d, unit, g = sandbox(TURBO, refs=[(BASE, "main\n")]) + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {BASE} {PINS['IMAGE_MODEL_PIN_REV']} local=True", log) + self.assertEqual((d / "hf/hub/models--Qwen--Qwen-Image-2.1/refs/main").read_text(), + PINS["IMAGE_MODEL_PIN_REV"]) + + +class ACheckpointOfItsOwn(unittest.TestCase): + """A unit installed with IMAGE_MODEL= serves a checkpoint that is neither the base nor the + Turbo: image-turbo and back again brings that one back, not the base.""" + + def test_the_round_trip_brings_it_back(self): + d, unit, g = sandbox("someone/finetune") + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), TURBO) + self.assertEqual((d / "cfg/image-model-before-turbo").read_text().strip(), "someone/finetune") + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), "someone/finetune") + self.assertIn("hub someone/finetune main local=True", log) + self.assertNotIn(f"hub {BASE} ", log) + self.assertFalse((d / "cfg/image-model-before-turbo").exists(), "the note outlived the way back") + + def test_from_the_base_nothing_is_written_down_and_image_is_the_base(self): + d, unit, g = sandbox(BASE) + (d / "cfg").mkdir() + (d / "cfg/image-model-before-turbo").write_text("someone/stale\n") + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertFalse((d / "cfg/image-model-before-turbo").exists(), "a stale note survived a switch from the base") + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertEqual(model_of(unit), BASE) + + +class TheRoomCheck(unittest.TestCase): + """About 34 GB for a whole checkpoint, less what the cache already holds of it.""" + + def test_a_fetch_that_stopped_needs_only_the_rest(self): + d, unit, g = sandbox(BASE, free_gb=20, blobs=[(TURBO, 30)]) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertEqual(rc, 0, out) + self.assertIn(f"hub {TURBO} {PINS['IMAGE_TURBO_PIN_REV']} local=False", log) + + def test_the_rest_must_still_fit(self): + d, unit, g = sandbox(BASE, free_gb=3, blobs=[(TURBO, 30)]) + rc, out, log = run(d, unit, g, "image-turbo") + self.assertNotEqual(rc, 0) + self.assertIn("needs about 4 GB more", out) + self.assertNotIn("local=False", log) + self.assertEqual(model_of(unit), BASE) + + +class TheRestartHint(unittest.TestCase): + def test_no_rewrite_no_claim_that_it_serves_the_previous_checkpoint(self): + d, unit, g = sandbox(BASE, cached=[(BASE, PINS["IMAGE_MODEL_PIN_REV"])], active=("qwen38-image.service",)) + rc, out, log = run(d, unit, g, "image") + self.assertEqual(rc, 0, out) + self.assertNotIn("serves the previous checkpoint", out) + self.assertIn("already named this checkpoint", out) + + +class TheTargetIsKnownEverywhere(unittest.TestCase): + def test_the_usage_line_and_the_cockpit_offer_it(self): + self.assertIn("|image|image-turbo|video)", TEXT) + cockpit = (REPO / "dashboard/cockpit.py").read_text() + self.assertIn('"image-turbo"', cockpit) + self.assertIn(f'IMAGE_TURBO_MODEL = "{TURBO}"', cockpit) + + def test_the_sudoers_line_is_the_stage_the_script_uses(self): + sud = (REPO / "dashboard/sudoers-cockpit.template").read_text() + self.assertIn("NOPASSWD: /usr/bin/install -m 644 __HOME__/.config/qwen38/qwen38-image.service.switch-stage " + "/etc/systemd/system/qwen38-image.service", sud) + self.assertRegex(TEXT, r'(?m)^IMG_STAGE="\$CONFIG_DIR/qwen38-image\.service\.switch-stage"$') + + def test_uninstall_knows_the_turbo(self): + self.assertIn(TURBO, (REPO / "uninstall.sh").read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mirror_pins.py b/tests/test_mirror_pins.py index 6957e545..1e5c5e85 100644 --- a/tests/test_mirror_pins.py +++ b/tests/test_mirror_pins.py @@ -136,8 +136,8 @@ class TheMirrorPins(unittest.TestCase): rc, out = self.run_mirror() self.assertEqual(rc, 0, out) models = re.findall(r"^\s+mirror: (\S+) @ upstream-", out, re.M) - self.assertEqual(len(models), 11, out) # nine text checkpoints and the two diffusion lanes' - self.assertEqual(len(set(models)), 11, models) + self.assertEqual(len(models), 12, out) # nine text checkpoints and the diffusion lanes' three + self.assertEqual(len(set(models)), 12, models) # every checkpoint has its license row, and every row names a checkpoint the script copies labels = re.findall(r"^ model\s+(\S+)$", out, re.M) rows = [r for r in re.findall(r"^\| ([a-z0-9-]+) \| [^|]+ \| [^|]+ \|$", self.mirror_md.read_text(), re.M) diff --git a/uninstall.sh b/uninstall.sh index e4661d18..3955e6fc 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -50,7 +50,7 @@ done # digest: a digest pull leaves no tag behind. LOCAL_IMAGE_REPOS="qwen38-dflash2 qwen38-flash qwen38-pinned" # qwen38-dflash2 is the pre-v1.14 27B overlay, retired but still deletable; qwen38-pinned (v1.18.6) tags the digest pulls BASE_IMAGES="lmsysorg/sglang:v0.5.21 lmsysorg/sglang@sha256:b1259f3ea3275f66237c498ea388919729018bc9f01c3d638391e06e2cf3f469 lmsysorg/sglang:v0.5.19 lmsysorg/sglang@sha256:d6e7288627be8b02be88e4bba38e73f6d50e2826869f753c13a4c4385ab3eda9 lmsysorg/sglang:qwen38-27b lmsysorg/sglang@sha256:febfb971c7352570fc445c466ebd6ffc9d896024958e544a60f2137fd85856b1 lmsysorg/sglang:qwen38flashnext lmsysorg/sglang@sha256:12d3392bdc8be8d35e9a95f191df6aef99c5114bdbefd41bfdc7e760e6d25ec1 lmsysorg/sglang@sha256:9d2a843c706c74bc259c0d9abf360551eb2734e1e7d255ab012a6965f10480b6 lmsysorg/sglang@sha256:cb6ed363800a5bea98ac90b4c6447e9ba66cef7db881ac1f108046b6622d22b8 lmsysorg/sglang@sha256:616a3e97f45191af975896cfa644279096cb31bd408a071c2e99ca7209c3cafe vllm/vllm-openai:qwen38-flash-next vllm/vllm-openai@sha256:fc120ece0a388cc0aa1caad4a9f1cd92113484ab7ec2fd0efadd62585be05bf8" -HF_REPOS="RadixArk/Qwen3.8-27B-NVFP4 edp1096/Huihui-RadixArk-Qwen3.8-27B-abliterated-NVFP4 Qwen/Qwen3.8-27B-FP8 edp1096/Huihui-Qwen3.8-27B-abliterated-FP8 RadixArk/Qwen3.8-27B-DSpark z-lab/Qwen3.8-27B-DFlash2 maurienne-ai/Qwen3.8-27B-DFlash2-NVFP4-RTNcal RadixArk/Qwen3.8-Flash-Next-NVFP4 nvidia/Qwen3.8-Flash-Next-NVFP4 dealignai/Qwen3.8-Flash-Next-ABLITERATED-NVFP4 Qwen/Qwen-Image-2.1 MiniMaxAI/MiniMax-H3" +HF_REPOS="RadixArk/Qwen3.8-27B-NVFP4 edp1096/Huihui-RadixArk-Qwen3.8-27B-abliterated-NVFP4 Qwen/Qwen3.8-27B-FP8 edp1096/Huihui-Qwen3.8-27B-abliterated-FP8 RadixArk/Qwen3.8-27B-DSpark z-lab/Qwen3.8-27B-DFlash2 maurienne-ai/Qwen3.8-27B-DFlash2-NVFP4-RTNcal RadixArk/Qwen3.8-Flash-Next-NVFP4 nvidia/Qwen3.8-Flash-Next-NVFP4 dealignai/Qwen3.8-Flash-Next-ABLITERATED-NVFP4 Qwen/Qwen-Image-2.1 Qwen/Qwen-Image-2.1-Turbo MiniMaxAI/MiniMax-H3" FOUND_IMAGES=() # "ref|size|every ref", deduplicated by image ID (a tag and its digest are one image) # Every reference Docker keeps for one image. A digest-pulled image carries its digest @@ -202,7 +202,7 @@ fi # review, 2026-09-24). The directory itself goes only once it is empty. # Left alone when sudo was refused: the image lane may still be running from it. if [ -d "$IMAGE_LANE_DIR" ] && { [ "$PRIV" -eq 0 ] || [ "$PRIV_DONE" -eq 1 ]; }; then - rm -rf "$IMAGE_LANE_DIR/venv" "$IMAGE_LANE_DIR/sglang" + rm -rf "$IMAGE_LANE_DIR/venv" "$IMAGE_LANE_DIR/sglang" "$IMAGE_LANE_DIR/sglang-wheel" rmdir "$IMAGE_LANE_DIR" 2>/dev/null || echo "kept $IMAGE_LANE_DIR: it holds files the image lane did not put there" fi # The video lane's runtime, under the same rule: only venv/ and sglang/, and the