diff --git a/build-token-map.py b/build-token-map.py index e1c50bb9..2dc39050 100755 --- a/build-token-map.py +++ b/build-token-map.py @@ -223,14 +223,21 @@ def main() -> None: out_dir = os.path.dirname(os.path.abspath(args.out)) if out_dir and not os.path.isdir(out_dir): die(f"output directory does not exist: {out_dir}") - torch.save(ids, args.out) + # Written beside it, read back, and only then put in place: install.sh and prepare-lane.sh + # take a map that is there (lanes.sh, [ -s ]) for built, and a run stopped mid-write (a job + # the cockpit stops, a disk that fills) left one half written that the launcher passed to + # the engine at every start (found in review, 2026-10-15). + tmp = args.out + ".tmp" + torch.save(ids, tmp) # Read it back the way SGLang will, so a map that cannot be loaded fails here # and not nine minutes into a boot. - reread = torch.load(args.out, weights_only=True) + reread = torch.load(tmp, weights_only=True) back = torch.tensor(reread, dtype=torch.int64) if back.numel() != args.size or int(back.min()) < 0 or int(back.max()) >= vocab_size: + os.unlink(tmp) die("the written map does not read back as SGLang would read it") + os.replace(tmp, args.out) covered = sum(n for tid, n in counts.items() if tid in seen) print(f"vocabulary {vocab_size}") diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index e26a3908..06de892d 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -1983,8 +1983,15 @@ def engine_image(text: str): def draft_in_cache(text: str) -> bool: - """Whether the DFlash2 draft a 27B unit names is in the cache it mounts, at its revision (a - ref such as main read through refs/): its config and a weights file, as lanes.sh reads it.""" + """Whether the DFlash2 draft a 27B unit names is whole in the cache it mounts, at its revision + (a ref such as main read through refs/), and its config set for the window the unit serves: + its config, every weight file its index names or one when it has none, a link counting once + its blob is there, and the YaRN window in its config when the unit serves 1M, none otherwise + (patch-yarn.py, which prepare-lane.sh runs after the fetch). A config with one weight file of + two, a link to a blob gone, or a fetch whose patch failed read as prepared: the next Load + skipped the preparation and started the 1M unit on a native draft (found in review, + 2026-10-15). lanes.sh asks less (a config and a weights file): install.sh reads it to update + a lane begun on the box whole, and that run sets the config again.""" repo = re.search(r"--speculative-draft-model-path (\S+)", text) if not repo: return True @@ -1998,18 +2005,24 @@ def draft_in_cache(text: str) -> bool: if (snap / "refs" / r).is_file(): r = (snap / "refs" / r).read_text().strip() d = snap / "snapshots" / r - return (d / "config.json").is_file() and any(d.glob("*.safetensors")) - except OSError: + if not (d / "config.json").is_file() or not rg.snapshot_complete(d): + return False + cfg = json.loads((d / "config.json").read_text()) + except (OSError, ValueError): return False + tc = cfg.get("text_config", cfg) if isinstance(cfg, dict) else {} + return (isinstance(tc, dict) and tc.get("max_position_embeddings") == 1010000) == ("--context-length 1010000" in text) def lane_prepared(lane: str): - """Whether a lane installed on demand is prepared, as install.sh reads it: the venv and the - note of its wheel (written once the wheel is in) for the image and video lanes, the image - its unit names for Kolibri; for the other text lane beside the lane that serves, the image - its launcher (flash) or unit (27B) runs, with the draft vocabulary the flash launcher waits - for, when it waits for one, and the 27B's DFlash2 draft. None when the lane is not - installed (no unit, no launcher).""" + """Whether a lane installed on demand is built, so that its Load does not prepare it first: + the venv and the note of its wheel, which its installer writes once the whole runtime is in, + for the image and video lanes; the image its unit names for Kolibri, tagged once built; for + the other text lane beside the lane that serves, the image its launcher (flash) or unit + (27B) runs, with the draft vocabulary the flash launcher waits for, when it waits for one, + and the 27B's DFlash2 draft, whole and set for its window (draft_in_cache). install.sh asks + less to update a lane whole (its runtime begun: a venv, an image); this asks what a Load + needs. None when the lane is not installed (no unit, no launcher).""" unit = {"image": IMAGE_UNIT_PATH, "video": VIDEO_UNIT_PATH, "kolibri": KOLIBRI_UNIT_PATH, "flash": UNIT_PATHS["qwen38-flash.service"], "27b": UNIT_PATHS["qwen38-sglang.service"]}[lane] try: @@ -2024,7 +2037,12 @@ def lane_prepared(lane: str): if lane == "27b": return draft_in_cache(text) waits = re.search(r'\[ -s "([^"]+)" \] && TIER\+=\(--speculative-token-map', text) - return not waits or Path(waits.group(1)).exists() + if not waits: + return True + try: + return Path(waits.group(1)).stat().st_size > 0 # [ -s ]: an empty one is skipped + except OSError: + return False if lane == "kolibri": m = re.search(r"qwen38-kolibri:\S+", text) return bool(m) and run(["docker", "image", "inspect", "--format", "{{.Id}}", m.group(0)], diff --git a/dashboard/registry.py b/dashboard/registry.py index d8c83226..072ab19d 100644 --- a/dashboard/registry.py +++ b/dashboard/registry.py @@ -114,7 +114,8 @@ def snapshot_complete(snap: Path, allow=None) -> bool: the lane's checkpoint incomplete (found building the models view, 2026-10-14).""" indexes = [p for p in snap.rglob("*.safetensors.index.json") if allowed(p.relative_to(snap).as_posix(), allow)] if not indexes: - return any(allowed(p.relative_to(snap).as_posix(), allow) for p in snap.rglob("*.safetensors")) + # a link counts once its blob is there, as in an index (a link to a blob gone did) + return any(allowed(p.relative_to(snap).as_posix(), allow) and p.exists() for p in snap.rglob("*.safetensors")) for idx in indexes: try: shards = set(json.loads(idx.read_text())["weight_map"].values()) diff --git a/dashboard/tests/test_cockpit_prepare.py b/dashboard/tests/test_cockpit_prepare.py index f7940d80..151786bf 100644 --- a/dashboard/tests/test_cockpit_prepare.py +++ b/dashboard/tests/test_cockpit_prepare.py @@ -123,6 +123,54 @@ class Prepare(unittest.TestCase): self.assertIs(self.cp.lane_prepared("27b"), True) self.assertIs(self.cp.collect_lanes_ready()["27b"], True) + def test_an_empty_vocabulary_is_none(self): + # [ -s ]: the launcher skips an empty one, and so does this (found in review, 2026-10-15) + img, vocab = "lmsysorg/sglang@sha256:" + "d" * 64, self.tmp / "token-map-65536.pt" + self.images.add(img) + (self.units / "launch-flash.sh").write_text( + self.runs(img, f'[ -s "{vocab}" ] && TIER+=(--speculative-token-map /out/token-map-65536.pt)\n')) + vocab.write_text("") + self.assertIs(self.cp.lane_prepared("flash"), False) + vocab.write_text("map") + self.assertIs(self.cp.lane_prepared("flash"), True) + + def test_a_draft_half_there_or_set_for_another_window_is_not_prepared(self): + # one shard of two, a link to a blob gone, a config set for another window than its unit + # serves: each read as prepared, and the next Load started the 1M unit on a native draft + # (found in review, 2026-10-15) + img, hf, rev = "lmsysorg/sglang@sha256:" + "f" * 64, self.tmp / "hf-draft", "a" * 40 + shutil.rmtree(hf, ignore_errors=True) + self.images.add(img) + unit = self.units / "qwen38-sglang.service" + + def write(window): + unit.write_text(self.runs(img, f" -v {hf}:/root/.cache/huggingface \\\n", + " --context-length 1010000 \\\n" if window == "1m" else "", + " --speculative-draft-model-path org/draft \\\n", + f" --speculative-draft-model-revision {rev} \\\n")) + repo = hf / "hub" / "models--org--draft" + snap, blobs = repo / "snapshots" / rev, repo / "blobs" + snap.mkdir(parents=True) + blobs.mkdir() + (snap / "config.json").write_text('{"max_position_embeddings": 262144}') + (snap / "model.safetensors.index.json").write_text( + '{"weight_map": {"a": "model-1.safetensors", "b": "model-2.safetensors"}}') + (snap / "model-1.safetensors").write_text("w") + write("native") + self.assertIs(self.cp.lane_prepared("27b"), False) # one shard of two + (blobs / "b2").write_text("w") + (snap / "model-2.safetensors").symlink_to(blobs / "b2") + self.assertIs(self.cp.lane_prepared("27b"), True) + (blobs / "b2").unlink() + self.assertIs(self.cp.lane_prepared("27b"), False) # a link to a blob gone + (blobs / "b2").write_text("w") + write("1m") + self.assertIs(self.cp.lane_prepared("27b"), False) # native config, 1M unit + (snap / "config.json").write_text('{"max_position_embeddings": 1010000}') + self.assertIs(self.cp.lane_prepared("27b"), True) + write("native") + self.assertIs(self.cp.lane_prepared("27b"), False) # 1M config, native unit + def test_a_venv_without_its_wheels_note_is_not_prepared(self): # the venv is made first and the wheel's note written once the wheel is in self.lane("image", built=True) diff --git a/dashboard/tests/test_registry.py b/dashboard/tests/test_registry.py index 68a527d7..d60b527a 100644 --- a/dashboard/tests/test_registry.py +++ b/dashboard/tests/test_registry.py @@ -16,6 +16,7 @@ target cannot be added to the installer and forgotten in the registry. """ import re import sys +import tempfile import unittest from pathlib import Path @@ -230,6 +231,21 @@ class CompleteForWhatTheLaneServes(unittest.TestCase): with self.subTest(parts=parts, allow=allow): self.assertEqual(rg.snapshot_complete(s, allow), cf.complete(s, allow)) + def test_a_link_counts_once_its_blob_is_there_with_no_index_too(self): + # a snapshot of single files whose link points at a blob gone read as whole here, while + # ckpt-fetch.py, which fetches it, read it as missing (found in review, 2026-10-15) + cf = self.ckpt_fetch() + d = Path(tempfile.mkdtemp(prefix="reg-link-")) + (d / "blobs").mkdir() + s = d / "snapshots" / ("a" * 40) + s.mkdir(parents=True) + (s / "model.safetensors").symlink_to(d / "blobs" / "b1") + self.assertFalse(rg.snapshot_complete(s)) + self.assertEqual(rg.snapshot_complete(s), cf.complete(s)) + (d / "blobs" / "b1").write_text("w") + self.assertTrue(rg.snapshot_complete(s)) + self.assertEqual(rg.snapshot_complete(s), cf.complete(s)) + def test_the_video_lane_patterns_are_the_switchs_own(self): sw = (REPO / "switch-model.sh").read_text() self.assertEqual(rg.video_allow(sw, "fl2va")[0], "FL2VA/*") diff --git a/install-image.sh b/install-image.sh index dc4b416e..6d403d9d 100755 --- a/install-image.sh +++ b/install-image.sh @@ -305,12 +305,13 @@ step "3/6 SGLang Diffusion (released wheel first, then the pinned source over it # 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. +# down once the whole runtime is in (below, after the registry check); a venv from before +# that note, or one a run left half built, has none and takes the wheel again. 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"; touch "$RUNTIME_NOTE" + touch "$RUNTIME_NOTE" fi if [ ! -d "$SRC/.git" ]; then git clone --quiet https://github.com/sgl-project/sglang "$SRC" || die "could not clone SGLang." @@ -408,6 +409,14 @@ if [ "$MODEL" = "$IMAGE_TURBO_PIN" ]; then || 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 +# The runtime is whole: its note says so, and it is what the cockpit and install.sh read as +# this lane prepared. Written last, so a run that stops on the way (a clone that fails, a +# patch, the overlay, the registry) leaves a lane its next Load prepares again, not one it +# takes for built and serves on the bare wheel (found in review, 2026-10-15). And only when it +# changes: its date is one of the runtime's (LANE_FILES, the cockpit's stale-runtime check), and +# rewritten at every run it told a serving lane it ran older files, at each update (found in +# review of that fix, the same day). +[ "$(cat "$WHEEL_NOTE" 2>/dev/null)" = "$WHEEL" ] || printf '%s\n' "$WHEEL" > "$WHEEL_NOTE" if [ "$MODE" = prepare ]; then step "Done: the image lane's runtime is ready; its Load fetches the checkpoint and starts it" diff --git a/install-video.sh b/install-video.sh index ac72f5f8..40b1b536 100755 --- a/install-video.sh +++ b/install-video.sh @@ -302,13 +302,13 @@ step "3/6 SGLang Diffusion (released wheel first, then the pinned source over it # runtime without those kernels and the server dies on the first request. # 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, as in install-image.sh: the -# version installed is written down, and a venv from before this has no note and takes the -# wheel once. +# version installed is written down once the whole runtime is in (below, after the registry +# check), and a venv from before that note, or one a run left half built, takes the wheel again. 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"; touch "$RUNTIME_NOTE" + touch "$RUNTIME_NOTE" fi if [ ! -d "$SRC/.git" ]; then git clone --quiet https://github.com/sgl-project/sglang "$SRC" || die "could not clone SGLang." @@ -394,6 +394,14 @@ if name != "MiniMaxH3Pipeline" or registry.get_pipeline_class(name) is not MiniM src = pathlib.Path(sglang.__file__).parent print(f" runtime: {src}") PY +# The runtime is whole: its note says so, and it is what the cockpit and install.sh read as +# this lane prepared. Written last, so a run that stops on the way (a clone that fails, a +# patch, the overlay, the registry) leaves a lane its next Load prepares again, not one it +# takes for built and serves on the bare wheel (found in review, 2026-10-15). And only when it +# changes: its date is one of the runtime's (LANE_FILES, the cockpit's stale-runtime check), and +# rewritten at every run it told a serving lane it ran older files, at each update (found in +# review of that fix, the same day). +[ "$(cat "$WHEEL_NOTE" 2>/dev/null)" = "$WHEEL" ] || printf '%s\n' "$WHEEL" > "$WHEEL_NOTE" step "4/6 Checkpoint ($MODEL at ${MODEL_REV:0:12}, one-time, resumable)" # Only the partition this lane serves is fetched, by allowlist. The repo holds both diff --git a/tests/test_lane_on_demand.py b/tests/test_lane_on_demand.py index 0cfe9b30..b6b9964f 100644 --- a/tests/test_lane_on_demand.py +++ b/tests/test_lane_on_demand.py @@ -129,6 +129,53 @@ class TheImageAndVideoLanesInTwoHalves(unittest.TestCase): self.assertFalse([c for c in calls if c.startswith(("sudo ", "systemctl ", "docker "))], calls) self.assertFalse((box.units / unit).exists(), "--prepare wrote the unit") self.assertFalse([c for c in calls if "ckpt-fetch.py" in c], calls) + def test_a_preparation_stopped_on_the_way_leaves_no_note(self): + # the note is what says prepared: a run that stops after the wheel (here its clone fails) + # leaves none, and the next Load prepares again instead of serving the bare wheel, with + # none of the patches (found in review, 2026-10-15: the note came right after the wheel) + no_clone = FAKE_GIT.replace('if [ "$1" = clone ]; then mkdir -p "${@: -1}/.git"; exit 0; fi', + 'if [ "$1" = clone ]; then exit 128; fi') + assert no_clone != FAKE_GIT + for installer, lane, _unit in LANES_IN_TWO_HALVES: + with self.subTest(installer=installer): + box = Box(installer) + (box.bin / "git").write_text(no_clone) + rc, out, calls = box.run("--prepare") + self.assertNotEqual(rc, 0, out) + self.assertIn("could not clone SGLang", out) + self.assertTrue([c for c in calls if "sglang[diffusion]" in c], calls) # the wheel went in + self.assertTrue((box.home / lane / "venv/bin/python").exists(), out) + self.assertFalse((box.home / lane / "sglang-wheel").exists(), "a half-built runtime has its note") + + def test_a_run_that_changes_nothing_leaves_the_notes_date(self): + # the note's date is one of the runtime's (the lane serves older files, the cockpit's + # stale-runtime check that turns the video lane's Turbo off): written at every run, it said + # so after every update (found in review, 2026-10-15) + for installer, lane, _unit in LANES_IN_TWO_HALVES: + with self.subTest(installer=installer): + box = Box(installer) + self.assertEqual(box.run("--prepare")[0], 0) + note = box.home / lane / "sglang-wheel" + first = note.stat().st_mtime_ns + __import__("time").sleep(0.05) + rc, out, _ = box.run("--prepare") + self.assertEqual(rc, 0, out) + self.assertEqual(note.stat().st_mtime_ns, first) + + def test_a_new_wheel_rewrites_the_note(self): + # written only when it changes: a wheel of another release reinstalls the runtime and the + # note names the new one, which the cockpit compares with what the lane serves + for installer, lane, _unit in LANES_IN_TWO_HALVES: + with self.subTest(installer=installer): + box = Box(installer) + self.assertEqual(box.run("--prepare")[0], 0) + note = box.home / lane / "sglang-wheel" + wheel = note.read_text() + note.write_text("0.5.19\n") + rc, out, calls = box.run("--prepare") + self.assertEqual(rc, 0, out) + self.assertEqual(note.read_text(), wheel) + self.assertNotEqual(wheel, "0.5.19\n") def test_the_two_halves_are_asked_for_one_at_a_time(self): for installer, _lane, _unit in LANES_IN_TWO_HALVES: diff --git a/tests/test_tools.py b/tests/test_tools.py index e57b8809..ae716d00 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -444,5 +444,23 @@ class BenchAgentTiming(unittest.TestCase): self.assertEqual(cm.exception.code, 3) +class TheTokenMapIsPutInPlaceWhole(unittest.TestCase): + """build-token-map.py writes beside the map, reads it back as SGLang would, and only then puts + it in place: lanes.sh takes a map that is there for built, and a run stopped mid-write (a job + the cockpit stops, a disk that fills) left one half written that the launcher passed to the + engine at every start (found in review, 2026-10-15). torch is not in this suite's Python, so + the order is read from the script.""" + + def test_the_map_is_read_back_before_it_replaces_the_one_there(self): + main = (REPO / "build-token-map.py").read_text() + main = main[main.index("def main("):] + save, load, put = (main.index("torch.save(ids, tmp)"), main.index("torch.load(tmp, weights_only=True)"), + main.index("os.replace(tmp, args.out)")) + self.assertLess(save, load) + self.assertLess(load, put) + self.assertNotIn("torch.save(ids, args.out)", main) + self.assertNotIn("torch.load(args.out", main) + + if __name__ == "__main__": unittest.main(verbosity=2)