From 5528924b962f497e3e3adf265896e35f32599235 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 15:53:17 +0800 Subject: [PATCH 1/7] Smoke an adopted image on one node and add yeto image adopt Step 5 of the adoption (yeto.launch.image_smoke), then the catalog record: - trainer: the model is cut to the most layers (at most 16, the MFU 16L cut) whose trainer state fits one node in the model registry's sizing, with the backend and recipe yeto adapt recommends for the full model. scripts/prune_layers.py writes the cut on the node, in the image, as a hub snapshot under the node's scratch. A one-node ssh: island trains one round on replayed synthetic rollouts and ends it with a cut in --smoke-store; a second launch resumes from that cut. Only Miles has the train-only replay, so only Miles has a trainer smoke for now; - sampler: yeto.node.smoke builds the engine of the pool's sampler spec (the sampler entry's own build_engine), starts it, generates, reloads and generates again; it starts in the image exactly as the node runtime starts a sampler (container_argv takes the module to run). yeto image adopt REF --model M --role trainer|sampler --inventory INV runs the five steps; --dry-run prints every step and the smoke commands and reaches no registry or node. Any failed step exits 1 and leaves the catalog unchanged. docs/OWN_CLUSTERS.md: "Onboarding a model image". own-cluster-fleet-stability 7.3, 7.5. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 122 ++++++++++ tests/test_image_smoke.py | 482 +++++++++++++++++++++++++++++++++++++ tests/test_run_flags.py | 6 +- yeto/cli.py | 8 + yeto/launch/image_adopt.py | 141 ++++++++++- yeto/launch/image_smoke.py | 408 +++++++++++++++++++++++++++++++ yeto/node/launch.py | 10 +- yeto/node/smoke.py | 142 +++++++++++ 8 files changed, 1306 insertions(+), 13 deletions(-) create mode 100644 tests/test_image_smoke.py create mode 100644 yeto/launch/image_smoke.py create mode 100644 yeto/node/smoke.py diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 68cf4d9bc..b606ca2c0 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -704,3 +704,125 @@ process that reused the pid. A ledger row is closed only after its stop was conf minutes is lost and stays quarantined until `yeto cluster release-node`. - The layout is never shrunk: without a spare the island waits; it does not change TP/PP/EP. + +## Onboarding a model image + +A new model often comes with an image built for it: a trainer image with the +kernels and Miles / Megatron versions the model needs, or a sampler image with the +vLLM or SGLang build that serves it. `yeto image adopt` takes such an image into +your site, checked and smoked on your own nodes, and records it in the **site image +catalog**. From then on a trainer island or a sampler pool of those nodes that +names no image runs it for that model. + +``` +yeto image adopt REGISTRY/IMAGE:TAG --model ORG/MODEL --role trainer \ + --inventory cluster.yaml --smoke-store s3://BUCKET/image-smoke --dry-run + +yeto image adopt REGISTRY/IMAGE:TAG --model ORG/MODEL --role sampler \ + --inventory cluster.yaml --sampler-spec sampler-spec.json --dry-run +``` + +`--dry-run` prints every step with its commands and reaches no registry and no +node. Drop it to adopt the image. The steps, in order: + +1. **manifest**: yeto asks the registry for the image's manifest (with the + registry login a pull would use: `SKYPILOT_DOCKER_USERNAME` / + `SKYPILOT_DOCKER_PASSWORD` / `SKYPILOT_DOCKER_SERVER`, else + `~/.docker/config.json`) and pins a tag to its digest. A missing manifest + stops here, before any node is contacted. +2. **probe**: one node (`--node`, default the first of the role) runs the image once + with its cards and reads the CPU architecture, Python, torch, CUDA or HIP, the + card architectures the image's kernels were built for, the engine packages and + the yeto image lock (`/opt/yeto/image`). +3. **fit**: the image against every node of the role: CPU architecture, device + runtime, card architecture (a node's `sm_N` must be built, or a `compute_M` PTX + with M <= N; a ROCm node's `gfx` target must be built), the trainer image + floors yeto knows, and the role's engine package. A mismatch names the image's + lowest card architecture and the node's card, for example + `the image is built for sm_90/sm_100 (lowest sm90); node a100-0 has A100-80GB (sm80)`. +4. **pull**: every node of the role (spares included, `roles: [trainer-spare]`) + is checked over SSH, and its image root (the docker data root, or + `/var/lib/containerd` with the containerd image store) must have + `--min-image-free-gib` free (default 120). Only when every node passes does the + pull run, on all nodes in parallel. A node that fails is named with the + preflight's finding or docker's error line. +5. **smoke**, on the probe node: + - **trainer**: the model is cut to its first N layers (all their experts, the + embeddings and the head, `scripts/prune_layers.py`), N being the largest, at + most 16, whose trainer state fits one node in the model registry's sizing + (`yeto adapt`'s backend and recipe for the full model). A one-node `ssh:` + island then trains one round on synthetic rollouts (no sampler), ends it with + a cut in `--smoke-store`, and a second launch resumes from that cut and trains + another round. The node needs `scratch:` in the inventory (the cut model is + written there). `--model-path` takes the checkpoint from a directory on the + node instead of the Hub. When the registry's flags for the model need a file + (for example `--rl-expert-selection` for Kimi K3.1), pass it with + `--smoke-arg=--rl-expert-selection=/path/selection.json`; any other + `yeto launch` flag the run needs goes the same way. Only the Miles backend has + a trainer smoke so far. + - **sampler**: the engine of `--sampler-spec` (the pool's sampler spec) starts + in the image the way the node runtime starts a sampler (the node's device + flags and directories), generates once, reloads (the weights of `--release`, + default its base weights, as policy version 1) and generates again. A failing + step is named, for example `smoke failed: engine: reload failed: ...`. + +Any failed step stops the adoption and leaves the catalog unchanged. After a +passing smoke the catalog gets a `verified-smoke` record with the digest, the +versions the probe read and the evidence of the run (time, node, seconds per +step, the nodes that pulled the image). + +### The site image catalog + +The catalog is `~/.yeto/site-images.yaml`, or the file the inventory names with +its top-level `site_images:` (a relative path is taken from the inventory's +directory): + +```yaml +site_images: images/site-images.yaml +nodes: + - name: b300-0 + ... +``` + +Each record: + +```yaml +version: 1 +images: + - model: ORG/MODEL + role: trainer # trainer | sampler + engine: miles # trainer: the --rl-backend; sampler: vllm | sglang | vllm-ascend + ref: REGISTRY/IMAGE@sha256:<64 hex> + device_family: cuda + cpu_arch: x86_64 + card_archs: [sm103] # the card architecture the smoke ran on + versions: {python: 3.12.3, torch: 2.9.1+cu130, cuda: "13.0", megatron-core: 0.15.0} + evidence: {at: "2026-11-26T10:00:00Z", node: b300-0, seconds: 1834.2, result: pass} + status: verified-smoke # verified-smoke | retired +``` + +To stop using a record, set its `status: retired`. A broken catalog (bad YAML, an +unknown key, a tag instead of a digest) is refused with the file and the record +named, but only by a run that reads it. + +### Which image a run uses + +For an `ssh:` trainer island and an ssh sampler pool node: + +1. the image the configuration names: `--rl-image`, an inventory `image:` or + `images:`, a pool's `container.image`. The catalog is not read; +2. else the newest `verified-smoke` record of the catalog for the run's model and + role whose CPU architecture, card architecture and device family match every + node of the island (or the pool node); +3. else the built-in default (the pinned `--rl-image`, or the engine image catalog's + choice for a pool's `container.image: auto`). + +The launcher and `pool --dry-run` print the image and where it came from, for +example: + +``` +[launcher] ssh trainer image REGISTRY/IMAGE@sha256:... (adopted 2026-11-26T10:00:00Z on b300-0) (source: site image catalog ...) +``` + +A configuration that names its image prints nothing new and runs exactly as +before. diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py new file mode 100644 index 000000000..a24a4e210 --- /dev/null +++ b/tests/test_image_smoke.py @@ -0,0 +1,482 @@ +"""``yeto image adopt`` step 5 and the command (own-cluster-fleet-stability 7.3, 7.5): +the trainer smoke (a cut model, one round, a cut and a resume) and the sampler smoke +(the node runtime's container start of yeto.node.smoke: start, generate, reload, +generate) on CPU fakes; the catalog is written only after a passing smoke; the dry +run prints the smoke's commands; the documented commands run in a dry run.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shlex +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest +import yaml + +from tests.test_cluster_preflight import FakeCluster, b300 +from tests.test_image_adopt import PINNED, TAGGED, FakeNodes, probe_out, registry +from yeto.cli import build_parser +from yeto.launch import image_adopt as ia +from yeto.launch import image_smoke as sm +from yeto.launch import site_images as si +from yeto.node import smoke as node_smoke +from yeto.rl.adapters.sampler_engines.fake import FakeEngine + +ROOT = Path(__file__).resolve().parents[1] +REGISTRY_CONFIGS = ROOT / "tests" / "data" / "model_registry" +QWEN = json.loads((REGISTRY_CONFIGS / "qwen3_30b_a3b.json").read_text()) +K31 = json.loads((REGISTRY_CONFIGS / "kimi_k31.json").read_text()) +FAKE_SPEC = {"sampler_id": "adopt", "engine": {"factory": "yeto.rl.adapters.sampler_engines.from_spec:build", + "adapter": "fake", "kwargs": {}}} +REV = "f" * 40 + + +@pytest.fixture(autouse=True) +def _env(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.delenv("YETO_IMAGE_MANIFEST_CHECK", raising=False) + + +def node(i=0, **kw): + return b300(i, **{"scratch": "/mnt/nvme/yeto", "image": None, **kw}) + + +# -- the node side of the sampler smoke ---------------------------------------------- + + +class ReloadFails(FakeEngine): + def load(self, release_dir, version): + raise RuntimeError("update_weights_from_disk answered 500") + + +def test_the_node_smoke_starts_generates_reloads_and_generates(capsys): + engine = FakeEngine() + record = node_smoke.run_smoke(engine, release=None) + assert record["ok"] and record["step"] is None and record["reload_mode"] == "in_place" + assert set(record["seconds"]) == set(node_smoke.STEPS) + assert engine.loads == [(None, 0), (None, 1)] and engine.stopped + lines = [json.loads(line.split(" ", 1)[1]) for line in capsys.readouterr().out.splitlines()] + assert [r["step"] for r in lines] == list(node_smoke.STEPS) and all(r["ok"] for r in lines) + + +def test_a_failed_reload_names_the_step_and_stops_the_engine(): + engine = ReloadFails() + record = node_smoke.run_smoke(engine, release="/models/r1", out=open(os.devnull, "w")) + assert (record["ok"], record["step"]) == (False, "reload") + assert "update_weights_from_disk answered 500" in record["error"] and engine.stopped + + +def test_the_node_smoke_entry_reads_the_spec(tmp_path, capsys): + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + assert node_smoke.main(["--spec", str(spec)]) == 0 + assert node_smoke.parse_result(capsys.readouterr().out)["ok"] is True + spec.write_text(json.dumps({"engine": {"factory": "yeto.rl.adapters.sampler_engines.from_spec:build", + "adapter": "nope"}})) + assert node_smoke.main(["--spec", str(spec)]) == 1 + result = node_smoke.parse_result(capsys.readouterr().out) + assert result["step"] == "start" and "unknown sampler engine 'nope'" in result["error"] + + +# -- the sampler smoke through the adoption ------------------------------------------- + + +class SmokeNodes(FakeNodes): + """The fake cluster, plus the sampler smoke: the upload is accepted, the engine + step runs ``python -m yeto.node.smoke`` here on the spec it uploaded.""" + + def __init__(self, nodes, tmp_path, *, pythonpath=(), **kw): + super().__init__(nodes, probe=probe_out(packages={"vllm": "0.19.0", "torch": "2.9.1"}), **kw) + self.tmp_path = tmp_path + self.pythonpath = pythonpath + + def run(self, node, script, *, timeout=300.0): + if "YETO_TREE_EOF" in script: + self.scripts.append((node.name, "upload")) + spec = re.search(r"<<'YETO_SPEC_EOF'\n(.*)\nYETO_SPEC_EOF", script, re.S).group(1) + (self.tmp_path / "uploaded-spec.json").write_text(spec) + return self.done(0, "") + if "yeto.node.smoke" in script: + self.scripts.append((node.name, "engine")) + argv = shlex.split(script) + assert PINNED in argv and "--rm" in argv and "--gpus" in argv + env = {**os.environ, "PYTHONPATH": os.pathsep.join([str(ROOT), *map(str, self.pythonpath)])} + done = subprocess.run([sys.executable, "-m", "yeto.node.smoke", "--spec", + str(self.tmp_path / "uploaded-spec.json")], capture_output=True, text=True, + env=env, timeout=120) + return self.done(done.returncode, done.stdout + done.stderr) + return super().run(node, script, timeout=timeout) + + +def _adopt(nodes, tmp_path, plan, ops, role): + opener, _ = registry({"k99": 200}) + req = ia.AdoptRequest(ref=TAGGED, model="org/new-model", role=role, nodes=tuple(nodes), + catalog=str(tmp_path / "site-images.yaml"), engine=plan.data.get("engine")) + + def smoke(adopter, ref, facts, engine): + return sm.run_plan(plan, ops=adopter.ops, ref=ref, python=facts.python_path, log=lambda m: None, + run=getattr(ops, "launch", subprocess.run), clock=lambda: 0.0) + + return ia.Adopter(req, ops=ops, smoke=smoke, urlopen=opener, login=None, log=lambda m: None, + clock=lambda: FakeCluster.NOW) + + +def test_a_sampler_image_whose_smoke_passes_is_recorded(tmp_path): + nodes = [node(0), node(1)] + plan = sm.sampler_plan(nodes[0], spec=FAKE_SPEC, run_id="adopt-t", code=("t000", b"tar")) + report = _adopt(nodes, tmp_path, plan, SmokeNodes(nodes, tmp_path), "sampler").run() + assert report.ok and report.steps[-1].detail.startswith("engine started, generated, reloaded") + (rec,) = si.load(tmp_path / "site-images.yaml") + assert (rec.role, rec.engine, rec.ref, rec.card_archs) == ("sampler", "vllm", si.parse_record( + rec.to_doc()).ref, ("sm103",)) + assert rec.evidence["smoke"]["reload_mode"] == "in_place" + assert set(rec.evidence["smoke"]["engine_steps"]) == set(node_smoke.STEPS) + + +def test_a_sampler_whose_reload_fails_is_not_recorded(tmp_path): + (tmp_path / "adopt_fail_engine.py").write_text( + "from tests.test_image_smoke import ReloadFails\n" + "def build(section):\n return ReloadFails()\n") + spec = {"sampler_id": "adopt", "engine": {"factory": "adopt_fail_engine:build"}} + nodes = [node(0)] + plan = sm.sampler_plan(nodes[0], spec=spec, run_id="adopt-t", code=("t000", b"tar")) + with pytest.raises(ia.AdoptError) as error: + _adopt(nodes, tmp_path, plan, SmokeNodes(nodes, tmp_path, pythonpath=[tmp_path]), "sampler").run() + assert error.value.step == "smoke" + assert error.value.reason.startswith("engine: reload failed: RuntimeError: update_weights_from_disk answered 500") + assert not (tmp_path / "site-images.yaml").exists() + + +def test_the_sampler_smoke_starts_like_the_node_runtime(): + from yeto.launch.node_inventory import profile_of + from yeto.node import launch as node_launch + + n = node(0) + plan = sm.sampler_plan(n, spec=FAKE_SPEC, run_id="adopt-t", code=("t000", b"tar")) + engine = shlex.split(plan.steps[1].script) + runtime = node_launch.container_argv(profile_of(n), name="yeto-adopt-adopt-t", image=sm.REF, + env={"PYTHONPATH": "/work/image-adopt/yeto/t000", "PYTHONUNBUFFERED": "1", + **profile_of(n).family_env()}, + python=sm.PYTHON, spec_path="/work/image-adopt/adopt-t/spec.json") + assert engine[:-1] == runtime[:-1] # the same flags, mounts and environment + assert engine[-1].endswith("-m yeto.node.smoke --spec /work/image-adopt/adopt-t/spec.json") + assert runtime[-1].endswith(f"-m {node_launch.SAMPLER_MODULE} --spec /work/image-adopt/adopt-t/spec.json") + with pytest.raises(sm.SmokeError, match="needs a container runtime"): + sm.sampler_plan(node(0, runtime="rootfs"), spec=FAKE_SPEC, run_id="x", code=("t", b"")) + + +# -- the trainer smoke ---------------------------------------------------------------- + + +def test_the_cut_is_the_most_layers_that_fit_one_node(): + layout = sm.smoke_layout(QWEN, node(0), engine=None) + assert layout["engine"] == "miles" and layout["layers"] == 16 and layout["plan"]["world"] <= 8 + assert sm.smoke_layout(QWEN, node(0), engine=None, layers=4)["layers"] == 4 + small = node(0, card="L4", hbm_gib=24.0, cards_per_node=1) + assert sm.smoke_layout(QWEN, small, engine="miles")["layers"] < 16 + with pytest.raises(sm.SmokeError, match="the model has 48 layers"): + sm.smoke_layout(QWEN, node(0), engine=None, layers=99) + + +def _trainer_plan(tmp_path, **kw): + target = kw.pop("node", node(0)) + args = {"model": "Qwen/Qwen3-30B-A3B", "config": QWEN, "engine": None, "store": "s3://bucket/smoke", + "run_id": "adopt-t", "workdir": tmp_path / "work", "python": "py", **kw} + return sm.trainer_plan(target, **args) + + +def test_the_trainer_plan_cuts_trains_and_resumes_on_one_node(tmp_path): + plan = _trainer_plan(tmp_path) + assert [s.name for s in plan.steps] == ["prune", "train", "resume"] + prune, train, resume = plan.steps + assert "--layers 16" in prune.script and "hf://Qwen/Qwen3-30B-A3B" in prune.script + assert "base64 -d" in prune.script and sm.REVISION_MARK in prune.script + argv = list(train.argv) + assert argv[:4] == ["py", "-m", "yeto.cli", "launch"] + for flag, value in (("--rl-backend", "miles"), ("--gpu", "ssh:1x8xB300"), ("--rl-image", f"docker:{sm.REF}"), + ("--model", "yeto-local/Qwen3-30B-A3B-16layer"), ("--model-revision", sm.REVISION), + ("--model-store", f"local://{sm.HUB_IN_CONTAINER}"), + ("--rl-checkpoint-store", "s3://bucket/smoke/adopt-t"), ("--rl-stop-after-rounds", "1")): + assert argv[argv.index(flag) + 1] == value + assert argv.count("--model") == 1 + assert list(resume.argv)[-2:] == ["--rl-stop-after-rounds", "2"] and resume.expect + synth = json.loads(next(a for a in argv if a.startswith(sm.SYNTH_ENV + "=")).split("=", 1)[1]) + assert synth["layers"] == 16 and synth["experts"] == 128 and synth["router_topk"] == 8 + (inventory, text), = plan.files.items() + (entry,) = yaml.safe_load(text)["nodes"] + assert entry["mounts"]["/mnt/nvme/yeto/image-adopt/hub"] == sm.HUB_IN_CONTAINER and "image" not in entry + assert entry["mounts"]["/mnt/nvme/models"] == "/data/models" # the node's own mounts stay + assert entry["roles"] == ["trainer"] and entry["scratch"] == "/mnt/nvme/yeto" + assert plan.data["layers"] == 16 and plan.data["engine"] == "miles" + assert any("16 of 48 layers" in n for n in plan.notes) + + +def test_a_node_path_takes_the_checkpoint_from_the_node(tmp_path): + prune = _trainer_plan(tmp_path, model_path="/mnt/models/qwen3", model_revision="abc").steps[0] + assert "/mnt/models/qwen3:/mnt/models/qwen3:ro" in prune.script and "hf://" not in prune.script + assert "--revision" not in prune.script + assert "--revision abc" in _trainer_plan(tmp_path, model_revision="abc").steps[0].script + + +@pytest.mark.parametrize("kw, message", [ + ({"node": node(0, scratch=None)}, "has no scratch"), + ({"store": None}, "pass --smoke-store"), + ({"node": node(0, runtime="rootfs")}, "runs rootfs"), + ({"engine": "verl"}, "no trainer smoke for backend verl"), +]) +def test_the_trainer_plan_refuses_what_it_cannot_run(tmp_path, kw, message): + with pytest.raises(sm.SmokeError, match=message): + _trainer_plan(tmp_path, **kw) + + +def test_a_registry_placeholder_needs_a_smoke_arg(tmp_path): + with pytest.raises(sm.SmokeError, match=r"need \[''\]"): + _trainer_plan(tmp_path, model="moonshotai/Kimi-K3.1-Pro", config=K31) + plan = _trainer_plan(tmp_path, model="moonshotai/Kimi-K3.1-Pro", config=K31, + extra_args=("--rl-expert-selection=/sel.json",)) + argv = list(plan.steps[1].argv) + assert "--rl-expert-selection=/sel.json" in argv and "--rl-expert-selection" not in argv + assert "" not in argv + + +class Launches: + """The launcher's subprocess for the train and resume steps.""" + + def __init__(self, resume_out="rl_resume: from cut round 1", rc=0): + self.calls, self.resume_out, self.rc = [], resume_out, rc + + def __call__(self, argv, **kw): + self.calls.append(argv) + resume = argv[-1] == "2" + return subprocess.CompletedProcess(argv, self.rc, stdout=self.resume_out if resume else "round 1 cut", + stderr="") + + +class TrainerNodes(FakeNodes): + def __init__(self, nodes, launches, **kw): + super().__init__(nodes, **kw) + self.launch = launches + + def run(self, node, script, *, timeout=300.0): + if "YETO_PRUNE_EOF" in script: + self.scripts.append((node.name, "prune")) + assert PINNED in script and "/usr/bin/python3 /tmp/yeto-prune_layers.py" in script + return self.done(0, f"{sm.REVISION_MARK} {REV}\n") + return super().run(node, script, timeout=timeout) + + +def test_a_trainer_image_whose_smoke_passes_is_recorded(tmp_path): + nodes = [node(0), node(1)] + plan = _trainer_plan(tmp_path) + launches = Launches() + report = _adopt(nodes, tmp_path, plan, TrainerNodes(nodes, launches), "trainer").run() + assert report.ok + train, resume = launches.calls + assert train[train.index("--model-revision") + 1] == REV and resume[resume.index("--rl-image") + 1] == \ + f"docker:{PINNED}" + assert Path(train[train.index("--rl-node-inventory") + 1]).is_file() + (rec,) = si.load(tmp_path / "site-images.yaml") + assert (rec.role, rec.engine, rec.model) == ("trainer", "miles", "org/new-model") + assert rec.evidence["smoke"]["layers"] == 16 and rec.evidence["smoke"]["revision"] == REV + assert set(rec.evidence["smoke"]["steps"]) == {"prune", "train", "resume"} + + +@pytest.mark.parametrize("launches, message", [ + (Launches(resume_out="round 2 done"), "resume: the output has no"), + (Launches(rc=1), "train: rc 1"), +]) +def test_a_trainer_smoke_that_does_not_resume_or_train_is_not_recorded(tmp_path, launches, message): + nodes = [node(0)] + with pytest.raises(ia.AdoptError, match=message): + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), TrainerNodes(nodes, launches), "trainer").run() + assert not (tmp_path / "site-images.yaml").exists() + + +def test_a_prune_without_a_revision_stops_the_smoke(tmp_path): + class NoRev(TrainerNodes): + def run(self, node, script, *, timeout=300.0): + if "YETO_PRUNE_EOF" in script: + return self.done(0, "cut done\n") + return super().run(node, script, timeout=timeout) + nodes = [node(0)] + with pytest.raises(ia.AdoptError, match="prune: the output has no 'YETO_SMOKE_REVISION'"): + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), NoRev(nodes, Launches()), "trainer").run() + + +DOCKER_SHIM = r"""#!/usr/bin/env python3 +import os, subprocess, sys +args = sys.argv[1:] +assert args[:2] == ["run", "--rm"], args +mounts, i = [], 2 +while args[i] != "--entrypoint": + if args[i] == "-v": + host, inside = args[i + 1].split(":")[:2] + mounts.append((inside, host)) + i += 2 + else: + i += 1 +inner = args[args.index("-c") + 1] +for inside, host in sorted(mounts, key=lambda m: -len(m[0])): + inner = inner.replace(inside, host) +sys.exit(subprocess.run(["bash", "-c", inner]).returncode) +""" + + +def _safetensors(path: Path, names): + import struct + + header = {n: {"dtype": "F32", "shape": [1], "data_offsets": [4 * i, 4 * i + 4]} for i, n in enumerate(names)} + raw = json.dumps(header).encode() + path.write_bytes(struct.pack(" argparse.ArgumentParser: _add_cluster_parser(sub) + from .launch.image_adopt import add_parser as _add_image_parser + + _add_image_parser(sub) + logs = sub.add_parser("logs", help="stream a run's launcher log (Ctrl-C detaches)") logs.add_argument("run", help="run name (its --cluster-prefix)") logs.add_argument( @@ -2794,6 +2798,10 @@ def main(argv=None) -> int: from .cluster_cli import main as cluster_main return cluster_main(args) + if args.command == "image": + from .launch.image_adopt import main as image_main + + return image_main(args) if args.command == "sandbox": from .sandbox.cli import main as sandbox_main diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index db98da2d0..41df70938 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -44,6 +44,8 @@ from typing import Any from . import engine_images, image_manifest, image_pull, site_images, trainer_image_check +from .image_smoke import MAX_LAYERS as MAX_SMOKE_LAYERS +from .image_smoke import StepResult from .node_inventory import Node, card_arch_of STEPS = ("manifest", "probe", "fit", "pull", "smoke") @@ -143,15 +145,6 @@ def versions(self) -> dict[str, str]: return {k: str(v) for k, v in out.items() if v} -@dataclass -class StepResult: - name: str - ok: bool - detail: str - seconds: float - data: dict[str, Any] = field(default_factory=dict) - - @dataclass class AdoptReport: """The steps run so far; ``record`` once the catalog was written.""" @@ -782,3 +775,133 @@ def _record(self, ref: str, facts: ImageFacts, engine: str, smoke: StepResult) - "device_family": engine_images.canonical_device_family(node.device_family), "cpu_arch": node.cpu_arch, "card_archs": [arch] if arch else [], "versions": facts.versions(), "evidence": evidence, "status": site_images.VERIFIED}) + + +# --- yeto image adopt ------------------------------------------------------------------ + + +def add_parser(sub: Any) -> Any: + p = sub.add_parser("image", help="site images: `yeto image adopt --model M --role trainer|sampler " + "--inventory INV`") + image_sub = p.add_subparsers(dest="image_command", metavar="{adopt}", required=True) + a = image_sub.add_parser( + "adopt", help="check, pre-pull and smoke an image built for a model; record it in the site image catalog", + description="Adopt an image built for one model on the nodes of an SSH inventory: registry manifest and " + "digest, a probe of the image on one node, its fit to every node of the role, a parallel " + "pre-pull with the image root checked, and the role's smoke on one node. Only a passing " + "smoke writes the site image catalog (the inventory's site_images:, else " + f"{site_images.DEFAULT_PATH}); an island or pool that names no image then takes it.") + a.add_argument("ref", help="the image: REGISTRY/IMAGE:TAG or REGISTRY/IMAGE@sha256:") + a.add_argument("--model", required=True, help="the model the image is built for (an HF id)") + a.add_argument("--role", required=True, choices=site_images.ROLES) + a.add_argument("--inventory", required=True, help="the SSH node inventory (YAML / JSON)") + a.add_argument("--engine", default=None, + help="trainer: the --rl-backend (default: the model registry's); sampler: vllm | sglang | " + "vllm-ascend (default: the engine found in the image)") + a.add_argument("--node", default=None, help="the node that probes and smokes (default: the first of the role)") + a.add_argument("--catalog", default=None, help="the site image catalog (default: the inventory's site_images:)") + a.add_argument("--min-image-free-gib", type=float, default=120.0, + help="free GiB the image root (docker data root / containerd store) of every node needs") + a.add_argument("--attention-backend", default="auto", + help="the trainer's attention backend, for the trainer image floor (default auto)") + a.add_argument("--dry-run", action="store_true", help="print every step and command; reach no registry or node") + t = a.add_argument_group("trainer smoke") + t.add_argument("--model-config", default=None, + help="the model's config.json (default: a local dir / the HF cache, else fetched from the Hub)") + t.add_argument("--model-revision", default=None, help="the HF revision the smoke cuts") + t.add_argument("--model-path", default=None, + help="the model's checkpoint directory on the smoke node (instead of downloading it there)") + t.add_argument("--smoke-store", default=None, help="s3://BUCKET/PREFIX: the smoke run's store (its checkpoint)") + t.add_argument("--smoke-layers", type=int, default=None, + help=f"layers of the cut (default: the most, at most {MAX_SMOKE_LAYERS}, that fit one node)") + t.add_argument("--smoke-arg", action="append", default=[], metavar="ARG", + help="an extra `yeto launch` argument of the smoke (repeat; --smoke-arg=--flag=value)") + s = a.add_argument_group("sampler smoke") + s.add_argument("--sampler-spec", default=None, help="the pool's sampler spec (JSON) whose engine is smoked") + s.add_argument("--release", default=None, + help="the release directory the smoke reloads (container path; default: the engine's base weights)") + return p + + +def _model_config(args: Any) -> dict[str, Any]: + from ..rl.model_registry.match import load_config # noqa: PLC0415 + + if args.model_config: + return load_config(args.model_config)[0] + try: + return load_config(args.model)[0] + except FileNotFoundError: + if args.dry_run: + raise + from ..rl.model_registry.cli import _fetch # noqa: PLC0415 - config.json only, never weights + + with open(_fetch(args.model, "config.json", args.model_revision), encoding="utf-8") as handle: + return json.load(handle) + + +def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: + """The smoke plan, with the image as :data:`.image_smoke.REF` (the trainer's backend: + the registry's, which has a smoke only for the default backend).""" + from . import image_smoke # noqa: PLC0415 + + workdir = Path(site_images.default_path()).parent / "image-adopt" / run_id + if request.role == "trainer": + plan = image_smoke.trainer_plan( + request.probe_node, model=request.model, config=_model_config(args), engine=request.engine, + store=args.smoke_store, run_id=run_id, workdir=workdir, model_revision=args.model_revision, + model_path=args.model_path, layers=args.smoke_layers, extra_args=tuple(args.smoke_arg)) + return plan + if not args.sampler_spec: + raise image_smoke.SmokeError("the sampler smoke runs the pool's sampler spec: pass --sampler-spec") + spec = json.loads(Path(args.sampler_spec).expanduser().read_text()) + return image_smoke.sampler_plan(request.probe_node, spec=spec, run_id=run_id, release=args.release) + + +def main(args: Any, *, ops: Any = None, out: Any = None) -> int: + """``yeto image adopt``: 0 recorded (or a dry run), 1 a step failed, 2 a bad request.""" + from . import image_smoke # noqa: PLC0415 + from .node_inventory import InventoryError, load_inventory # noqa: PLC0415 + + out = out or sys.stdout + try: + nodes = role_nodes(load_inventory(args.inventory), args.role) + catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) + request = AdoptRequest(ref=args.ref, model=args.model, role=args.role, nodes=tuple(nodes), + engine=args.engine, node=args.node, catalog=catalog, + min_image_free_gib=args.min_image_free_gib, attention_backend=args.attention_backend) + stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S") + slug = re.sub(r"[^a-z0-9]+", "-", args.model.rsplit("/", 1)[-1].lower()).strip("-")[:24] or "model" + run_id = f"adopt-{slug}-{args.role}-{stamp}" + plan = _plan(args, request, run_id) + except (InventoryError, site_images.SiteImagesError, image_smoke.SmokeError, FileNotFoundError, OSError, + ValueError) as error: + print(f"yeto image adopt: {error}", file=sys.stderr) + return 2 + if args.dry_run: + node = request.probe_node + role = [n.name for n in request.nodes] + lines = [f"yeto image adopt (dry run): {args.ref} for {args.model} as {args.role} on {len(role)} node(s) " + f"{role}", + f"1. manifest: HEAD of {args.ref} in its registry; a tag is pinned to its digest " + f"(below: {image_smoke.REF})", + f"2. probe on {node.name}: {probe_script(image_smoke.REF, node)[:200]} ...", + f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}", + f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then docker pull " + f"{image_smoke.REF} on {role} in parallel", + "5. " + "\n".join(plan.lines()), + f"then: a verified-smoke record in {catalog}"] + print("\n".join(lines), file=out) + return 0 + + def smoke(adopter: Adopter, ref: str, facts: ImageFacts, engine: str) -> StepResult: + return image_smoke.run_plan(plan, ops=adopter.ops, ref=ref, python=facts.python_path, log=adopter.log) + + adopter = Adopter(request, ops=ops, smoke=smoke) + try: + report = adopter.run() + except AdoptError as error: + print("\n".join(adopter.report.lines()), file=out) + print(f"yeto image adopt: {error}; the site image catalog {catalog} is unchanged", file=sys.stderr) + return 1 + print("\n".join(report.lines()), file=out) + return 0 diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py new file mode 100644 index 000000000..d6035e71e --- /dev/null +++ b/yeto/launch/image_smoke.py @@ -0,0 +1,408 @@ +"""Step 5 of ``yeto image adopt``: the role's smoke run of the image on one node. + +**trainer** (``--role trainer``): the model, cut down until one node holds it, trains +one step, saves a checkpoint, reads it back and trains on: + +1. ``prune`` (on the node, in the image): ``scripts/prune_layers.py`` keeps the first + ``N`` decoder layers (all their experts, the embeddings and the head; the MFU 16L + cut of 2026-11-18) and lays the result out as a Hugging Face hub snapshot under the + node's ``scratch`` (revision = the sha1 of the cut ``config.json``). ``N`` is the + largest of at most :data:`MAX_LAYERS` whose trainer state fits the node's cards in + the model registry's sizing (:func:`yeto.rl.model_registry.recommend.plan_trainer`, + with the backend and recipe ``yeto adapt`` recommends for the full model); +2. ``train`` (on the launcher): ``yeto launch`` of an ``ssh:`` island of that one node + with the image, the registry's flags for the cut model (recipe, tuning, TP / PP / + EP) and a train-only replay of synthetic rollouts (Miles' debug-rollout replay, + ``YETO_TEST_SYNTH_ROLLOUT``: no sampler); ``--rl-stop-after-rounds 1`` ends the + round with a cut (the checkpoint) in ``--smoke-store``; +3. ``resume`` (on the launcher): the same launch with ``--rl-stop-after-rounds 2``: it + resumes from that cut (the checkpoint read) and trains the second round. + +**sampler** (``--role sampler``): the pool's sampler spec on one node, started as the +node runtime starts a sampler (:func:`yeto.node.launch.container_argv`) running +:mod:`yeto.node.smoke`: start the engine, one generation, one reload (the reload of a +trainer release), one more generation. + +:func:`trainer_plan` / :func:`sampler_plan` build the steps (what ``--dry-run`` +prints); :func:`run_plan` runs them (an ``SshOps`` for the node steps, ``subprocess`` +for the launcher steps; tests pass fakes). The pinned image, the image's interpreter +and the cut's revision are known only while adopting: the steps name them +:data:`REF`, :data:`PYTHON` and :data:`REVISION` until then. +""" + +from __future__ import annotations + +import base64 +import copy +import dataclasses +import json +import re +import shlex +import subprocess +import sys +import time +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from .node_inventory import _KNOWN as INVENTORY_KEYS +from .node_inventory import Node, card_arch_of, profile_of + +REF, PYTHON, REVISION = "@REF@", "@PYTHON@", "@REVISION@" +MAX_LAYERS = 16 # the MFU 16L cut +HUB_IN_CONTAINER = "/data/image-adopt-hub" # where the trainer sees the cut (--model-store local://) +SMOKE_MODEL_ORG = "yeto-local" +REVISION_MARK = "YETO_SMOKE_REVISION" +TRAINER_BACKENDS = ("miles",) # backends with a train-only replay (Miles' debug-rollout replay) +TRAIN_TIMEOUT_S = 3 * 3600.0 +PRUNE_TIMEOUT_S = 2 * 3600.0 +SAMPLER_TIMEOUT_S = 2 * 3600.0 +REPO_ROOT = Path(__file__).resolve().parents[2] +PRUNE_SCRIPT = REPO_ROOT / "scripts" / "prune_layers.py" +SYNTH_ENV = "YETO_TEST_SYNTH_ROLLOUT" # yeto.rl.adapters.miles.synth_rollout.SYNTH_ENV +REPLAY_ENV = "YETO_TEST_MILES_LOAD_DEBUG_ROLLOUT_DATA" # yeto.rl.adapters.miles.config.TEST_DEBUG_ROLLOUT_ENV +REPLAY_PATH = "/tmp/yeto-image-adopt-rollout/{rollout_id}.pt" + + +@dataclass +class StepResult: + """One adoption step's outcome (``yeto.launch.image_adopt``; the smoke returns one).""" + + name: str + ok: bool + detail: str + seconds: float + data: dict[str, Any] = field(default_factory=dict) + + +class SmokeError(ValueError): + """No smoke can be planned for this adoption (the reason says what is missing).""" + + +@dataclass(frozen=True) +class SmokeStep: + """One step: ``where`` ``node`` (a bash script run over ssh on the smoke node) or + ``launcher`` (``argv`` run here). ``expect``: a pattern the output must contain.""" + + name: str + where: str + script: str = "" + argv: tuple[str, ...] = () + timeout_s: float = 3600.0 + expect: str | None = None + show: str = "" # what --dry-run prints (default: the argv, or the script) + + def render(self, values: Mapping[str, str]) -> SmokeStep: + def fill(text: str) -> str: + for key, value in values.items(): + text = text.replace(key, value) + return text + return dataclasses.replace(self, script=fill(self.script), argv=tuple(fill(a) for a in self.argv), + show=fill(self.show)) + + def text(self) -> str: + return self.show or (shlex.join(self.argv) if self.argv else self.script) + + +@dataclass(frozen=True) +class SmokePlan: + role: str + node: Node + steps: tuple[SmokeStep, ...] + files: Mapping[str, str] = field(default_factory=dict) # launcher files the steps read + notes: tuple[str, ...] = () + data: Mapping[str, Any] = field(default_factory=dict) + + def lines(self) -> list[str]: + out = [f"smoke ({self.role}) on node {self.node.name}:"] + out += [f" note: {n}" for n in self.notes] + for path in self.files: + out.append(f" writes {path}") + for i, step in enumerate(self.steps, 1): + out.append(f" {i}. {step.name} [{step.where}]: {step.text()}") + return out + + +# --- trainer --------------------------------------------------------------------------- + + +def _slug(model: str) -> str: + return re.sub(r"[^A-Za-z0-9._-]+", "-", str(model).rstrip("/").rsplit("/", 1)[-1]).strip("-") or "model" + + +def _hardware(node: Node): + from ..rl.model_registry.schema import HardwareFacts # noqa: PLC0415 + from .engine_images import canonical_device_family # noqa: PLC0415 + + return HardwareFacts(device_family=canonical_device_family(node.device_family), arch=card_arch_of(node.card) or "?", + card=node.card, hbm_gib=int(node.hbm_gib), cards_per_node=int(node.cards_per_node), + max_nodes=1, interconnect="nvlink+ib") + + +def cut_config(config: Mapping[str, Any], layers: int) -> dict[str, Any]: + """``config`` with ``num_hidden_layers`` = ``layers`` (the text config of a VL model).""" + out = copy.deepcopy(dict(config)) + target = out.get("text_config") if isinstance(out.get("text_config"), dict) else out + target["num_hidden_layers"] = int(layers) + return out + + +def smoke_layout(config: Mapping[str, Any], node: Node, *, engine: str | None, + layers: int | None = None) -> dict[str, Any]: + """The registry's recipe for the full model (``yeto adapt``'s; ``engine`` None: the + backend it recommends) and the layout of the cut that fits ``node``: ``{"engine", + "recommendation", "recipe", "layers", "plan", "flags", "tuning"}``. Raises + :class:`SmokeError` when the registry has no recipe or no cut fits one node.""" + from ..rl.model_registry.match import facts_from_config # noqa: PLC0415 + from ..rl.model_registry.recommend import plan_trainer, recommend # noqa: PLC0415 + from ..rl.model_registry.render import BACKEND, cli_flags # noqa: PLC0415 + from ..rl.model_registry.schema import Constraints # noqa: PLC0415 + + hw = _hardware(node) + try: + full = facts_from_config(dict(config)) + except (KeyError, TypeError, ValueError) as error: + raise SmokeError(f"the model's config.json is not one the registry reads ({type(error).__name__}: " + f"{error})") from None + rec = recommend(full, hw, Constraints(trainer_backend=engine), card_explicit=True) + recipe = rec.recipe + if recipe is None or recipe.rl_model_recipe is None or recipe.status == "unsupported": + why = "; ".join(f"{name}: {reason}" for name, reason in rec.rejected) or "no recipe" + raise SmokeError(f"the model registry has no {engine or 'trainer'} recipe for this model on {node.card} " + f"({why})") + engine = engine or BACKEND.get(recipe.trainer.split("-", 1)[0], recipe.trainer) + tuning = rec.trainer_parallel.get("tuning") or recipe.tunings[0] + candidates = [int(layers)] if layers else list(range(min(MAX_LAYERS, full.layers), 0, -1)) + for n in candidates: + if n < 1 or n > full.layers: + raise SmokeError(f"--smoke-layers {n}: the model has {full.layers} layers") + facts = facts_from_config(cut_config(config, n)) + plan = plan_trainer(facts, hw, recipe, tuning) + if plan.get("fits"): # max_nodes 1: a fitting world is one node + cut = copy.copy(rec) + cut.facts, cut.supported = facts, True + cut.trainer_parallel = {**plan, "tuning": tuning} + flags = cli_flags(cut, f"{SMOKE_MODEL_ORG}/{_slug('m')}") + unresolved = [f for f in flags if f.startswith("<")] + return {"engine": engine, "recommendation": rec, "recipe": recipe, "layers": n, + "plan": cut.trainer_parallel, "flags": flags, "unresolved": unresolved, "tuning": tuning} + raise SmokeError(f"no cut of at most {candidates[0]} layers fits one {node.cards_per_node} x {node.card} node " + f"in the registry's sizing (tuning {tuning})") + + +def inventory_entry(node: Node, **over: Any) -> dict[str, Any]: + """``node`` as an inventory entry (the keys a node of the file may have).""" + defaults = {f.name: f.default for f in dataclasses.fields(Node) + if f.default is not dataclasses.MISSING} + out: dict[str, Any] = {} + for key in INVENTORY_KEYS: + value = getattr(node, key, None) + if key in defaults and value == defaults[key]: + continue + if value in (None, (), {}): + continue + out[key] = list(value) if isinstance(value, tuple) else dict(value) if isinstance(value, Mapping) else value + out.update(over) + return {k: v for k, v in out.items() if v is not None} + + +def _replace_flag(flags: list[str], extra: Sequence[str]) -> list[str]: + """``flags`` without the ``--flag value`` pairs ``extra`` gives again (the operator's + value wins: a registry placeholder such as ````).""" + given = {a.split("=", 1)[0] for a in extra if a.startswith("--")} + out, i = [], 0 + while i < len(flags): + if flags[i] in given: + i += 2 if i + 1 < len(flags) and not flags[i + 1].startswith("--") else 1 + continue + out.append(flags[i]) + i += 1 + return out + + +def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: str | None, store: str | None, + run_id: str, workdir: Path, model_revision: str | None = None, model_path: str | None = None, + layers: int | None = None, extra_args: Sequence[str] = (), + python: str | None = None) -> SmokePlan: + """The trainer smoke's steps (module doc). Raises :class:`SmokeError` for what is + missing: a backend without a train-only replay, a node without ``scratch``, no + store for the checkpoint, a registry placeholder no ``--smoke-arg`` fills.""" + if node.runtime != "docker": + raise SmokeError(f"node {node.name} runs {node.runtime}: the trainer smoke runs the image (runtime docker)") + if not node.scratch: + raise SmokeError(f"node {node.name} has no scratch: the cut model is written under the node's scratch " + "(inventory scratch: )") + if not store: + raise SmokeError("the trainer smoke writes its checkpoint to a run store: pass --smoke-store s3://BUCKET/PREFIX") + layout = smoke_layout(config, node, engine=engine, layers=layers) + engine = layout["engine"] + if engine not in TRAINER_BACKENDS: + raise SmokeError(f"no trainer smoke for backend {engine} yet (smoke recipes: {list(TRAINER_BACKENDS)}): " + "its train-only replay is not wired") + n = layout["layers"] + slug = f"{_slug(model)}-{n}layer" + repo = f"{SMOKE_MODEL_ORG}/{slug}" + host_hub = f"{node.scratch.rstrip('/')}/image-adopt/hub" + flags = _replace_flag([repo if f == f"{SMOKE_MODEL_ORG}/{_slug('m')}" else f for f in layout["flags"]], + extra_args) + unresolved = [f for f in flags if f.startswith("<")] + if unresolved: + raise SmokeError(f"the registry's flags for this model need {unresolved}: pass the flag with --smoke-arg " + "(e.g. --smoke-arg=--rl-expert-selection=/path/selection.json)") + # 1. prune: the cut as a hub snapshot on the node (models----/snapshots/) + source = model_path or f"hf://{model}" + cache = f"models--{SMOKE_MODEL_ORG}--{slug}" + script_b64 = base64.b64encode(PRUNE_SCRIPT.read_bytes()).decode() + mounts = ["-v", f"{host_hub}:{HUB_IN_CONTAINER}"] + if model_path: + mounts += ["-v", f"{model_path}:{model_path}:ro"] + inner = (f"set -euo pipefail; tmp={HUB_IN_CONTAINER}/.cut-{slug}; rm -rf \"$tmp\"; " + f"{PYTHON} /tmp/yeto-prune_layers.py {shlex.quote(source)} \"$tmp\" --layers {n}" + + (f" --revision {shlex.quote(model_revision)}" if model_revision and not model_path else "") + + f"; rev=$(sha1sum \"$tmp/config.json\" | cut -c1-40); " + f"mkdir -p {HUB_IN_CONTAINER}/{cache}/snapshots {HUB_IN_CONTAINER}/{cache}/refs; " + f"rm -rf {HUB_IN_CONTAINER}/{cache}/snapshots/$rev; mv \"$tmp\" {HUB_IN_CONTAINER}/{cache}/snapshots/$rev; " + f"printf %s \"$rev\" > {HUB_IN_CONTAINER}/{cache}/refs/main; echo {REVISION_MARK} $rev") + prune = (f"set -euo pipefail\nmkdir -p {shlex.quote(host_hub)}\n" + f"base64 -d > {shlex.quote(host_hub)}/.prune_layers.py <<'YETO_PRUNE_EOF'\n{script_b64}\nYETO_PRUNE_EOF\n" + + shlex.join(["docker", "run", "--rm", "--network", "host", *mounts, + "-v", f"{host_hub}/.prune_layers.py:/tmp/yeto-prune_layers.py:ro", + "-e", "HF_TOKEN", "-e", "HF_ENDPOINT", "--entrypoint", "bash", REF, "-c", inner]) + "\n") + prune_show = (f"docker run --rm {' '.join(mounts)} {REF} {PYTHON} scripts/prune_layers.py {source} " + f"/{cache}/snapshots/ --layers {n}") + # 2./3. train and resume: yeto launch of a one-node ssh: island + inventory = workdir / "inventory.yaml" + entry = inventory_entry(node, roles=["trainer"], image=None, + mounts={**dict(node.mounts), host_hub: HUB_IN_CONTAINER}) + facts = layout["recommendation"].facts + synth = {"lengths": [2048], "samples": 2, "prompt": 1024, "topk": 2, "layers": n, + "dense_layers": min(int(facts.first_k_dense or 0), n), "router_topk": max(1, int(facts.topk or 1)), + "experts": max(1, int(facts.num_experts or 1)), "vocab": int(facts.vocab)} + if synth["experts"] % synth["router_topk"]: + synth["router_topk"] = 1 + base = [python or sys.executable, "-m", "yeto.cli", "launch", *flags, "--model-revision", REVISION, + "--gpu", f"ssh:1x{node.cards_per_node}x{node.card}", "--rl-node-inventory", str(inventory), + "--rl-image", f"docker:{REF}", "--model-store", f"local://{HUB_IN_CONTAINER}", + "--rl-checkpoint-store", f"{store.rstrip('/')}/{run_id}", "--cluster-prefix", run_id, + "--island-env", f"{SYNTH_ENV}={json.dumps(synth, separators=(',', ':'))}", + "--island-env", f"{REPLAY_ENV}={REPLAY_PATH}", *extra_args] + steps = ( + SmokeStep("prune", "node", script=prune, timeout_s=PRUNE_TIMEOUT_S, expect=REVISION_MARK, show=prune_show), + SmokeStep("train", "launcher", argv=(*base, "--rl-stop-after-rounds", "1"), timeout_s=TRAIN_TIMEOUT_S), + SmokeStep("resume", "launcher", argv=(*base, "--rl-stop-after-rounds", "2"), timeout_s=TRAIN_TIMEOUT_S, + expect=r"rl_resume|resum(?:e|ed|ing) from"), + ) + import yaml # noqa: PLC0415 + + plan = layout["plan"] + notes = (f"{layout['recipe'].name} ({layout['recipe'].rl_model_recipe}, tuning {layout['tuning']}): " + f"the first {n} of {facts.layers} layers on one node, TP{plan['tensor_parallel']} " + f"PP{plan['pipeline_parallel']} EP{plan['expert_parallel']}, {plan['state_gib_per_card']} GiB state per card", + "train-only: synthetic rollouts replayed by the trainer (no sampler); the cut of round 1 is the " + "checkpoint, round 2 resumes from it") + return SmokePlan("trainer", node, steps, files={str(inventory): yaml.safe_dump({"nodes": [entry]}, + sort_keys=False)}, + notes=notes, data={"layers": n, "layout": {k: plan[k] for k in ( + "tensor_parallel", "pipeline_parallel", "expert_parallel", "data_parallel")}, + "recipe": layout["recipe"].rl_model_recipe, "tuning": layout["tuning"], "run": run_id, + "engine": engine}) + + +# --- sampler --------------------------------------------------------------------------- + + +def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: str | None = None, + code: tuple[str, bytes] | None = None) -> SmokePlan: + """The sampler smoke's steps: put the yeto tree and the spec on the node, then the + node runtime's container start of :mod:`yeto.node.smoke` on the image.""" + from yeto.node import launch as node_launch # noqa: PLC0415 + from yeto.node.code import tree_code_tar # noqa: PLC0415 + from yeto.node.profile import CONTAINER_WORK, node_dirs # noqa: PLC0415 + + profile = profile_of(node) + if profile.container not in ("docker", "podman"): + raise SmokeError(f"node {node.name} runs samplers as a {profile.container}: the image smoke needs a " + "container runtime (docker / podman)") + if not isinstance(spec.get("engine"), Mapping): + raise SmokeError("the sampler spec has no engine section") + sha, tar = code or tree_code_tar(REPO_ROOT) + work = node_dirs(profile)["work"] + base = f"{work}/image-adopt/{run_id}" + tree_host, tree_in = f"{work}/image-adopt/yeto/{sha}", f"{CONTAINER_WORK}/image-adopt/yeto/{sha}" + spec_host = f"{base}/spec.json" + spec_in = f"{CONTAINER_WORK}/image-adopt/{run_id}/spec.json" + put = (f"set -euo pipefail\nmkdir -p {shlex.quote(base)}\n" + f"if [ ! -d {shlex.quote(tree_host)}/yeto ]; then rm -rf {shlex.quote(tree_host)}.tmp; " + f"mkdir -p {shlex.quote(tree_host)}.tmp; base64 -d <<'YETO_TREE_EOF' | tar x -C {shlex.quote(tree_host)}.tmp\n" + f"{base64.b64encode(tar).decode()}\nYETO_TREE_EOF\nmv {shlex.quote(tree_host)}.tmp {shlex.quote(tree_host)}; fi\n" + f"cat > {shlex.quote(spec_host)} <<'YETO_SPEC_EOF'\n{json.dumps(dict(spec), indent=1)}\nYETO_SPEC_EOF\n") + env = {"PYTHONPATH": tree_in, "PYTHONUNBUFFERED": "1", **profile.family_env()} + argv = node_launch.container_argv(profile, name=f"yeto-adopt-{run_id}", image=REF, env=env, python=PYTHON, + spec_path=spec_in, module="yeto.node.smoke", + module_args=["--spec", spec_in, *(["--release", release] if release else [])]) + steps = (SmokeStep("upload", "node", script=put, timeout_s=600.0, + show=f"put the yeto tree {sha} at {tree_host} and the spec at {spec_host}"), + SmokeStep("engine", "node", script=shlex.join(argv), timeout_s=SAMPLER_TIMEOUT_S)) + engine = spec["engine"] + notes = (f"engine {engine.get('adapter') or engine.get('factory')}: start, generate, reload " + f"({'release ' + release if release else 'the base weights'} as version 1), generate",) + return SmokePlan("sampler", node, steps, notes=notes, data={"run": run_id, "code": sha}) + + +# --- run ------------------------------------------------------------------------------ + + +def run_plan(plan: SmokePlan, *, ops: Any, ref: str, python: str | None, + run: Callable[..., Any] = subprocess.run, clock: Callable[[], float] = time.time, + log: Callable[[str], None] = lambda m: print(m, file=sys.stderr, flush=True)): + """Every step of ``plan`` in order; the smoke's ``StepResult`` (``ok`` False names the + step and the output's tail).""" + from yeto.node.smoke import parse_result # noqa: PLC0415 + + values = {REF: ref, PYTHON: python or "python3"} + for path, text in plan.files.items(): + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(text) + t_start = clock() + times: dict[str, float] = {} + data: dict[str, Any] = {**plan.data, "steps": times} + + def failed(step: SmokeStep, why: str) -> Any: + return StepResult("smoke", False, f"{step.name}: {why}", clock() - t_start, data) + + for step in plan.steps: + step = step.render(values) + log(f"[image adopt] smoke {step.name} [{step.where}]") + t0 = clock() + try: + if step.where == "node": + done = ops.run(plan.node, step.script, timeout=step.timeout_s) + else: + done = run(list(step.argv), capture_output=True, text=True, timeout=step.timeout_s, check=False) + except Exception as error: # noqa: BLE001 - a timeout or a dead ssh is the step's failure + times[step.name] = round(clock() - t0, 1) + return failed(step, f"{type(error).__name__}: {error}"[:600]) + times[step.name] = round(clock() - t0, 1) + out = (getattr(done, "stdout", "") or "") + "\n" + (getattr(done, "stderr", "") or "") + result = parse_result(out) if plan.role == "sampler" and step.name == "engine" else None + if result is not None and not result.get("ok"): + data["engine_steps"] = result.get("seconds") + return failed(step, f"{result.get('step')} failed: {result.get('error')}") + if done.returncode != 0: + return failed(step, f"rc {done.returncode}: {out.strip()[-600:]}") + if step.expect and not re.search(step.expect, out): + return failed(step, f"the output has no {step.expect!r}: {out.strip()[-400:]}") + if step.name == "engine" and plan.role == "sampler": + if result is None: + return failed(step, f"no smoke result in the output: {out.strip()[-400:]}") + data["engine_steps"] = result.get("seconds") + if result.get("reload_mode"): + data["reload_mode"] = result["reload_mode"] + match = re.search(rf"{REVISION_MARK} ([0-9a-f]{{40}})", out) + if match: + values[REVISION] = match.group(1) + data["revision"] = match.group(1) + what = "one step trained, checkpoint saved and resumed" if plan.role == "trainer" else \ + "engine started, generated, reloaded and generated again" + return StepResult("smoke", True, f"{what} on {plan.node.name}", clock() - t_start, data) diff --git a/yeto/node/launch.py b/yeto/node/launch.py index 830e3a429..2ad3a8b38 100644 --- a/yeto/node/launch.py +++ b/yeto/node/launch.py @@ -112,11 +112,14 @@ def engine_prefix(profile: NodeProfile, sudo: bool) -> list[str]: def container_argv(profile: NodeProfile, *, name: str, image: str, env: Mapping[str, str], python: str, spec_path: str, env_files: Sequence[str] = (), cards: Sequence[int] | None = None, host_paths: Sequence[str] | None = None, sudo: bool = False, - labels: Mapping[str, str] | None = None) -> list[str]: + labels: Mapping[str, str] | None = None, module: str = SAMPLER_MODULE, + module_args: Sequence[str] | None = None) -> list[str]: """`` run --rm`` of the sampler in the foreground (the runtime is its parent). The yeto tree goes in front of the image's own ``PYTHONPATH`` inside the container (``-e PYTHONPATH=`` would drop it: the CANN ``acl`` module of an Ascend image). - ``labels``: ``--label`` flags (a leased node's run label; none: the argv as before).""" + ``labels``: ``--label`` flags (a leased node's run label; none: the argv as before). + ``module`` / ``module_args``: another yeto module started the same way (the image + smoke, :mod:`yeto.node.smoke`; default: the sampler with ``--spec``).""" argv = [*engine_prefix(profile, sudo), "run", "--rm", "--name", name, "--network", "host", "--ipc", "host"] for key, value in sorted((labels or {}).items()): argv += ["--label", f"{key}={value}"] @@ -131,8 +134,9 @@ def container_argv(profile: NodeProfile, *, name: str, image: str, env: Mapping[ if key != "PYTHONPATH": argv += ["-e", f"{key}={value}"] prelude = f'export PYTHONPATH={shlex.quote(tree)}"${{PYTHONPATH:+:$PYTHONPATH}}"; ' if tree else "" + rest = ["--spec", spec_path] if module_args is None else list(module_args) return [*argv, "--entrypoint", "bash", image, "-c", - f"{prelude}exec {shlex.quote(python)} -m {SAMPLER_MODULE} --spec {shlex.quote(spec_path)}"] + f"{prelude}exec {shlex.quote(python)} -m {module} {shlex.join(rest)}"] def stop_argv(profile: NodeProfile, name: str, *, sudo: bool = False) -> list[str]: diff --git a/yeto/node/smoke.py b/yeto/node/smoke.py new file mode 100644 index 000000000..dd2f81fee --- /dev/null +++ b/yeto/node/smoke.py @@ -0,0 +1,142 @@ +"""``python -m yeto.node.smoke --spec ``: a sampler image's smoke on this node. + +``yeto image adopt --role sampler`` (:mod:`yeto.launch.image_smoke`) runs this inside +the image it adopts, started the way the node runtime starts a sampler +(:func:`yeto.node.launch.container_argv`: the profile's device flags, the node's +directories at ``/work`` / ``/models`` / ``/root/.cache``). With the engine of the +pool's sampler spec (:func:`yeto.rl.engine.engine_sampler_entry.build_engine`, the +sampler's own factory) it + +1. ``start``: starts the engine on its base weights (policy version 0); +2. ``generate``: one completion; +3. ``reload``: loads the release ``--release`` (default: the engine's base weights) + as policy version 1, the reload the engine does for every trainer release (in + place, or a restart for an engine that cannot); +4. ``generate_after_reload``: one completion at version 1; + +then stops the engine. Every step prints a ``YETO_SMOKE`` line and the run ends with +``YETO_SMOKE_RESULT {"ok": ..., "step": , ...}``; the exit code is 0 +only when every step passed. +""" + +from __future__ import annotations + +import argparse +import json +import sys +import time +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +STEP_MARK = "YETO_SMOKE" +RESULT_MARK = "YETO_SMOKE_RESULT" +STEPS = ("start", "generate", "reload", "generate_after_reload") + + +def _emit(mark: str, record: Mapping[str, Any], out: Any) -> None: + print(f"{mark} {json.dumps(dict(record), sort_keys=True, default=str)}", file=out, flush=True) + + +def base_dir(spec: Mapping[str, Any]) -> str | None: + """The engine's base weights (``engine.server.base_dir``), if the spec names them.""" + server = (spec.get("engine") or {}).get("server") or {} + value = server.get("base_dir") + return str(value) if value else None + + +def run_smoke(engine: Any, *, release: str | None, prompt: str = "Say hello.", max_tokens: int = 16, + out: Any = None, clock: Callable[[], float] = time.monotonic) -> dict[str, Any]: + """The four steps on ``engine`` (a ``SamplerEngine``); the result record. The engine + is stopped whatever happened.""" + from yeto.rl.engine.sampler_engine import SamplingParams # noqa: PLC0415 + + out = out or sys.stdout + sampling = SamplingParams(max_tokens=int(max_tokens), temperature=0.0) + times: dict[str, float] = {} + record: dict[str, Any] = {"ok": False, "step": None, "seconds": times} + + def text_of(completions: Any) -> str: + first = completions[0][0] + return str(getattr(first, "text", "") or "")[:200] + + steps: list[tuple[str, Callable[[], Any]]] = [ + ("start", lambda: engine.start(None, 0)), + ("generate", lambda: text_of(engine.generate([prompt], sampling))), + ("reload", lambda: engine.load(Path(release) if release else None, 1)), + ("generate_after_reload", lambda: text_of(engine.generate([prompt], sampling))), + ] + try: + for name, fn in steps: + t0 = clock() + try: + value = fn() + except Exception as error: # noqa: BLE001 - the step's failure is the smoke's answer + times[name] = round(clock() - t0, 3) + record.update(step=name, error=f"{type(error).__name__}: {error}"[:600]) + _emit(STEP_MARK, {"step": name, "ok": False, "seconds": times[name], "error": record["error"]}, out) + return record + times[name] = round(clock() - t0, 3) + detail: dict[str, Any] = {} + if name.startswith("generate"): + detail["text"] = value + if not value: + record.update(step=name, error="the engine returned an empty completion") + _emit(STEP_MARK, {"step": name, "ok": False, "seconds": times[name], "error": record["error"]}, + out) + return record + elif value is not None and hasattr(value, "reload_mode"): + detail["reload_mode"] = value.reload_mode + record[f"{name}_mode"] = value.reload_mode + _emit(STEP_MARK, {"step": name, "ok": True, "seconds": times[name], **detail}, out) + served = getattr(engine, "served_version", lambda: None)() + if served is not None and int(served) != 1: + record.update(step="reload", error=f"the engine serves version {served} after the reload, not 1") + return record + record.update(ok=True, step=None) + return record + finally: + try: + engine.stop() + except Exception: # noqa: BLE001 - a failed stop does not change the answer + pass + + +def main(argv: list[str] | None = None, *, out: Any = None) -> int: + parser = argparse.ArgumentParser(prog="python -m yeto.node.smoke", description=__doc__.split("\n\n")[0]) + parser.add_argument("--spec", required=True, help="the sampler spec (JSON) whose engine is smoked") + parser.add_argument("--release", default=None, + help="the release directory the reload loads (default: engine.server.base_dir)") + parser.add_argument("--prompt", default="Say hello.") + parser.add_argument("--max-tokens", type=int, default=16) + args = parser.parse_args(argv) + out = out or sys.stdout + from yeto.rl.engine.engine_sampler_entry import build_engine # noqa: PLC0415 + + try: + spec = json.loads(Path(args.spec).read_text()) + engine = build_engine(spec) + except Exception as error: # noqa: BLE001 - a spec the engine refuses is the start's failure + record = {"ok": False, "step": "start", "error": f"{type(error).__name__}: {error}"[:600], "seconds": {}} + _emit(RESULT_MARK, record, out) + return 1 + record = run_smoke(engine, release=args.release or base_dir(spec), prompt=args.prompt, + max_tokens=args.max_tokens, out=out) + _emit(RESULT_MARK, record, out) + return 0 if record["ok"] else 1 + + +def parse_result(text: str) -> dict[str, Any] | None: + """The last ``YETO_SMOKE_RESULT`` record of a smoke's output (None: there is none).""" + found = None + for line in (text or "").splitlines(): + if line.startswith(RESULT_MARK + " "): + try: + found = json.loads(line[len(RESULT_MARK) + 1:]) + except ValueError: + continue + return found + + +if __name__ == "__main__": + raise SystemExit(main()) From 008fe0dad17dc2e399c4401832108e40cf72dd98 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 17:49:06 +0800 Subject: [PATCH 2/7] image adopt smoke: a launch the real checks take, idle nodes, cleanup, no injection - the trainer smoke launch carries what the launch's checks need: one island with no syncer, the local controller, trust-remote-code, a small local prompt file with the built-in numeric reward, an inner LR and no launcher-side model preflight (the cut exists only on the node); a test runs the rendered argv through the real parser in a dry run - the node is checked idle again right before the smoke; whatever the outcome the smoke's containers are removed and its run stopped, and the cut, the store checkpoint and the launcher files are deleted unless --keep-smoke-artifacts (then named with their size) - the prune downloads into a cache next to the cut, removed after it, and the scratch is checked for room for both first - node scripts are built after the values are known: argv elements of shlex.join, the interpreter quoted inside shell strings; a reference outside the docker grammar and an interpreter that is not a plain path are refused - train passes on an rl_round_cut event whose manifest is in the store; resume on an rl_resume / rl_round_cut_restored event naming that cut - the sampler record takes the spec's engine; a contradicting --engine is refused at fit; the trainer record names the backend the smoke ran - tuning (overridable with --smoke-arg) and a dropped MTP are in the notes and the evidence; a sampler smoke with neither --release nor base_dir is refused at plan; HF_TOKEN goes from the launcher to the node, unprinted - --strict-arch, --allow-busy and --keep-smoke-artifacts on the command; the docs cover each of these Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 139 +++++++---- tests/test_image_smoke.py | 372 +++++++++++++++++++++++++---- tests/test_run_flags.py | 3 +- yeto/launch/image_adopt.py | 54 ++++- yeto/launch/image_smoke.py | 473 +++++++++++++++++++++++++++++-------- 5 files changed, 841 insertions(+), 200 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index b606ca2c0..a6e4ee600 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -716,66 +716,98 @@ names no image runs it for that model. ``` yeto image adopt REGISTRY/IMAGE:TAG --model ORG/MODEL --role trainer \ - --inventory cluster.yaml --smoke-store s3://BUCKET/image-smoke --dry-run + --inventory cluster.yaml --model-config config.json \ + --smoke-store s3://BUCKET/image-smoke --dry-run yeto image adopt REGISTRY/IMAGE:TAG --model ORG/MODEL --role sampler \ --inventory cluster.yaml --sampler-spec sampler-spec.json --dry-run ``` `--dry-run` prints every step with its commands and reaches no registry and no -node. Drop it to adopt the image. The steps, in order: - -1. **manifest**: yeto asks the registry for the image's manifest (with the - registry login a pull would use: `SKYPILOT_DOCKER_USERNAME` / - `SKYPILOT_DOCKER_PASSWORD` / `SKYPILOT_DOCKER_SERVER`, else - `~/.docker/config.json`) and pins a tag to its digest. A missing manifest - stops here, before any node is contacted. -2. **probe**: one node (`--node`, default the first of the role) runs the image once - with its cards and reads the CPU architecture, Python, torch, CUDA or HIP, the - card architectures the image's kernels were built for, the engine packages and - the yeto image lock (`/opt/yeto/image`). +node (`--model-config` gives it the model's `config.json`; without it the real run +reads the local HF cache or fetches `config.json` from the Hub). Drop `--dry-run` +to adopt the image. The steps, in order: + +1. **manifest**: yeto checks that the reference is a docker reference, asks the + registry for the image's manifest (with the registry login a pull would use: + `SKYPILOT_DOCKER_USERNAME` / `SKYPILOT_DOCKER_PASSWORD` / + `SKYPILOT_DOCKER_SERVER`, else `~/.docker/config.json`) and pins a tag to its + digest. A missing manifest stops here, before any node is contacted. +2. **probe**: one node (`--node`, default the first of the role) is checked first: + SSH, the host probe and room in its image root, and that its cards are idle (no + process in `nvidia-smi`, `amd-smi` / `rocm-smi` or `npu-smi`, no running `yeto-` + container; `--allow-busy` goes on with a warning). It then runs the image once, + with its container engine and without cards, and reads the CPU architecture, + Python, torch, CUDA or HIP, the card architectures the image's kernels were + built for (torch's build flags; only when they are empty does it run again with + the node's cards), the engine packages and the yeto image lock + (`/opt/yeto/image`). 3. **fit**: the image against every node of the role: CPU architecture, device - runtime, card architecture (a node's `sm_N` must be built, or a `compute_M` PTX - with M <= N; a ROCm node's `gfx` target must be built), the trainer image - floors yeto knows, and the role's engine package. A mismatch names the image's - lowest card architecture and the node's card, for example - `the image is built for sm_90/sm_100 (lowest sm90); node a100-0 has A100-80GB (sm80)`. + runtime, card architecture, the trainer image floors yeto knows, and the role's + engine package (a sampler: the engine of the sampler spec, which `--engine` + must not contradict). Card architectures follow the CUDA binary compatibility + rules: a cubin `sm_XY` runs on the same major version with an equal or higher + minor (an `sm_100` image runs on B300, `sm103`), `sm_XYa` only on exactly X.Y, + PTX `compute_XY` is compiled on any X.Y or newer card (`compute_XYa` only on + X.Y). A pass by the minor-version rule or PTX is noted in the result and the + evidence (`compatible by CUDA minor-version rule; the smoke test is the final + check`): the smoke runs real kernels on the card. `--strict-arch` asks for a + cubin of exactly the node's architecture. A ROCm node's `gfx` target must be + built (feature suffixes such as `:xnack-` are ignored). A mismatch names the + rule and the node's card. 4. **pull**: every node of the role (spares included, `roles: [trainer-spare]`) is checked over SSH, and its image root (the docker data root, or `/var/lib/containerd` with the containerd image store) must have `--min-image-free-gib` free (default 120). Only when every node passes does the - pull run, on all nodes in parallel. A node that fails is named with the + pull run, on all docker nodes in parallel. A node that fails is named with the preflight's finding or docker's error line. -5. **smoke**, on the probe node: +5. **smoke**, on the probe node, after its cards are checked idle again: - **trainer**: the model is cut to its first N layers (all their experts, the - embeddings and the head, `scripts/prune_layers.py`), N being the largest, at - most 16, whose trainer state fits one node in the model registry's sizing - (`yeto adapt`'s backend and recipe for the full model). A one-node `ssh:` - island then trains one round on synthetic rollouts (no sampler), ends it with - a cut in `--smoke-store`, and a second launch resumes from that cut and trains - another round. The node needs `scratch:` in the inventory (the cut model is - written there). `--model-path` takes the checkpoint from a directory on the - node instead of the Hub. When the registry's flags for the model need a file - (for example `--rl-expert-selection` for Kimi K3.1), pass it with + embeddings and the head, `scripts/prune_layers.py`; MTP layers are dropped, + and the result says so), N being the largest, at most 16, whose trainer + state fits one node in the model registry's sizing (`yeto adapt`'s backend, + recipe and tuning for the full model; `--smoke-arg=--tuning=full` picks + another tuning). The node's `scratch:` (required in the inventory) must have + room for the cut and the shards it downloads, about twice the cut's size; + the download cache is removed after the cut. A one-node `ssh:` island then + trains one round on synthetic rollouts (no sampler, no syncer, a small local + prompt file and a built-in reward), ends it with a cut in `--smoke-store` + (the trainer's `rl_round_cut` event and the cut's manifest in the store are + checked), and a second launch resumes from that cut (its `rl_resume` event + must name the same cut) and trains another round. `--model-path` takes the + checkpoint from a directory on the node instead of the Hub. A gated model + needs `HF_TOKEN` in the environment of `yeto image adopt`: it is passed to + the node's cut, never printed. When the registry's flags for the model need + a file (for example `--rl-expert-selection` for Kimi K3.1), pass it with `--smoke-arg=--rl-expert-selection=/path/selection.json`; any other - `yeto launch` flag the run needs goes the same way. Only the Miles backend has - a trainer smoke so far. + `yeto launch` flag the run needs goes the same way. Only the Miles backend + has a trainer smoke so far. - **sampler**: the engine of `--sampler-spec` (the pool's sampler spec) starts in the image the way the node runtime starts a sampler (the node's device flags and directories), generates once, reloads (the weights of `--release`, - default its base weights, as policy version 1) and generates again. A failing - step is named, for example `smoke failed: engine: reload failed: ...`. - -Any failed step stops the adoption and leaves the catalog unchanged. After a -passing smoke the catalog gets a `verified-smoke` record with the digest, the -versions the probe read and the evidence of the run (time, node, seconds per -step, the nodes that pulled the image). + else the spec's `engine.server.base_dir`, as policy version 1; one of the two + is required) and generates again. The reload checks the engine's hot-reload + endpoint only, not the format of a trainer release. A failing step is named, + for example `smoke failed: engine: reload failed: ...`. + + Whatever the smoke's outcome, a failure or a timeout, its containers are + removed and its run stopped (`yeto down`), and its artifacts are deleted: the + cut on the node, the checkpoint under `--smoke-store`, the launcher's files. + `--keep-smoke-artifacts` keeps them and prints where they are and their size. + +Any failed step stops the adoption and leaves the catalog unchanged. The image +stays pulled on the nodes that already have it (the error names them): a retry +reuses it, and `docker rmi` on those nodes frees the room. After a passing smoke +the catalog gets a `verified-smoke` record with the digest, the versions the probe +read and the evidence of the run (time, node, seconds per step, the nodes that +pulled the image, the smoke's layout and tuning, and any compatibility notes). Two +adoptions that write one catalog at the same time take turns on a lock next to it. ### The site image catalog -The catalog is `~/.yeto/site-images.yaml`, or the file the inventory names with -its top-level `site_images:` (a relative path is taken from the inventory's -directory): +The catalog is `~/.yeto/site-images.yaml` (`YETO_SITE_IMAGES_PATH` moves it), or +the file the inventory names with its top-level `site_images:` (a relative path is +taken from the inventory's directory): ```yaml site_images: images/site-images.yaml @@ -801,22 +833,30 @@ images: status: verified-smoke # verified-smoke | retired ``` -To stop using a record, set its `status: retired`. A broken catalog (bad YAML, an -unknown key, a tag instead of a digest) is refused with the file and the record -named, but only by a run that reads it. +One image adopted on two kinds of nodes keeps one record per CPU and card +architecture. `evidence.at` is an ISO-8601 time with its time zone. To stop using a +record, set its `status: retired`. A broken record (bad YAML, a tag instead of a +digest, an unknown card architecture, a time without a zone) is refused with the +file and the record named, but only by a run that reads it; a key the reader does +not know, or a newer catalog `version`, is a warning. ### Which image a run uses -For an `ssh:` trainer island and an ssh sampler pool node: +For an `ssh:` trainer island (when every `--gpu` entry is `ssh:`) and an ssh +sampler pool node: 1. the image the configuration names: `--rl-image`, an inventory `image:` or `images:`, a pool's `container.image`. The catalog is not read; -2. else the newest `verified-smoke` record of the catalog for the run's model and - role whose CPU architecture, card architecture and device family match every - node of the island (or the pool node); +2. else the newest `verified-smoke` record of the catalog for the run's model (an + alias such as `qwen3-8b` is resolved first) and role whose CPU architecture, + card architecture and device family match every node of the island (for a + pool: every node of the pool, so a spare starts the same image); 3. else the built-in default (the pinned `--rl-image`, or the engine image catalog's choice for a pool's `container.image: auto`). +A fleet that mixes `ssh:` and cloud islands takes the built-in default and says +so. A pool chooses its images once, at its first start, and keeps them in its +state: a replacement node and a restarted pool controller start the same image. The launcher and `pool --dry-run` print the image and where it came from, for example: @@ -824,5 +864,6 @@ example: [launcher] ssh trainer image REGISTRY/IMAGE@sha256:... (adopted 2026-11-26T10:00:00Z on b300-0) (source: site image catalog ...) ``` -A configuration that names its image prints nothing new and runs exactly as -before. +When it falls back to the default, the line names the closest records and why +they do not fit. A configuration that names its image prints nothing new and runs +exactly as before. diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index a24a4e210..412203e5c 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -27,6 +27,7 @@ from yeto.launch import site_images as si from yeto.node import smoke as node_smoke from yeto.rl.adapters.sampler_engines.fake import FakeEngine +from yeto.rl.engine.object_store import DirectoryObjectStore ROOT = Path(__file__).resolve().parents[1] REGISTRY_CONFIGS = ROOT / "tests" / "data" / "model_registry" @@ -35,12 +36,16 @@ FAKE_SPEC = {"sampler_id": "adopt", "engine": {"factory": "yeto.rl.adapters.sampler_engines.from_spec:build", "adapter": "fake", "kwargs": {}}} REV = "f" * 40 +PY = "/usr/bin/python3" +RELEASE = "/models/r1" @pytest.fixture(autouse=True) def _env(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path / "home")) monkeypatch.delenv("YETO_IMAGE_MANIFEST_CHECK", raising=False) + monkeypatch.delenv(si.PATH_ENV, raising=False) + monkeypatch.delenv("HF_TOKEN", raising=False) def node(i=0, **kw): @@ -97,6 +102,9 @@ def __init__(self, nodes, tmp_path, *, pythonpath=(), **kw): self.pythonpath = pythonpath def run(self, node, script, *, timeout=300.0): + if script.startswith(("docker rm -f", "rm -rf", "du -sh")): + self.scripts.append((node.name, "cleanup-" + script.split()[0])) + return self.done(0, "") if "YETO_TREE_EOF" in script: self.scripts.append((node.name, "upload")) spec = re.search(r"<<'YETO_SPEC_EOF'\n(.*)\nYETO_SPEC_EOF", script, re.S).group(1) @@ -114,14 +122,16 @@ def run(self, node, script, *, timeout=300.0): return super().run(node, script, timeout=timeout) -def _adopt(nodes, tmp_path, plan, ops, role): +def _adopt(nodes, tmp_path, plan, ops, role, **kw): opener, _ = registry({"k99": 200}) req = ia.AdoptRequest(ref=TAGGED, model="org/new-model", role=role, nodes=tuple(nodes), - catalog=str(tmp_path / "site-images.yaml"), engine=plan.data.get("engine")) + catalog=str(tmp_path / "site-images.yaml"), engine=plan.data.get("engine"), **kw) + store = tmp_path / "store" def smoke(adopter, ref, facts, engine): - return sm.run_plan(plan, ops=adopter.ops, ref=ref, python=facts.python_path, log=lambda m: None, - run=getattr(ops, "launch", subprocess.run), clock=lambda: 0.0) + return sm.run_plan(plan, ops=adopter.ops, ref=ref, python=facts.python_path, + log=getattr(ops, "logs", []).append, run=getattr(ops, "launch", subprocess.run), clock=lambda: 0.0, + objects_for=lambda uri: DirectoryObjectStore(store), environ={}) return ia.Adopter(req, ops=ops, smoke=smoke, urlopen=opener, login=None, log=lambda m: None, clock=lambda: FakeCluster.NOW) @@ -129,14 +139,16 @@ def smoke(adopter, ref, facts, engine): def test_a_sampler_image_whose_smoke_passes_is_recorded(tmp_path): nodes = [node(0), node(1)] - plan = sm.sampler_plan(nodes[0], spec=FAKE_SPEC, run_id="adopt-t", code=("t000", b"tar")) - report = _adopt(nodes, tmp_path, plan, SmokeNodes(nodes, tmp_path), "sampler").run() + plan = sm.sampler_plan(nodes[0], spec=FAKE_SPEC, run_id="adopt-t", release=RELEASE, code=("t000", b"tar")) + ops = SmokeNodes(nodes, tmp_path) + report = _adopt(nodes, tmp_path, plan, ops, "sampler").run() assert report.ok and report.steps[-1].detail.startswith("engine started, generated, reloaded") (rec,) = si.load(tmp_path / "site-images.yaml") assert (rec.role, rec.engine, rec.ref, rec.card_archs) == ("sampler", "vllm", si.parse_record( rec.to_doc()).ref, ("sm103",)) assert rec.evidence["smoke"]["reload_mode"] == "in_place" assert set(rec.evidence["smoke"]["engine_steps"]) == set(node_smoke.STEPS) + assert ops.kinds()[-2:] == ["cleanup-docker", "cleanup-rm"] # the container, then the run's directory def test_a_sampler_whose_reload_fails_is_not_recorded(tmp_path): @@ -145,10 +157,12 @@ def test_a_sampler_whose_reload_fails_is_not_recorded(tmp_path): "def build(section):\n return ReloadFails()\n") spec = {"sampler_id": "adopt", "engine": {"factory": "adopt_fail_engine:build"}} nodes = [node(0)] - plan = sm.sampler_plan(nodes[0], spec=spec, run_id="adopt-t", code=("t000", b"tar")) + plan = sm.sampler_plan(nodes[0], spec=spec, run_id="adopt-t", release=RELEASE, code=("t000", b"tar")) + ops = SmokeNodes(nodes, tmp_path, pythonpath=[tmp_path]) with pytest.raises(ia.AdoptError) as error: - _adopt(nodes, tmp_path, plan, SmokeNodes(nodes, tmp_path, pythonpath=[tmp_path]), "sampler").run() + _adopt(nodes, tmp_path, plan, ops, "sampler").run() assert error.value.step == "smoke" + assert ops.kinds()[-2:] == ["cleanup-docker", "cleanup-rm"] # removed although the smoke failed assert error.value.reason.startswith("engine: reload failed: RuntimeError: update_weights_from_disk answered 500") assert not (tmp_path / "site-images.yaml").exists() @@ -158,17 +172,22 @@ def test_the_sampler_smoke_starts_like_the_node_runtime(): from yeto.node import launch as node_launch n = node(0) - plan = sm.sampler_plan(n, spec=FAKE_SPEC, run_id="adopt-t", code=("t000", b"tar")) - engine = shlex.split(plan.steps[1].script) - runtime = node_launch.container_argv(profile_of(n), name="yeto-adopt-adopt-t", image=sm.REF, + plan = sm.sampler_plan(n, spec=FAKE_SPEC, run_id="adopt-t", release=RELEASE, code=("t000", b"tar")) + engine = shlex.split(plan.steps[1].render({sm.REF: PINNED, sm.PYTHON: PY}).script) + runtime = node_launch.container_argv(profile_of(n), name="yeto-adopt-adopt-t", image=PINNED, env={"PYTHONPATH": "/work/image-adopt/yeto/t000", "PYTHONUNBUFFERED": "1", **profile_of(n).family_env()}, - python=sm.PYTHON, spec_path="/work/image-adopt/adopt-t/spec.json") + python=PY, spec_path="/work/image-adopt/adopt-t/spec.json") assert engine[:-1] == runtime[:-1] # the same flags, mounts and environment - assert engine[-1].endswith("-m yeto.node.smoke --spec /work/image-adopt/adopt-t/spec.json") + assert engine[-1].endswith(f"exec {PY} -m yeto.node.smoke --spec /work/image-adopt/adopt-t/spec.json " + f"--release {RELEASE}") assert runtime[-1].endswith(f"-m {node_launch.SAMPLER_MODULE} --spec /work/image-adopt/adopt-t/spec.json") with pytest.raises(sm.SmokeError, match="needs a container runtime"): - sm.sampler_plan(node(0, runtime="rootfs"), spec=FAKE_SPEC, run_id="x", code=("t", b"")) + sm.sampler_plan(node(0, runtime="rootfs"), spec=FAKE_SPEC, run_id="x", release=RELEASE, code=("t", b"")) + with pytest.raises(sm.SmokeError, match="pass --release"): # no release, no base_dir: nothing to reload + sm.sampler_plan(n, spec=FAKE_SPEC, run_id="x", code=("t", b"")) + based = {**FAKE_SPEC, "engine": {**FAKE_SPEC["engine"], "server": {"base_dir": "/models/base"}}} + assert sm.sampler_plan(n, spec=based, run_id="x", code=("t", b"")).steps # -- the trainer smoke ---------------------------------------------------------------- @@ -195,8 +214,12 @@ def test_the_trainer_plan_cuts_trains_and_resumes_on_one_node(tmp_path): plan = _trainer_plan(tmp_path) assert [s.name for s in plan.steps] == ["prune", "train", "resume"] prune, train, resume = plan.steps - assert "--layers 16" in prune.script and "hf://Qwen/Qwen3-30B-A3B" in prune.script - assert "base64 -d" in prune.script and sm.REVISION_MARK in prune.script + script = prune.render({sm.REF: PINNED, sm.PYTHON: PY}, {}).script + assert "--layers 16" in script and "hf://Qwen/Qwen3-30B-A3B" in script + assert "base64 -d" in script and sm.REVISION_MARK in script + assert f"--cache-dir {sm.HUB_IN_CONTAINER}/.dl-Qwen3-30B-A3B-16layer" in script # not the docker root + assert f"rm -rf {sm.HUB_IN_CONTAINER}/.dl-Qwen3-30B-A3B-16layer" in script + assert f"the shards it reads need {round(sm.cut_gib(QWEN, 16) * 2.2 + 1, 1)} GiB" in script argv = list(train.argv) assert argv[:4] == ["py", "-m", "yeto.cli", "launch"] for flag, value in (("--rl-backend", "miles"), ("--gpu", "ssh:1x8xB300"), ("--rl-image", f"docker:{sm.REF}"), @@ -205,23 +228,36 @@ def test_the_trainer_plan_cuts_trains_and_resumes_on_one_node(tmp_path): ("--rl-checkpoint-store", "s3://bucket/smoke/adopt-t"), ("--rl-stop-after-rounds", "1")): assert argv[argv.index(flag) + 1] == value assert argv.count("--model") == 1 - assert list(resume.argv)[-2:] == ["--rl-stop-after-rounds", "2"] and resume.expect + for flag in ("--rl-single-island-no-sync", "--trust-remote-code", "--rl-allow-local-data"): + assert flag in argv + assert argv[argv.index("--controller") + 1] == "local" + assert argv[argv.index("--reward-function") + 1] == sm.REWARD + prompts = Path(argv[argv.index("--data") + 1]) + assert [json.loads(line)["label"] for line in plan.files[str(prompts)].splitlines()] == ["4", "8"] + assert list(resume.argv)[-2:] == ["--rl-stop-after-rounds", "2"] + assert (train.check, resume.check, resume.expect) == ("round_cut", "resume", None) synth = json.loads(next(a for a in argv if a.startswith(sm.SYNTH_ENV + "=")).split("=", 1)[1]) assert synth["layers"] == 16 and synth["experts"] == 128 and synth["router_topk"] == 8 - (inventory, text), = plan.files.items() + text = plan.files[argv[argv.index("--rl-node-inventory") + 1]] (entry,) = yaml.safe_load(text)["nodes"] assert entry["mounts"]["/mnt/nvme/yeto/image-adopt/hub"] == sm.HUB_IN_CONTAINER and "image" not in entry assert entry["mounts"]["/mnt/nvme/models"] == "/data/models" # the node's own mounts stay assert entry["roles"] == ["trainer"] and entry["scratch"] == "/mnt/nvme/yeto" assert plan.data["layers"] == 16 and plan.data["engine"] == "miles" assert any("16 of 48 layers" in n for n in plan.notes) + assert any("tuning lora (the registry's; --smoke-arg=--tuning=... overrides it)" in n for n in plan.notes) + assert plan.data["notes"] == list(plan.notes) and plan.data["tuning"] == "lora" def test_a_node_path_takes_the_checkpoint_from_the_node(tmp_path): - prune = _trainer_plan(tmp_path, model_path="/mnt/models/qwen3", model_revision="abc").steps[0] - assert "/mnt/models/qwen3:/mnt/models/qwen3:ro" in prune.script and "hf://" not in prune.script - assert "--revision" not in prune.script - assert "--revision abc" in _trainer_plan(tmp_path, model_revision="abc").steps[0].script + def script(**kw): + return _trainer_plan(tmp_path, **kw).steps[0].render({sm.REF: PINNED, sm.PYTHON: PY}, {}).script + + local = script(model_path="/mnt/models/qwen3", model_revision="abc") + assert "/mnt/models/qwen3:/mnt/models/qwen3:ro" in local and "hf://" not in local + assert "--revision" not in local and "--cache-dir" not in local + assert "--revision abc --cache-dir" in script(model_revision="abc") + assert "--revision" not in script() @pytest.mark.parametrize("kw, message", [ @@ -245,16 +281,37 @@ def test_a_registry_placeholder_needs_a_smoke_arg(tmp_path): assert "" not in argv +def event(name, **fields): + record = {"event": name, "island_id": 0, "time_unix": 1.0, **fields} + return "[cluster] YETO_RL_EVENT " + json.dumps(record, sort_keys=True, separators=(",", ":")) + + +CUT = "r000001-abc" + + class Launches: - """The launcher's subprocess for the train and resume steps.""" + """The launcher's subprocess for the train and resume steps (the train writes its + cut's manifest into the store ``store``), and the cleanup's ``yeto down``.""" - def __init__(self, resume_out="rl_resume: from cut round 1", rc=0): - self.calls, self.resume_out, self.rc = [], resume_out, rc + def __init__(self, store=None, *, resume_out=None, train_out=None, rc=0, manifest=True, timeout=False): + self.calls, self.downs, self.store, self.rc = [], [], store, rc + self.resume_out = event("rl_resume", cut_id=CUT) if resume_out is None else resume_out + self.train_out = event("rl_round_cut", ok=True, cut_id=CUT) if train_out is None else train_out + self.manifest, self.timeout = manifest, timeout def __call__(self, argv, **kw): + if "down" in argv: + self.downs.append(argv) + return subprocess.CompletedProcess(argv, 0, stdout="", stderr="") self.calls.append(argv) + if self.timeout: + raise subprocess.TimeoutExpired(argv, kw.get("timeout")) resume = argv[-1] == "2" - return subprocess.CompletedProcess(argv, self.rc, stdout=self.resume_out if resume else "round 1 cut", + if not resume and self.manifest and self.store is not None: + cut = Path(self.store) / "island-0" / "round-cuts" / CUT + cut.mkdir(parents=True, exist_ok=True) + (cut / "manifest.json").write_text("{}") + return subprocess.CompletedProcess(argv, self.rc, stdout=self.resume_out if resume else self.train_out, stderr="") @@ -262,8 +319,12 @@ class TrainerNodes(FakeNodes): def __init__(self, nodes, launches, **kw): super().__init__(nodes, **kw) self.launch = launches + self.logs = [] def run(self, node, script, *, timeout=300.0): + if script.startswith(("docker ps -aq", "rm -rf", "du -sh")): + self.scripts.append((node.name, "cleanup-" + script.split()[0])) + return self.done(0, "4.0G\t/mnt/nvme/yeto/image-adopt/hub/models--x\n" if script.startswith("du") else "") if "YETO_PRUNE_EOF" in script: self.scripts.append((node.name, "prune")) assert PINNED in script and "/usr/bin/python3 /tmp/yeto-prune_layers.py" in script @@ -274,28 +335,72 @@ def run(self, node, script, *, timeout=300.0): def test_a_trainer_image_whose_smoke_passes_is_recorded(tmp_path): nodes = [node(0), node(1)] plan = _trainer_plan(tmp_path) - launches = Launches() - report = _adopt(nodes, tmp_path, plan, TrainerNodes(nodes, launches), "trainer").run() + launches = Launches(tmp_path / "store") + ops = TrainerNodes(nodes, launches) + report = _adopt(nodes, tmp_path, plan, ops, "trainer").run() assert report.ok train, resume = launches.calls assert train[train.index("--model-revision") + 1] == REV and resume[resume.index("--rl-image") + 1] == \ f"docker:{PINNED}" - assert Path(train[train.index("--rl-node-inventory") + 1]).is_file() + assert train[train.index("--rl-node-inventory") + 1] in plan.files # written for the run, deleted after (rec,) = si.load(tmp_path / "site-images.yaml") assert (rec.role, rec.engine, rec.model) == ("trainer", "miles", "org/new-model") assert rec.evidence["smoke"]["layers"] == 16 and rec.evidence["smoke"]["revision"] == REV assert set(rec.evidence["smoke"]["steps"]) == {"prune", "train", "resume"} + assert rec.evidence["smoke"]["cut_id"] == CUT and rec.evidence["smoke"]["tuning"] == "lora" + assert rec.evidence["notes"] == plan.data["notes"] + # the cleanup: the run stopped, the containers and the cut removed, the store and launcher files deleted + assert launches.downs and launches.downs[0][-3:] == ["down", "adopt-t", "--missing-ok"] + assert ops.kinds()[-2:] == ["cleanup-docker", "cleanup-rm"] + assert not list((tmp_path / "store").rglob("manifest.json")) and not (tmp_path / "work").exists() -@pytest.mark.parametrize("launches, message", [ - (Launches(resume_out="round 2 done"), "resume: the output has no"), - (Launches(rc=1), "train: rc 1"), +@pytest.mark.parametrize("kw, message", [ + ({"resume_out": "rl_resume: resumed from cut round 1"}, "resume: no rl_resume / rl_round_cut_restored event"), + ({"resume_out": event("rl_round_cut_restored", cut_id="r000009-old")}, + r"resume: it resumed from \['r000009-old'\], not the cut r000001-abc"), + ({"train_out": "round 1 cut"}, "train: no rl_round_cut event with a cut_id"), + ({"train_out": event("rl_round_cut", ok=False, error="disk")}, "train: no rl_round_cut event"), + ({"train_out": event("rl_round_cut", ok=False, cut_id=CUT, error="disk")}, "train: no rl_round_cut event"), + ({"manifest": False}, "train: the store has no round-cuts/r000001-abc/manifest.json"), + ({"rc": 1}, "train: rc 1"), + ({"timeout": True}, "train: TimeoutExpired"), ]) -def test_a_trainer_smoke_that_does_not_resume_or_train_is_not_recorded(tmp_path, launches, message): +def test_a_trainer_smoke_that_does_not_resume_or_train_is_not_recorded_and_cleans_up(tmp_path, kw, message): nodes = [node(0)] + launches = Launches(tmp_path / "store", **kw) + ops = TrainerNodes(nodes, launches) with pytest.raises(ia.AdoptError, match=message): - _adopt(nodes, tmp_path, _trainer_plan(tmp_path), TrainerNodes(nodes, launches), "trainer").run() + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), ops, "trainer").run() assert not (tmp_path / "site-images.yaml").exists() + assert launches.downs and ops.kinds()[-2:] == ["cleanup-docker", "cleanup-rm"] + assert not list((tmp_path / "store").rglob("*.json")) and not (tmp_path / "work").exists() + + +def test_kept_smoke_artifacts_are_named_with_their_size(tmp_path): + nodes = [node(0)] + launches = Launches(tmp_path / "store") + ops = TrainerNodes(nodes, launches) + _adopt(nodes, tmp_path, _trainer_plan(tmp_path, keep=True), ops, "trainer").run() + assert ops.kinds()[-2:] == ["cleanup-docker", "cleanup-du"] and launches.downs + assert list((tmp_path / "store").rglob("manifest.json")) and (tmp_path / "work").is_dir() + assert "[image adopt] kept on b300-0: 4.0G\t/mnt/nvme/yeto/image-adopt/hub/models--x" in ops.logs + assert any(m.startswith("[image adopt] kept in the store: s3://bucket/smoke/adopt-t (1 object(s))") + for m in ops.logs) + assert any(m.startswith(f"[image adopt] kept on the launcher: {tmp_path / 'work'} (") for m in ops.logs) + + +def test_a_prune_short_of_room_names_the_room_it_needs(tmp_path): + class Full(TrainerNodes): + def run(self, node, script, *, timeout=300.0): + if "YETO_PRUNE_EOF" in script: + return self.done(7, f"{sm.SPACE_MARK} /mnt/nvme/yeto/image-adopt/hub has 3 GiB free; the cut (5.8 GiB) " + "and the shards it reads need 13.8 GiB\n") + return super().run(node, script, timeout=timeout) + nodes = [node(0)] + with pytest.raises(ia.AdoptError, match=r"step smoke failed: prune: /mnt/nvme/yeto/image-adopt/hub has 3 GiB " + r"free; the cut \(5.8 GiB\) and the shards it reads need 13.8 GiB"): + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), Full(nodes, Launches(tmp_path / "store")), "trainer").run() def test_a_prune_without_a_revision_stops_the_smoke(tmp_path): @@ -306,7 +411,7 @@ def run(self, node, script, *, timeout=300.0): return super().run(node, script, timeout=timeout) nodes = [node(0)] with pytest.raises(ia.AdoptError, match="prune: the output has no 'YETO_SMOKE_REVISION'"): - _adopt(nodes, tmp_path, _trainer_plan(tmp_path), NoRev(nodes, Launches()), "trainer").run() + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), NoRev(nodes, Launches(tmp_path / "store")), "trainer").run() DOCKER_SHIM = r"""#!/usr/bin/env python3 @@ -350,7 +455,7 @@ def test_the_prune_script_on_the_node_writes_a_hub_snapshot(tmp_path): shim.chmod(0o755) n = node(0, scratch=str(tmp_path / "scratch")) plan = _trainer_plan(tmp_path, node=n, model_path=str(src), layers=4) - prune = plan.steps[0].render({sm.REF: PINNED, sm.PYTHON: sys.executable}) + prune = plan.steps[0].render({sm.REF: PINNED, sm.PYTHON: sys.executable}, {}) done = subprocess.run(["bash", "-c", prune.script], capture_output=True, text=True, timeout=120, env={**os.environ, "PATH": f"{shim.parent}{os.pathsep}{os.environ['PATH']}"}) assert done.returncode == 0, done.stdout + done.stderr @@ -368,6 +473,21 @@ def test_the_prune_script_on_the_node_writes_a_hub_snapshot(tmp_path): assert not list((tmp_path / "scratch" / "image-adopt" / "hub").glob(".cut-*")) # the temporary cut moved +def test_a_scratch_without_room_for_the_cut_stops_the_prune(tmp_path, monkeypatch): + shim = tmp_path / "bin" / "docker" + shim.parent.mkdir() + shim.write_text("#!/bin/sh\necho docker ran; exit 0\n") + shim.chmod(0o755) + monkeypatch.setattr(sm, "cut_gib", lambda config, layers: 1e9) + plan = _trainer_plan(tmp_path, node=node(0, scratch=str(tmp_path / "scratch")), layers=4) + prune = plan.steps[0].render({sm.REF: PINNED, sm.PYTHON: PY}, {}) + done = subprocess.run(["bash", "-c", prune.script], capture_output=True, text=True, timeout=60, + env={**os.environ, "PATH": f"{shim.parent}{os.pathsep}{os.environ['PATH']}"}) + assert done.returncode == 7 and "docker ran" not in done.stdout + assert f"{sm.SPACE_MARK} {tmp_path / 'scratch' / 'image-adopt' / 'hub'} has" in done.stdout + assert "the cut (1000000000.0 GiB) and the shards it reads need" in done.stdout + + # -- yeto image adopt ------------------------------------------------------------------- @@ -392,13 +512,14 @@ def test_the_dry_run_prints_every_step_and_the_smoke_commands_and_writes_nothing out = capsys.readouterr().out for want in ("1. manifest:", "2. probe on b300-0: docker run --rm", "3. fit:", "4. pull:", "smoke (trainer) on node b300-0", "1. prune [node]", "2. train [launcher]", "3. resume [launcher]", - "--rl-stop-after-rounds 1", f"then: a verified-smoke record in {tmp_path / 'home'}"): + "--rl-stop-after-rounds 1", "finally: stop [launcher]", "finally: artifacts [node]: rm -rf", + f"then: a verified-smoke record in {tmp_path / 'home'}"): assert want in out assert not (tmp_path / "home" / ".yeto").exists() # no catalog, no smoke inventory spec = tmp_path / "spec.json" spec.write_text(json.dumps(FAKE_SPEC)) args = _cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, - "--dry-run") + "--release", RELEASE, "--dry-run") assert ia.main(args) == 0 out = capsys.readouterr().out assert "1. upload [node]" in out and "-m yeto.node.smoke --spec" in out @@ -421,7 +542,7 @@ def test_a_failed_step_exits_1_and_says_the_catalog_is_unchanged(tmp_path, capsy monkeypatch.setattr(ia, "registry_login", lambda ref: None) monkeypatch.setattr(ia.image_manifest, "_OPENER", SimpleNamespace(open=registry({})[0])) args = _cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", _inventory(tmp_path), - "--sampler-spec", spec) + "--sampler-spec", spec, "--release", RELEASE) assert ia.main(args, ops=FakeNodes([node(0)])) == 1 err = capsys.readouterr().err assert "step manifest failed: the registry has no manifest" in err and "is unchanged" in err @@ -435,12 +556,11 @@ def test_the_documented_commands_run_in_a_dry_run(tmp_path, capsys): assert len(commands) == 2 inv = _inventory(tmp_path) spec = tmp_path / "sampler-spec.json" - spec.write_text(json.dumps(FAKE_SPEC)) + spec.write_text(json.dumps({**FAKE_SPEC, "engine": {**FAKE_SPEC["engine"], "server": {"base_dir": "/models/b"}}})) for command in commands: argv = shlex.split(command)[1:] - argv = [str(inv) if a == "cluster.yaml" else str(spec) if a == "sampler-spec.json" else a for a in argv] - if "trainer" in argv: - argv += ["--model-config", str(REGISTRY_CONFIGS / "qwen3_30b_a3b.json")] + argv = [str(inv) if a == "cluster.yaml" else str(spec) if a == "sampler-spec.json" else + str(REGISTRY_CONFIGS / "qwen3_30b_a3b.json") if a == "config.json" else a for a in argv] args = build_parser().parse_args(argv) assert args.dry_run and ia.main(args) == 0, capsys.readouterr().err @@ -478,5 +598,169 @@ def test_the_node_smoke_entry_exits_1_on_a_failed_step(tmp_path, monkeypatch, ca def test_the_sampler_smoke_reloads_the_release_given(): plan = sm.sampler_plan(node(0), spec=FAKE_SPEC, run_id="adopt-t", release="/models/r1", code=("t000", b"tar")) - assert shlex.split(plan.steps[1].script)[-1].endswith( + assert shlex.split(plan.steps[1].render({sm.REF: PINNED, sm.PYTHON: PY}).script)[-1].endswith( "-m yeto.node.smoke --spec /work/image-adopt/adopt-t/spec.json --release /models/r1") + + +# -- review fixes: a launch the real parser takes, no injection, the secret, busy, engine -------------- + + +@pytest.mark.parametrize("step", ["train", "resume"]) +def test_the_trainer_smoke_launch_passes_the_real_launch_checks_in_a_dry_run(tmp_path, capsys, monkeypatch, step): + """The rendered ``yeto launch`` of the smoke through the real parser and the + launch's checks (``--dry-run``: no order, no node): a flag the launch comes to + need fails here first.""" + from yeto import cli + + monkeypatch.setattr(cli, "DEFAULT_INNER_LR", cli._DefaultLR(3e-4)) # the production default (conftest unmarks it) + + plan = _trainer_plan(tmp_path) + for path, text in plan.files.items(): + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(text) + rendered = next(s for s in plan.steps if s.name == step).render({sm.REF: PINNED, sm.PYTHON: PY, + sm.REVISION: REV}, {}) + argv = list(rendered.argv) + assert argv[1:3] == ["-m", "yeto.cli"] + try: + rc = cli.main([*argv[3:], "--dry-run"]) + except SystemExit as exit_: + rc = exit_.code + out = capsys.readouterr() + assert rc == 0, out.err[-2000:] + + +@pytest.mark.parametrize("ref", ["reg.example/a/b:t;touch /tmp/x", "reg.example/a/b:$(id)", "reg.example/a/b c:t", + "reg.example/a/b:t`id`"]) +def test_a_reference_outside_the_docker_grammar_is_refused_before_the_registry(ref): + seen = [] + with pytest.raises(ia.AdoptError, match="is not a docker reference"): + ia.pin(ref, urlopen=lambda req, timeout=None: seen.append(req)) + assert seen == [] + + +def test_rendered_values_are_one_shell_word_each(): + step = sm.SmokeStep("x", "node", node_argv=("docker", "run", sm.REF, "-c", f"{sm.PYTHON_SH} -V")) + bad_ref, bad_py = "a;touch /tmp/pwn", "/usr/bin/python3; touch /tmp/pwn" + argv = shlex.split(step.render({sm.REF: bad_ref, sm.PYTHON: bad_py}, {}).script) + assert argv[:3] == ["docker", "run", bad_ref] + assert shlex.split(argv[4]) == [bad_py, "-V"] # the interpreter is one word inside the inner shell too + plan = sm.sampler_plan(node(0), spec=FAKE_SPEC, run_id="adopt-t", release=RELEASE, code=("t000", b"tar")) + engine = shlex.split(plan.steps[1].render({sm.REF: bad_ref, sm.PYTHON: bad_py}, {}).script) + assert bad_ref in engine and shlex.split(engine[-1].split("; ", 1)[1])[:2] == ["exec", bad_py] + + +@pytest.mark.parametrize("python", ["/usr/bin/python3; touch /tmp/pwn", "python3", "/opt/py $(id)/bin/python"]) +def test_an_image_interpreter_that_is_not_a_plain_path_is_refused(tmp_path, python): + nodes = [node(0)] + ops = TrainerNodes(nodes, Launches(tmp_path / "store")) + result = sm.run_plan(_trainer_plan(tmp_path), ops=ops, ref=PINNED, python=python, run=ops.launch, + log=lambda m: None, objects_for=lambda uri: None, environ={}) + assert not result.ok and "is not a plain absolute path" in result.detail + assert ops.scripts == [] and ops.launch.calls == [] # nothing ran + + +def test_the_hf_token_goes_to_the_node_from_the_launcher_and_is_never_printed(tmp_path): + plan = _trainer_plan(tmp_path) + prune = plan.steps[0] + rendered = prune.render({sm.REF: PINNED, sm.PYTHON: PY}, {"HF_TOKEN": "tok-123", "OTHER": "x"}) + assert rendered.script.startswith("export HF_TOKEN=tok-123\n") and "OTHER" not in rendered.script + assert "-e HF_TOKEN -e HF_ENDPOINT" in rendered.script # docker reads the value from the exported variable + assert "tok-123" not in rendered.text() and "tok-123" not in "\n".join(plan.lines()) + assert not prune.render({sm.REF: PINNED, sm.PYTHON: PY}, {}).script.startswith("export") + + +class TurnsBusy(TrainerNodes): + """Idle for the probe, busy by the smoke.""" + + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + self.checks = 0 + + def run(self, node, script, *, timeout=300.0): + if ia.BUSY_MARK in script: + self.checks += 1 + self.busy = f"{ia.BUSY_MARK} tool cuda\n" + ( + f"{ia.BUSY_MARK} apps 77, python, 1000 MiB\n" if self.checks > 1 else "") + return super().run(node, script, timeout=timeout) + + +def test_a_node_that_turned_busy_before_the_smoke_is_refused(tmp_path): + nodes = [node(0)] + launches = Launches(tmp_path / "store") + with pytest.raises(ia.AdoptError, match="step smoke failed: node b300-0 is in use: process 77 python"): + _adopt(nodes, tmp_path, _trainer_plan(tmp_path), TurnsBusy(nodes, launches), "trainer").run() + assert launches.calls == [] and not (tmp_path / "site-images.yaml").exists() + + +def test_the_sampler_record_takes_the_spec_engine_and_a_contradicting_engine_is_refused(tmp_path): + from tests.test_image_adopt import passing_smoke, request + + facts = ia.parse_probe(probe_out(packages={"sglang": "0.5.0", "torch": "2.9.1"})) + req = request([node(0)], tmp_path, role="sampler", spec_engine="sglang") + assert ia.default_engine(req, facts) == "sglang" + problems, _, _ = ia.fit_problems(dataclasses_replace(req, engine="vllm"), PINNED, facts, "vllm") + assert any("--engine vllm but the sampler spec runs sglang" in p for p in problems) + nodes = [node(0)] + ops = FakeNodes(nodes, probe=probe_out(packages={"vllm": "0.19", "sglang": "0.5.0"})) + opener, _ = registry({"k99": 200}) + ia.Adopter(req, ops=ops, smoke=passing_smoke(), urlopen=opener, login=None, log=lambda m: None, + clock=lambda: FakeCluster.NOW).run() + (rec,) = si.load(tmp_path / "site-images.yaml") + assert rec.engine == "sglang" # the spec's, although the image also has vllm + + +def dataclasses_replace(obj, **kw): + import dataclasses + + return dataclasses.replace(obj, **kw) + + +def test_the_cli_passes_the_spec_engine_the_arch_busy_and_keep_flags(tmp_path, monkeypatch): + seen = {} + + class Captured: + def __init__(self, request, **kw): + seen["request"] = request + seen["smoke"] = kw["smoke"] + self.report = ia.AdoptReport(request) + + def run(self): + raise ia.AdoptError("manifest", "stopped by the test") + + monkeypatch.setattr(ia, "Adopter", Captured) + real_plan = sm.trainer_plan + + def recording_plan(*a, **kw): + seen["keep"] = kw["keep"] + return real_plan(*a, **kw) + + monkeypatch.setattr(sm, "trainer_plan", recording_plan) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps({**FAKE_SPEC, "engine": {**FAKE_SPEC["engine"], "adapter": "sglang-server"}})) + args = _cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", _inventory(tmp_path), + "--sampler-spec", spec, "--release", RELEASE, "--strict-arch", "--allow-busy", + "--keep-smoke-artifacts") + assert ia.main(args) == 1 + req = seen["request"] + assert (req.spec_engine, req.strict_arch, req.allow_busy) == ("sglang", True, True) + args = _cli(TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", _inventory(tmp_path), + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s", + "--keep-smoke-artifacts") + assert ia.main(args) == 1 + assert seen["request"].engine == "miles" # the registry's backend, the one the smoke runs + assert seen["keep"] is True + + +def test_a_tuning_override_and_a_dropped_mtp_are_in_the_notes(tmp_path): + plan = _trainer_plan(tmp_path, extra_args=("--tuning=full",)) + argv = list(plan.steps[1].argv) + assert "--tuning=full" in argv and "--tuning" not in argv and plan.data["tuning"] == "full" + assert any("tuning full (--smoke-arg;" in n for n in plan.notes) + with pytest.raises(sm.SmokeError, match="--tuning half: the recipe"): + _trainer_plan(tmp_path, extra_args=("--tuning", "half")) + mtp = _trainer_plan(tmp_path, config={**QWEN, "num_nextn_predict_layers": 1}) + assert any("drops the model's 1 MTP layer(s)" in n for n in mtp.notes) + assert not any("MTP" in n for n in plan.notes) + lr = _trainer_plan(tmp_path, extra_args=("--inner-lr=3e-6",)) + assert "--inner-lr=3e-6" in lr.steps[1].argv and "1e-6" not in lr.steps[1].argv diff --git a/tests/test_run_flags.py b/tests/test_run_flags.py index 85c659f5b..37a41cc30 100644 --- a/tests/test_run_flags.py +++ b/tests/test_run_flags.py @@ -263,10 +263,11 @@ def test_forward_tables_name_flags_of_both_layers(): _NON_RL_LITERALS = frozenset({ # yeto image adopt (yeto.launch.image_adopt): its flags, the card tools / docker ps of its idle # check, and its smoke (yeto.launch.image_smoke: the scripts/prune_layers.py --layers of the - # trainer cut; --smoke-arg=--flag=value in its help) + # trainer cut and its --cache-dir; --smoke-arg=--flag=value in its help; the cleanup's yeto down --missing-ok) "--role", "--strict-arch", "--allow-busy", "--showpids", "--csv", "--filter", "--inventory", "--engine", "--catalog", "--min-image-free-gib", "--model-config", "--model-path", "--smoke-store", "--smoke-layers", "--smoke-arg", "--sampler-spec", "--layers", "--flag", + "--keep-smoke-artifacts", "--cache-dir", "--missing-ok", # podman / docker CLI flags of the own-SSH-node sampler pool (yeto.launch.ssh_sampler_pool) "--security-opt", "--signal", "--tail", "--type", # the AgentENV-side regctl setting the task image check names (yeto.launch.agentic_setup) diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index 41df70938..380e67968 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -32,6 +32,7 @@ from __future__ import annotations +import dataclasses import datetime import json import re @@ -105,6 +106,7 @@ class AdoptRequest: strict_arch: bool = False allow_busy: bool = False container_sudo: bool = False + spec_engine: str | None = None # sampler: the engine the pool's sampler spec runs (its engine.adapter) def __post_init__(self) -> None: if self.role not in site_images.ROLES: @@ -183,6 +185,8 @@ def pin(ref: str, *, login: Mapping[str, str] | None = None, urlopen=None) -> st (step ``manifest``) when the registry has no such manifest or cannot be read. With ``YETO_IMAGE_MANIFEST_CHECK=off`` a digest is taken as it is and a tag is refused.""" bare = ref.strip().removeprefix("docker:") + if not site_images.valid_reference(bare, digest=False): + raise AdoptError("manifest", f"{bare!r} is not a docker reference ([REGISTRY[:PORT]/]PATH[:TAG][@sha256:<64 hex>])") if not image_manifest.enabled(): if not re.search(r"@sha256:[0-9a-f]{64}$", bare): raise AdoptError("manifest", f"{image_manifest.CHECK_ENV}=off: a tag cannot be pinned; give the " @@ -491,6 +495,9 @@ def fit_problems(request: AdoptRequest, ref: str, facts: ImageFacts, problems: list[str] = [] warnings: list[str] = [] notes: list[str] = [] + if request.spec_engine and request.engine and request.spec_engine.lower() != request.engine.lower(): + problems.append(f"--engine {request.engine} but the sampler spec runs {request.spec_engine} (its " + "engine.adapter): the record would name an engine the smoke did not run") need = ENGINE_PACKAGES.get((request.role, engine), ()) if need and not any(p in facts.packages for p in need): problems.append(f"the image has no {request.role} engine {engine} (none of {list(need)} is installed; " @@ -528,10 +535,14 @@ def fit_problems(request: AdoptRequest, ref: str, facts: ImageFacts, def default_engine(request: AdoptRequest, facts: ImageFacts | None) -> str: - """The engine of the record: the one asked for, else the default training backend - (trainer) or the engine package the probe found (sampler: vllm-ascend, vllm, sglang).""" + """The engine of the record: the one asked for (``--engine``; for a trainer smoke + the backend the model registry recommends, which ``yeto image adopt`` passes), else + the sampler spec's (``engine.adapter``), else the default training backend (trainer) + or the engine package the probe found (sampler: vllm-ascend, vllm, sglang).""" if request.engine: return request.engine.lower() + if request.spec_engine: + return request.spec_engine.lower() if request.role == "trainer": from ..rl.engine import backends # noqa: PLC0415 @@ -608,6 +619,11 @@ def run(self) -> AdoptReport: engine = default_engine(req, facts) if self.smoke is None: raise self._held(AdoptError("smoke", f"no {req.role} smoke is wired for this adoption")) + try: # the pull may have taken long: the node is checked again right before the smoke + self.check_idle(req.probe_node, "smoke") + except AdoptError as error: + self.report.steps.append(StepResult("smoke", False, error.reason, 0.0)) + raise self._held(error) from None self.log("[image adopt] smoke ...") result = self.smoke(self, pinned, facts, engine) self.report.steps.append(result) @@ -796,14 +812,23 @@ def add_parser(sub: Any) -> Any: a.add_argument("--role", required=True, choices=site_images.ROLES) a.add_argument("--inventory", required=True, help="the SSH node inventory (YAML / JSON)") a.add_argument("--engine", default=None, - help="trainer: the --rl-backend (default: the model registry's); sampler: vllm | sglang | " - "vllm-ascend (default: the engine found in the image)") + help="trainer: the --rl-backend (default: the model registry's recommendation; the smoke runs " + "miles); sampler: vllm | sglang | vllm-ascend (default: the sampler spec's engine.adapter, " + "else the engine found in the image); a spec that runs another engine is refused") a.add_argument("--node", default=None, help="the node that probes and smokes (default: the first of the role)") a.add_argument("--catalog", default=None, help="the site image catalog (default: the inventory's site_images:)") a.add_argument("--min-image-free-gib", type=float, default=120.0, help="free GiB the image root (docker data root / containerd store) of every node needs") a.add_argument("--attention-backend", default="auto", help="the trainer's attention backend, for the trainer image floor (default auto)") + a.add_argument("--strict-arch", action="store_true", + help="the image must carry a cubin of exactly the node's card architecture (no CUDA " + "minor-version or PTX compatibility)") + a.add_argument("--allow-busy", action="store_true", + help="probe and smoke a node whose cards run processes or that runs yeto containers (a warning)") + a.add_argument("--keep-smoke-artifacts", action="store_true", + help="keep the smoke's cut model, checkpoint and files (printed with their size) instead of " + "deleting them") a.add_argument("--dry-run", action="store_true", help="print every step and command; reach no registry or node") t = a.add_argument_group("trainer smoke") t.add_argument("--model-config", default=None, @@ -849,12 +874,20 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: plan = image_smoke.trainer_plan( request.probe_node, model=request.model, config=_model_config(args), engine=request.engine, store=args.smoke_store, run_id=run_id, workdir=workdir, model_revision=args.model_revision, - model_path=args.model_path, layers=args.smoke_layers, extra_args=tuple(args.smoke_arg)) + model_path=args.model_path, layers=args.smoke_layers, extra_args=tuple(args.smoke_arg), + keep=args.keep_smoke_artifacts) return plan + spec = _sampler_spec(args) + return image_smoke.sampler_plan(request.probe_node, spec=spec, run_id=run_id, release=args.release, + keep=args.keep_smoke_artifacts) + + +def _sampler_spec(args: Any) -> dict[str, Any]: + from . import image_smoke # noqa: PLC0415 + if not args.sampler_spec: raise image_smoke.SmokeError("the sampler smoke runs the pool's sampler spec: pass --sampler-spec") - spec = json.loads(Path(args.sampler_spec).expanduser().read_text()) - return image_smoke.sampler_plan(request.probe_node, spec=spec, run_id=run_id, release=args.release) + return json.loads(Path(args.sampler_spec).expanduser().read_text()) def main(args: Any, *, ops: Any = None, out: Any = None) -> int: @@ -866,13 +899,18 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: try: nodes = role_nodes(load_inventory(args.inventory), args.role) catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) + spec_engine = engine_images.spec_needs(_sampler_spec(args))["engine_pref"] if args.role == "sampler" \ + and args.sampler_spec else None request = AdoptRequest(ref=args.ref, model=args.model, role=args.role, nodes=tuple(nodes), engine=args.engine, node=args.node, catalog=catalog, - min_image_free_gib=args.min_image_free_gib, attention_backend=args.attention_backend) + min_image_free_gib=args.min_image_free_gib, attention_backend=args.attention_backend, + strict_arch=args.strict_arch, allow_busy=args.allow_busy, spec_engine=spec_engine) stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S") slug = re.sub(r"[^a-z0-9]+", "-", args.model.rsplit("/", 1)[-1].lower()).strip("-")[:24] or "model" run_id = f"adopt-{slug}-{args.role}-{stamp}" plan = _plan(args, request, run_id) + if args.role == "trainer" and not request.engine: # the record names the backend the smoke ran + request = dataclasses.replace(request, engine=str(plan.data["engine"])) except (InventoryError, site_images.SiteImagesError, image_smoke.SmokeError, FileNotFoundError, OSError, ValueError) as error: print(f"yeto image adopt: {error}", file=sys.stderr) diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py index d6035e71e..ba295056c 100644 --- a/yeto/launch/image_smoke.py +++ b/yeto/launch/image_smoke.py @@ -5,29 +5,43 @@ 1. ``prune`` (on the node, in the image): ``scripts/prune_layers.py`` keeps the first ``N`` decoder layers (all their experts, the embeddings and the head; the MFU 16L - cut of 2026-11-18) and lays the result out as a Hugging Face hub snapshot under the - node's ``scratch`` (revision = the sha1 of the cut ``config.json``). ``N`` is the + cut of 2026-11-18; MTP layers are dropped) and lays the result out as a Hugging + Face hub snapshot under the node's ``scratch`` (revision = the sha1 of the cut + ``config.json``); the shards it downloads go to a cache next to it, removed after + the cut, and the scratch must have room for both (:func:`cut_gib`). ``N`` is the largest of at most :data:`MAX_LAYERS` whose trainer state fits the node's cards in the model registry's sizing (:func:`yeto.rl.model_registry.recommend.plan_trainer`, - with the backend and recipe ``yeto adapt`` recommends for the full model); -2. ``train`` (on the launcher): ``yeto launch`` of an ``ssh:`` island of that one node - with the image, the registry's flags for the cut model (recipe, tuning, TP / PP / - EP) and a train-only replay of synthetic rollouts (Miles' debug-rollout replay, + with the backend, recipe and tuning ``yeto adapt`` recommends for the full model; + ``--smoke-arg=--tuning=...`` overrides the tuning); +2. ``train`` (on the launcher): ``yeto launch --controller local`` of one ``ssh:`` + island of that node, no syncer (``--rl-single-island-no-sync``), with the image, + the registry's flags for the cut model (recipe, tuning, TP / PP / EP), a small + local prompt file and the built-in numeric reward (the launch's own checks need + them) and a train-only replay of synthetic rollouts (Miles' debug-rollout replay, ``YETO_TEST_SYNTH_ROLLOUT``: no sampler); ``--rl-stop-after-rounds 1`` ends the - round with a cut (the checkpoint) in ``--smoke-store``; + round with a cut (the checkpoint) in ``--smoke-store``. The step passes when the + trainer's ``rl_round_cut`` event names a cut whose manifest is in the store; 3. ``resume`` (on the launcher): the same launch with ``--rl-stop-after-rounds 2``: it - resumes from that cut (the checkpoint read) and trains the second round. + passes when its ``rl_resume`` / ``rl_round_cut_restored`` event names that cut. + +Whatever the outcome (a failure, a timeout), the smoke's containers are removed and +its run stopped, and its artifacts (the cut on the node, the checkpoint in the store, +the launcher's files) deleted unless ``--keep-smoke-artifacts``. **sampler** (``--role sampler``): the pool's sampler spec on one node, started as the node runtime starts a sampler (:func:`yeto.node.launch.container_argv`) running :mod:`yeto.node.smoke`: start the engine, one generation, one reload (the reload of a -trainer release), one more generation. +trainer release: the release ``--release`` names, else the engine's base weights; +the reload exercises the engine's hot-reload endpoint, not the format of a trainer +release), one more generation. :func:`trainer_plan` / :func:`sampler_plan` build the steps (what ``--dry-run`` prints); :func:`run_plan` runs them (an ``SshOps`` for the node steps, ``subprocess`` for the launcher steps; tests pass fakes). The pinned image, the image's interpreter and the cut's revision are known only while adopting: the steps name them -:data:`REF`, :data:`PYTHON` and :data:`REVISION` until then. +:data:`REF`, :data:`PYTHON` and :data:`REVISION` until then, and a node script is +built only once they are known (:meth:`SmokeStep.render`: the values are argv +elements of ``shlex.join``, or ``shlex.quote``-d where they sit inside a shell string). """ from __future__ import annotations @@ -36,6 +50,7 @@ import copy import dataclasses import json +import os import re import shlex import subprocess @@ -50,10 +65,23 @@ from .node_inventory import Node, card_arch_of, profile_of REF, PYTHON, REVISION = "@REF@", "@PYTHON@", "@REVISION@" +PYTHON_SH = "@PYTHON_SH@" # the interpreter inside a shell string (rendered shlex.quote-d) +PYTHON_PATH = re.compile(r"/[\w./+-]+") # an image interpreter the smoke runs +SECRET_ENV = ("HF_TOKEN",) # passed to the node's prune from the launcher's environment, never printed +PASS_ENV = ("HF_TOKEN", "HF_ENDPOINT") +REWARD = "yeto.rl.numeric_answer_reward:score" # a built-in reward (the replay never scores) +PROMPTS = [{"prompt": "What is 2 + 2? Put the answer in \\boxed{}.", "label": "4"}, + {"prompt": "What is 3 + 5? Put the answer in \\boxed{}.", "label": "8"}] +# launch flags the smoke sets unless --smoke-arg gives them: a rate (one step: it barely matters); no model +# preflight from the launcher (the cut exists only on the node: the prune step made and checked it) +LAUNCH_DEFAULTS = (("--inner-lr", "1e-6"), ("--preflight-model", "off")) +BYTES_PER_PARAM = {"bf16": 2.0, "fp16": 2.0, "fp32": 4.0, "fp8": 1.0, "int8": 1.0, "mxfp4": 0.53, "int4": 0.53, + "nvfp4": 0.56} MAX_LAYERS = 16 # the MFU 16L cut HUB_IN_CONTAINER = "/data/image-adopt-hub" # where the trainer sees the cut (--model-store local://) SMOKE_MODEL_ORG = "yeto-local" REVISION_MARK = "YETO_SMOKE_REVISION" +SPACE_MARK = "YETO_SMOKE_SPACE" TRAINER_BACKENDS = ("miles",) # backends with a train-only replay (Miles' debug-rollout replay) TRAIN_TIMEOUT_S = 3 * 3600.0 PRUNE_TIMEOUT_S = 2 * 3600.0 @@ -80,10 +108,23 @@ class SmokeError(ValueError): """No smoke can be planned for this adoption (the reason says what is missing).""" +def fill(text: str, values: Mapping[str, str]) -> str: + """``text`` with the placeholders of ``values``; :data:`PYTHON_SH` takes the + interpreter ``shlex.quote``-d (it sits inside a shell string).""" + for key, value in values.items(): + text = text.replace(key, value) + if PYTHON in values: + text = text.replace(PYTHON_SH, shlex.quote(values[PYTHON])) + return text + + @dataclass(frozen=True) class SmokeStep: - """One step: ``where`` ``node`` (a bash script run over ssh on the smoke node) or - ``launcher`` (``argv`` run here). ``expect``: a pattern the output must contain.""" + """One step: ``where`` ``node`` (a bash script run over ssh on the smoke node: + ``script``, or ``prefix`` + ``shlex.join(node_argv)`` + ``suffix`` built at + :meth:`render`) or ``launcher`` (``argv`` run here). ``expect``: a pattern the output must contain; ``check``: the run's + check of the output (``round_cut`` / ``resume``, :func:`run_plan`); ``env``: the + launcher variables a node script exports first (their values never printed).""" name: str where: str @@ -92,17 +133,35 @@ class SmokeStep: timeout_s: float = 3600.0 expect: str | None = None show: str = "" # what --dry-run prints (default: the argv, or the script) - - def render(self, values: Mapping[str, str]) -> SmokeStep: - def fill(text: str) -> str: - for key, value in values.items(): - text = text.replace(key, value) - return text - return dataclasses.replace(self, script=fill(self.script), argv=tuple(fill(a) for a in self.argv), - show=fill(self.show)) + node_argv: tuple[str, ...] = () + prefix: str = "" + suffix: str = "" + check: str | None = None + env: tuple[str, ...] = () + + def render(self, values: Mapping[str, str], environ: Mapping[str, str] | None = None) -> SmokeStep: + """The step with the placeholders filled. A node script built from ``node_argv`` + joins the filled elements (``shlex.join``: a value is one shell word), and + exports the step's ``env`` variables the launcher has (``environ``).""" + script = fill(self.script, values) + if self.node_argv: + script = fill(self.prefix, values) + shlex.join(fill(a, values) for a in self.node_argv) + \ + fill(self.suffix, values) + environ = os.environ if environ is None else environ + exports = "".join(f"export {name}={shlex.quote(environ[name])}\n" for name in self.env if environ.get(name)) + if exports and script: + script = exports + script + return dataclasses.replace(self, script=script, argv=tuple(fill(a, values) for a in self.argv), + show=fill(self.show, values)) def text(self) -> str: - return self.show or (shlex.join(self.argv) if self.argv else self.script) + if self.show: + return self.show + if self.argv: + return shlex.join(self.argv) + if self.node_argv: + return shlex.join(self.node_argv) + return self.script @dataclass(frozen=True) @@ -113,6 +172,8 @@ class SmokePlan: files: Mapping[str, str] = field(default_factory=dict) # launcher files the steps read notes: tuple[str, ...] = () data: Mapping[str, Any] = field(default_factory=dict) + cleanup: tuple[SmokeStep, ...] = () # run whatever the steps did (run_plan's finally) + artifacts: tuple[tuple[str, str], ...] = () # (where, path): what the cleanup deletes def lines(self) -> list[str]: out = [f"smoke ({self.role}) on node {self.node.name}:"] @@ -121,6 +182,8 @@ def lines(self) -> list[str]: out.append(f" writes {path}") for i, step in enumerate(self.steps, 1): out.append(f" {i}. {step.name} [{step.where}]: {step.text()}") + for step in self.cleanup: + out.append(f" finally: {step.name} [{step.where}]: {step.text()}") return out @@ -149,11 +212,12 @@ def cut_config(config: Mapping[str, Any], layers: int) -> dict[str, Any]: def smoke_layout(config: Mapping[str, Any], node: Node, *, engine: str | None, - layers: int | None = None) -> dict[str, Any]: + layers: int | None = None, tuning: str | None = None) -> dict[str, Any]: """The registry's recipe for the full model (``yeto adapt``'s; ``engine`` None: the backend it recommends) and the layout of the cut that fits ``node``: ``{"engine", - "recommendation", "recipe", "layers", "plan", "flags", "tuning"}``. Raises - :class:`SmokeError` when the registry has no recipe or no cut fits one node.""" + "recommendation", "recipe", "layers", "plan", "flags", "tuning"}`` (``tuning`` None: + the registry's). Raises :class:`SmokeError` when the registry has no recipe or no + cut fits one node.""" from ..rl.model_registry.match import facts_from_config # noqa: PLC0415 from ..rl.model_registry.recommend import plan_trainer, recommend # noqa: PLC0415 from ..rl.model_registry.render import BACKEND, cli_flags # noqa: PLC0415 @@ -172,7 +236,9 @@ def smoke_layout(config: Mapping[str, Any], node: Node, *, engine: str | None, raise SmokeError(f"the model registry has no {engine or 'trainer'} recipe for this model on {node.card} " f"({why})") engine = engine or BACKEND.get(recipe.trainer.split("-", 1)[0], recipe.trainer) - tuning = rec.trainer_parallel.get("tuning") or recipe.tunings[0] + if tuning is not None and tuning not in recipe.tunings: + raise SmokeError(f"--tuning {tuning}: the recipe {recipe.name} has tunings {list(recipe.tunings)}") + tuning = tuning or rec.trainer_parallel.get("tuning") or recipe.tunings[0] candidates = [int(layers)] if layers else list(range(min(MAX_LAYERS, full.layers), 0, -1)) for n in candidates: if n < 1 or n > full.layers: @@ -207,6 +273,27 @@ def inventory_entry(node: Node, **over: Any) -> dict[str, Any]: return {k: v for k, v in out.items() if v is not None} +def cut_gib(config: Mapping[str, Any], layers: int) -> float: + """The cut's weights in GiB, the registry's parameter count of the cut times the + checkpoint's bytes per parameter.""" + from ..rl.model_registry.match import facts_from_config # noqa: PLC0415 + + facts = facts_from_config(cut_config(config, layers)) + per = BYTES_PER_PARAM.get(str(facts.checkpoint_quant).lower(), 2.0) + return round(float(facts.total_params_b) * 1e9 * per / 2**30, 1) + + +def _flag_value(args: Sequence[str], flag: str) -> str | None: + """The value of ``flag`` in ``args`` (``--flag value`` or ``--flag=value``; the last wins).""" + found = None + for i, arg in enumerate(args): + if arg == flag and i + 1 < len(args): + found = args[i + 1] + elif arg.startswith(flag + "="): + found = arg.split("=", 1)[1] + return found + + def _replace_flag(flags: list[str], extra: Sequence[str]) -> list[str]: """``flags`` without the ``--flag value`` pairs ``extra`` gives again (the operator's value wins: a registry placeholder such as ````).""" @@ -223,11 +310,12 @@ def _replace_flag(flags: list[str], extra: Sequence[str]) -> list[str]: def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: str | None, store: str | None, run_id: str, workdir: Path, model_revision: str | None = None, model_path: str | None = None, - layers: int | None = None, extra_args: Sequence[str] = (), - python: str | None = None) -> SmokePlan: + layers: int | None = None, extra_args: Sequence[str] = (), python: str | None = None, + keep: bool = False) -> SmokePlan: """The trainer smoke's steps (module doc). Raises :class:`SmokeError` for what is missing: a backend without a train-only replay, a node without ``scratch``, no - store for the checkpoint, a registry placeholder no ``--smoke-arg`` fills.""" + store for the checkpoint, a registry placeholder no ``--smoke-arg`` fills. + ``keep``: the cleanup leaves the artifacts and prints where they are.""" if node.runtime != "docker": raise SmokeError(f"node {node.name} runs {node.runtime}: the trainer smoke runs the image (runtime docker)") if not node.scratch: @@ -235,7 +323,8 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s "(inventory scratch: )") if not store: raise SmokeError("the trainer smoke writes its checkpoint to a run store: pass --smoke-store s3://BUCKET/PREFIX") - layout = smoke_layout(config, node, engine=engine, layers=layers) + tuning = _flag_value(extra_args, "--tuning") + layout = smoke_layout(config, node, engine=engine, layers=layers, tuning=tuning) engine = layout["engine"] if engine not in TRAINER_BACKENDS: raise SmokeError(f"no trainer smoke for backend {engine} yet (smoke recipes: {list(TRAINER_BACKENDS)}): " @@ -253,26 +342,38 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s # 1. prune: the cut as a hub snapshot on the node (models----/snapshots/) source = model_path or f"hf://{model}" cache = f"models--{SMOKE_MODEL_ORG}--{slug}" + download = f"{HUB_IN_CONTAINER}/.dl-{slug}" + size = cut_gib(config, n) + need_gib = round(size * (1.1 if model_path else 2.2) + 1.0, 1) # the cut, and the shards it reads (hf://) script_b64 = base64.b64encode(PRUNE_SCRIPT.read_bytes()).decode() mounts = ["-v", f"{host_hub}:{HUB_IN_CONTAINER}"] if model_path: mounts += ["-v", f"{model_path}:{model_path}:ro"] + options = "" + if not model_path: # hf://: the revision asked, the shards in a cache removed after the cut + options = (f" --revision {shlex.quote(model_revision)}" if model_revision else "") + f" --cache-dir {download}" inner = (f"set -euo pipefail; tmp={HUB_IN_CONTAINER}/.cut-{slug}; rm -rf \"$tmp\"; " - f"{PYTHON} /tmp/yeto-prune_layers.py {shlex.quote(source)} \"$tmp\" --layers {n}" - + (f" --revision {shlex.quote(model_revision)}" if model_revision and not model_path else "") + f"{PYTHON_SH} /tmp/yeto-prune_layers.py {shlex.quote(source)} \"$tmp\" --layers {n}{options}" + f"; rev=$(sha1sum \"$tmp/config.json\" | cut -c1-40); " f"mkdir -p {HUB_IN_CONTAINER}/{cache}/snapshots {HUB_IN_CONTAINER}/{cache}/refs; " f"rm -rf {HUB_IN_CONTAINER}/{cache}/snapshots/$rev; mv \"$tmp\" {HUB_IN_CONTAINER}/{cache}/snapshots/$rev; " - f"printf %s \"$rev\" > {HUB_IN_CONTAINER}/{cache}/refs/main; echo {REVISION_MARK} $rev") - prune = (f"set -euo pipefail\nmkdir -p {shlex.quote(host_hub)}\n" - f"base64 -d > {shlex.quote(host_hub)}/.prune_layers.py <<'YETO_PRUNE_EOF'\n{script_b64}\nYETO_PRUNE_EOF\n" - + shlex.join(["docker", "run", "--rm", "--network", "host", *mounts, - "-v", f"{host_hub}/.prune_layers.py:/tmp/yeto-prune_layers.py:ro", - "-e", "HF_TOKEN", "-e", "HF_ENDPOINT", "--entrypoint", "bash", REF, "-c", inner]) + "\n") + f"printf %s \"$rev\" > {HUB_IN_CONTAINER}/{cache}/refs/main; rm -rf {download}; echo {REVISION_MARK} $rev") + hub_q = shlex.quote(host_hub) + prefix = (f"set -euo pipefail\nmkdir -p {hub_q}\n" + f"free_kb=$(df -Pk {hub_q} | awk 'NR==2 {{print $4}}')\n" + f"if [ \"$free_kb\" -lt {int(need_gib * 1024 * 1024)} ]; then echo \"{SPACE_MARK} {host_hub} has " + f"$((free_kb / 1048576)) GiB free; the cut ({size} GiB) and the shards it reads need {need_gib} GiB\"; " + "exit 7; fi\n" + f"base64 -d > {hub_q}/.prune_layers.py <<'YETO_PRUNE_EOF'\n{script_b64}\nYETO_PRUNE_EOF\n") + node_argv = ("docker", "run", "--rm", "--network", "host", *mounts, + "-v", f"{host_hub}/.prune_layers.py:/tmp/yeto-prune_layers.py:ro", + *(a for name in PASS_ENV for a in ("-e", name)), "--entrypoint", "bash", REF, "-c", inner) prune_show = (f"docker run --rm {' '.join(mounts)} {REF} {PYTHON} scripts/prune_layers.py {source} " - f"/{cache}/snapshots/ --layers {n}") + f"/{cache}/snapshots/ --layers {n}" + + ("" if model_path else f" --cache-dir {download}") + f" (needs {need_gib} GiB free)") # 2./3. train and resume: yeto launch of a one-node ssh: island inventory = workdir / "inventory.yaml" + prompts = workdir / "prompts.jsonl" entry = inventory_entry(node, roles=["trainer"], image=None, mounts={**dict(node.mounts), host_hub: HUB_IN_CONTAINER}) facts = layout["recommendation"].facts @@ -281,44 +382,81 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s "experts": max(1, int(facts.num_experts or 1)), "vocab": int(facts.vocab)} if synth["experts"] % synth["router_topk"]: synth["router_topk"] = 1 - base = [python or sys.executable, "-m", "yeto.cli", "launch", *flags, "--model-revision", REVISION, + run_store = f"{store.rstrip('/')}/{run_id}" + yeto = [python or sys.executable, "-m", "yeto.cli"] + base = [*yeto, "launch", *flags, "--model-revision", REVISION, "--gpu", f"ssh:1x{node.cards_per_node}x{node.card}", "--rl-node-inventory", str(inventory), "--rl-image", f"docker:{REF}", "--model-store", f"local://{HUB_IN_CONTAINER}", - "--rl-checkpoint-store", f"{store.rstrip('/')}/{run_id}", "--cluster-prefix", run_id, + "--rl-checkpoint-store", run_store, "--cluster-prefix", run_id, + "--controller", "local", "--rl-single-island-no-sync", "--trust-remote-code", + "--data", str(prompts), "--rl-allow-local-data", "--reward-function", REWARD, + *(a for flag, value in LAUNCH_DEFAULTS if _flag_value(extra_args, flag) is None for a in (flag, value)), "--island-env", f"{SYNTH_ENV}={json.dumps(synth, separators=(',', ':'))}", "--island-env", f"{REPLAY_ENV}={REPLAY_PATH}", *extra_args] steps = ( - SmokeStep("prune", "node", script=prune, timeout_s=PRUNE_TIMEOUT_S, expect=REVISION_MARK, show=prune_show), - SmokeStep("train", "launcher", argv=(*base, "--rl-stop-after-rounds", "1"), timeout_s=TRAIN_TIMEOUT_S), + SmokeStep("prune", "node", node_argv=node_argv, prefix=prefix, suffix="\n", timeout_s=PRUNE_TIMEOUT_S, + expect=REVISION_MARK, show=prune_show, env=SECRET_ENV), + SmokeStep("train", "launcher", argv=(*base, "--rl-stop-after-rounds", "1"), timeout_s=TRAIN_TIMEOUT_S, + check="round_cut"), SmokeStep("resume", "launcher", argv=(*base, "--rl-stop-after-rounds", "2"), timeout_s=TRAIN_TIMEOUT_S, - expect=r"rl_resume|resum(?:e|ed|ing) from"), + check="resume"), ) import yaml # noqa: PLC0415 plan = layout["plan"] - notes = (f"{layout['recipe'].name} ({layout['recipe'].rl_model_recipe}, tuning {layout['tuning']}): " - f"the first {n} of {facts.layers} layers on one node, TP{plan['tensor_parallel']} " - f"PP{plan['pipeline_parallel']} EP{plan['expert_parallel']}, {plan['state_gib_per_card']} GiB state per card", + picked = "--smoke-arg" if tuning else "the registry's" + notes = [f"{layout['recipe'].name} ({layout['recipe'].rl_model_recipe}, tuning {layout['tuning']} ({picked}; " + f"--smoke-arg=--tuning=... overrides it)): the first {n} of {facts.layers} layers on one node, " + f"TP{plan['tensor_parallel']} PP{plan['pipeline_parallel']} EP{plan['expert_parallel']}, " + f"{plan['state_gib_per_card']} GiB state per card", "train-only: synthetic rollouts replayed by the trainer (no sampler); the cut of round 1 is the " - "checkpoint, round 2 resumes from it") - return SmokePlan("trainer", node, steps, files={str(inventory): yaml.safe_dump({"nodes": [entry]}, - sort_keys=False)}, - notes=notes, data={"layers": n, "layout": {k: plan[k] for k in ( + "checkpoint, round 2 resumes from it"] + mtp = _mtp_layers(config) + if mtp: + notes.append(f"the cut drops the model's {mtp} MTP layer(s) (num_nextn_predict_layers): the smoke does not " + "train them") + container = f"^yeto-{run_id}-" + remove = (f"docker ps -aq --filter name={shlex.quote(container)} | while read -r c; do " + "docker rm -f \"$c\" >/dev/null 2>&1 || true; done") + cut_dirs = [f"{host_hub}/{cache}", f"{host_hub}/.dl-{slug}", f"{host_hub}/.cut-{slug}"] + artifacts = (*(("node", d) for d in cut_dirs), ("store", run_store), ("launcher", str(workdir))) + cleanup = [SmokeStep("stop", "launcher", argv=(*yeto, "down", run_id, "--missing-ok"), timeout_s=600.0), + SmokeStep("containers", "node", script=remove, timeout_s=300.0)] + if keep: + cleanup.append(SmokeStep("keep", "node", script="du -sh " + " ".join(shlex.quote(d) for d in cut_dirs) + + " 2>/dev/null || true", timeout_s=300.0)) + else: + cleanup.append(SmokeStep("artifacts", "node", script="rm -rf " + " ".join(shlex.quote(d) for d in cut_dirs), + timeout_s=600.0)) + return SmokePlan("trainer", node, steps, + files={str(inventory): yaml.safe_dump({"nodes": [entry]}, sort_keys=False), + str(prompts): "".join(json.dumps(p) + "\n" for p in PROMPTS)}, + notes=tuple(notes), data={"layers": n, "layout": {k: plan[k] for k in ( "tensor_parallel", "pipeline_parallel", "expert_parallel", "data_parallel")}, "recipe": layout["recipe"].rl_model_recipe, "tuning": layout["tuning"], "run": run_id, - "engine": engine}) + "engine": engine, "store": run_store, "workdir": str(workdir), "keep": bool(keep), + "cut_gib": size, "notes": list(notes)}, + cleanup=tuple(cleanup), artifacts=artifacts) + + +def _mtp_layers(config: Mapping[str, Any]) -> int: + text = config.get("text_config") if isinstance(config.get("text_config"), Mapping) else config + return int((text or {}).get("num_nextn_predict_layers") or 0) # --- sampler --------------------------------------------------------------------------- def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: str | None = None, - code: tuple[str, bytes] | None = None) -> SmokePlan: + code: tuple[str, bytes] | None = None, keep: bool = False) -> SmokePlan: """The sampler smoke's steps: put the yeto tree and the spec on the node, then the - node runtime's container start of :mod:`yeto.node.smoke` on the image.""" + node runtime's container start of :mod:`yeto.node.smoke` on the image. The reload + loads ``release``, else the spec's ``engine.server.base_dir``: a spec with neither + is refused here. ``keep``: the cleanup leaves the run's directory on the node.""" from yeto.node import launch as node_launch # noqa: PLC0415 from yeto.node.code import tree_code_tar # noqa: PLC0415 from yeto.node.profile import CONTAINER_WORK, node_dirs # noqa: PLC0415 + from yeto.node.smoke import base_dir # noqa: PLC0415 profile = profile_of(node) if profile.container not in ("docker", "podman"): @@ -326,6 +464,9 @@ def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: s "container runtime (docker / podman)") if not isinstance(spec.get("engine"), Mapping): raise SmokeError("the sampler spec has no engine section") + if not release and not base_dir(spec): + raise SmokeError("the sampler smoke's reload loads a release: pass --release (a container path), or give " + "the spec's engine.server.base_dir") sha, tar = code or tree_code_tar(REPO_ROOT) work = node_dirs(profile)["work"] base = f"{work}/image-adopt/{run_id}" @@ -338,71 +479,207 @@ def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: s f"{base64.b64encode(tar).decode()}\nYETO_TREE_EOF\nmv {shlex.quote(tree_host)}.tmp {shlex.quote(tree_host)}; fi\n" f"cat > {shlex.quote(spec_host)} <<'YETO_SPEC_EOF'\n{json.dumps(dict(spec), indent=1)}\nYETO_SPEC_EOF\n") env = {"PYTHONPATH": tree_in, "PYTHONUNBUFFERED": "1", **profile.family_env()} - argv = node_launch.container_argv(profile, name=f"yeto-adopt-{run_id}", image=REF, env=env, python=PYTHON, + name = container_name(run_id) + argv = node_launch.container_argv(profile, name=name, image=REF, env=env, python=PYTHON_SH, spec_path=spec_in, module="yeto.node.smoke", module_args=["--spec", spec_in, *(["--release", release] if release else [])]) steps = (SmokeStep("upload", "node", script=put, timeout_s=600.0, show=f"put the yeto tree {sha} at {tree_host} and the spec at {spec_host}"), - SmokeStep("engine", "node", script=shlex.join(argv), timeout_s=SAMPLER_TIMEOUT_S)) + SmokeStep("engine", "node", node_argv=tuple(argv), timeout_s=SAMPLER_TIMEOUT_S)) engine = spec["engine"] notes = (f"engine {engine.get('adapter') or engine.get('factory')}: start, generate, reload " - f"({'release ' + release if release else 'the base weights'} as version 1), generate",) - return SmokePlan("sampler", node, steps, notes=notes, data={"run": run_id, "code": sha}) + f"({'release ' + release if release else 'the base weights'} as version 1), generate; the reload " + "exercises the engine's hot-reload endpoint, not the format of a trainer release",) + ce = shlex.quote(profile.container) + cleanup = [SmokeStep("container", "node", script=f"{ce} rm -f {shlex.quote(name)} >/dev/null 2>&1 || true", + timeout_s=300.0)] + cleanup.append(SmokeStep("keep", "node", script=f"du -sh {shlex.quote(base)} 2>/dev/null || true", timeout_s=300.0) + if keep else SmokeStep("artifacts", "node", script=f"rm -rf {shlex.quote(base)}", timeout_s=300.0)) + return SmokePlan("sampler", node, steps, notes=notes, data={"run": run_id, "code": sha, "keep": bool(keep)}, + cleanup=tuple(cleanup), artifacts=(("node", base),)) + + +def container_name(run_id: str) -> str: + """The sampler smoke's container (removed whatever the smoke did).""" + return f"yeto-adopt-{run_id}" # --- run ------------------------------------------------------------------------------ +def events(text: str) -> list[dict[str, Any]]: + """The trainer's event records in a launch's output (``YETO_RL_EVENT`` lines, + :mod:`yeto.rl.event_echo`).""" + from yeto.rl.event_echo import INVALID, parse_line # noqa: PLC0415 + + out = [] + for line in (text or "").splitlines(): + raw = parse_line(line) + if raw is None or raw is INVALID: + continue + try: + out.append(json.loads(raw)) + except ValueError: + continue + return out + + +def _store_keys(objects: Any) -> list[str]: + return list(objects.list("")) + + +def check_round_cut(text: str, objects: Any) -> tuple[str | None, str]: + """``(cut_id, why)`` of the train step: the newest ``rl_round_cut`` event that wrote + a cut, and its manifest in the store (``round-cuts//manifest.json``); + cut_id None: ``why`` says what is missing.""" + cuts = [e for e in events(text) if e.get("event") == "rl_round_cut" and e.get("ok") and e.get("cut_id")] + if not cuts: + return None, "no rl_round_cut event with a cut_id in the launch's output" + cut_id = str(cuts[-1]["cut_id"]) + if objects is None: + return None, "the smoke store has no object API to read the cut's manifest from" + want = f"round-cuts/{cut_id}/manifest.json" + if not any(key == want or key.endswith("/" + want) for key in _store_keys(objects)): + return None, f"the store has no {want} for the cut {cut_id} the trainer reported" + return cut_id, "" + + +def check_resume(text: str, cut_id: str | None) -> str: + """Why the resume step did not resume from ``cut_id`` (empty: it did): an + ``rl_resume`` or ``rl_round_cut_restored`` event naming that cut.""" + found = [e for e in events(text) if e.get("event") in ("rl_resume", "rl_round_cut_restored")] + if not found: + return "no rl_resume / rl_round_cut_restored event in the launch's output" + if not any(str(e.get("cut_id")) == str(cut_id) for e in found): + return f"it resumed from {sorted({str(e.get('cut_id')) for e in found})}, not the cut {cut_id} of the train" + return "" + + def run_plan(plan: SmokePlan, *, ops: Any, ref: str, python: str | None, run: Callable[..., Any] = subprocess.run, clock: Callable[[], float] = time.time, - log: Callable[[str], None] = lambda m: print(m, file=sys.stderr, flush=True)): - """Every step of ``plan`` in order; the smoke's ``StepResult`` (``ok`` False names the - step and the output's tail).""" + log: Callable[[str], None] = lambda m: print(m, file=sys.stderr, flush=True), + objects_for: Callable[[str], Any] | None = None, environ: Mapping[str, str] | None = None): + """Every step of ``plan`` in order, then (whatever happened: a failure, a timeout) + its cleanup; the smoke's ``StepResult`` (``ok`` False names the step and the + output's tail). ``objects_for``: the store's object API of a store URI (default: + the launcher's, :func:`yeto.launch.island_lifecycle.store_objects`).""" from yeto.node.smoke import parse_result # noqa: PLC0415 - values = {REF: ref, PYTHON: python or "python3"} - for path, text in plan.files.items(): - Path(path).parent.mkdir(parents=True, exist_ok=True) - Path(path).write_text(text) t_start = clock() times: dict[str, float] = {} data: dict[str, Any] = {**plan.data, "steps": times} + python = python or "python3" + if not PYTHON_PATH.fullmatch(python): + return StepResult("smoke", False, f"the image's interpreter {python!r} is not a plain absolute path " + "(/[\\w./+-]+): the smoke does not run it", 0.0, data) + if objects_for is None: + from .island_lifecycle import store_objects # noqa: PLC0415 + + objects_for = store_objects + values = {REF: ref, PYTHON: python} + for path, text in plan.files.items(): + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(text) def failed(step: SmokeStep, why: str) -> Any: return StepResult("smoke", False, f"{step.name}: {why}", clock() - t_start, data) - for step in plan.steps: - step = step.render(values) - log(f"[image adopt] smoke {step.name} [{step.where}]") - t0 = clock() - try: - if step.where == "node": - done = ops.run(plan.node, step.script, timeout=step.timeout_s) - else: - done = run(list(step.argv), capture_output=True, text=True, timeout=step.timeout_s, check=False) - except Exception as error: # noqa: BLE001 - a timeout or a dead ssh is the step's failure + def go(step: SmokeStep) -> tuple[Any, str]: + if step.where == "node": + done = ops.run(plan.node, step.script, timeout=step.timeout_s) + else: + done = run(list(step.argv), capture_output=True, text=True, timeout=step.timeout_s, check=False) + return done, (getattr(done, "stdout", "") or "") + "\n" + (getattr(done, "stderr", "") or "") + + try: + for step in plan.steps: + step = step.render(values, environ) + log(f"[image adopt] smoke {step.name} [{step.where}]") + t0 = clock() + try: + done, out = go(step) + except Exception as error: # noqa: BLE001 - a timeout or a dead ssh is the step's failure + times[step.name] = round(clock() - t0, 1) + return failed(step, f"{type(error).__name__}: {error}"[:600]) times[step.name] = round(clock() - t0, 1) - return failed(step, f"{type(error).__name__}: {error}"[:600]) - times[step.name] = round(clock() - t0, 1) - out = (getattr(done, "stdout", "") or "") + "\n" + (getattr(done, "stderr", "") or "") - result = parse_result(out) if plan.role == "sampler" and step.name == "engine" else None - if result is not None and not result.get("ok"): - data["engine_steps"] = result.get("seconds") - return failed(step, f"{result.get('step')} failed: {result.get('error')}") - if done.returncode != 0: - return failed(step, f"rc {done.returncode}: {out.strip()[-600:]}") - if step.expect and not re.search(step.expect, out): - return failed(step, f"the output has no {step.expect!r}: {out.strip()[-400:]}") - if step.name == "engine" and plan.role == "sampler": - if result is None: - return failed(step, f"no smoke result in the output: {out.strip()[-400:]}") - data["engine_steps"] = result.get("seconds") - if result.get("reload_mode"): - data["reload_mode"] = result["reload_mode"] - match = re.search(rf"{REVISION_MARK} ([0-9a-f]{{40}})", out) - if match: - values[REVISION] = match.group(1) - data["revision"] = match.group(1) - what = "one step trained, checkpoint saved and resumed" if plan.role == "trainer" else \ - "engine started, generated, reloaded and generated again" - return StepResult("smoke", True, f"{what} on {plan.node.name}", clock() - t_start, data) + result = parse_result(out) if plan.role == "sampler" and step.name == "engine" else None + if result is not None and not result.get("ok"): + data["engine_steps"] = result.get("seconds") + return failed(step, f"{result.get('step')} failed: {result.get('error')}") + space = re.search(rf"{SPACE_MARK} (.*)", out) + if space: + return failed(step, space.group(1).strip()) + if done.returncode != 0: + return failed(step, f"rc {done.returncode}: {out.strip()[-600:]}") + if step.expect and not re.search(step.expect, out): + return failed(step, f"the output has no {step.expect!r}: {out.strip()[-400:]}") + if step.check == "round_cut": + cut_id, why = check_round_cut(out, objects_for(str(plan.data.get("store")))) + if cut_id is None: + return failed(step, f"{why}: {out.strip()[-300:]}") + data["cut_id"] = cut_id + elif step.check == "resume": + why = check_resume(out, data.get("cut_id")) + if why: + return failed(step, f"{why}: {out.strip()[-300:]}") + if step.name == "engine" and plan.role == "sampler": + if result is None: + return failed(step, f"no smoke result in the output: {out.strip()[-400:]}") + data["engine_steps"] = result.get("seconds") + if result.get("reload_mode"): + data["reload_mode"] = result["reload_mode"] + match = re.search(rf"{REVISION_MARK} ([0-9a-f]{{40}})", out) + if match: + values[REVISION] = match.group(1) + data["revision"] = match.group(1) + what = "one step trained, checkpoint saved and resumed" if plan.role == "trainer" else \ + "engine started, generated, reloaded and generated again" + return StepResult("smoke", True, f"{what} on {plan.node.name}", clock() - t_start, data) + finally: + data["cleanup"] = clean(plan, ops=ops, run=run, log=log, objects_for=objects_for, go=go, values=values) + + +def clean(plan: SmokePlan, *, ops: Any, run: Callable[..., Any], log: Callable[[str], None], + objects_for: Callable[[str], Any], go: Callable[[SmokeStep], tuple[Any, str]], + values: Mapping[str, str]) -> dict[str, str]: + """The plan's cleanup steps, then the launcher side of its artifacts: the smoke + store's objects and the launcher's files (deleted, or with ``keep`` named with + their size). A cleanup that fails is a warning: the smoke's answer stands.""" + import shutil # noqa: PLC0415 + + out: dict[str, str] = {} + for step in plan.cleanup: + step = step.render(values, {}) + try: + done, text = go(step) + out[step.name] = "ok" if done.returncode == 0 else f"rc {done.returncode}" + if step.name == "keep" and text.strip(): + for line in text.strip().splitlines(): + log(f"[image adopt] kept on {plan.node.name}: {line.strip()}") + except Exception as error: # noqa: BLE001 - never hides the smoke's answer + out[step.name] = f"{type(error).__name__}: {error}"[:200] + log(f"[image adopt] WARNING: smoke cleanup {step.name} failed: {out[step.name]}") + keep = bool(plan.data.get("keep")) + for where, path in plan.artifacts: + try: + if where == "store": + objects = objects_for(path) + keys = _store_keys(objects) if objects is not None else [] + if keep: + log(f"[image adopt] kept in the store: {path} ({len(keys)} object(s))") + else: + for key in keys: + objects.delete(key) + out["store"] = f"{len(keys)} object(s) deleted" + elif where == "launcher": + target = Path(path) + if keep: + size = sum(f.stat().st_size for f in target.rglob("*") if f.is_file()) if target.exists() else 0 + log(f"[image adopt] kept on the launcher: {target} ({size / 2**20:.1f} MiB)") + else: + shutil.rmtree(target, ignore_errors=True) + out["launcher"] = "deleted" + except Exception as error: # noqa: BLE001 + out[where] = f"{type(error).__name__}: {error}"[:200] + log(f"[image adopt] WARNING: smoke cleanup of {where} {path} failed: {out[where]}") + return out From e20fe50a85e2ea2ffb126ff76c1e98c3e5d19554 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 19:13:00 +0800 Subject: [PATCH 3/7] image adopt smoke: remote code as the model needs, in-place reload, hub env - --trust-remote-code follows the model: on when config.json has an auto_map (the registry has no trust field; auto_map is its equivalent) or when the registry does not know the model, off otherwise; the evidence notes say why. --smoke-arg=--trust-remote-code / --no-trust-remote-code decide it. Pinned Miles refuses a launch without the flag, so the Miles smoke passes it for every model and refuses --no-trust-remote-code. - The sampler smoke fails when the reload falls back to a restart; the error names the reload_mode. - HF_ENDPOINT is exported to the node's prune like HF_TOKEN (the script over ssh stdin, never argv). - Tests: the real launch dry run with the model preflight on (a Hub that does not know the cut), a real-bash run of the prune script with shell words in the model, revision, HF_TOKEN and HF_ENDPOINT. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 16 ++++-- tests/test_image_smoke.py | 111 ++++++++++++++++++++++++++++++++++++- tests/test_run_flags.py | 5 +- yeto/launch/image_smoke.py | 63 ++++++++++++++++++--- yeto/node/smoke.py | 13 ++++- 5 files changed, 192 insertions(+), 16 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index a6e4ee600..8dfc44a26 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -776,8 +776,14 @@ to adopt the image. The steps, in order: checked), and a second launch resumes from that cut (its `rl_resume` event must name the same cut) and trains another round. `--model-path` takes the checkpoint from a directory on the node instead of the Hub. A gated model - needs `HF_TOKEN` in the environment of `yeto image adopt`: it is passed to - the node's cut, never printed. When the registry's flags for the model need + needs `HF_TOKEN` in the environment of `yeto image adopt`, and a Hub mirror + `HF_ENDPOINT`: both are passed to the node's cut through the script it + reads, never on a command line and never printed. The model needs + `--trust-remote-code` when its `config.json` has an `auto_map`, or when the + model registry does not know it; `--smoke-arg=--trust-remote-code` or + `--smoke-arg=--no-trust-remote-code` decides it instead. The Miles launch + requires the flag for every model (its loaders always allow remote code), + so the Miles smoke always passes it; the evidence notes say both. When the registry's flags for the model need a file (for example `--rl-expert-selection` for Kimi K3.1), pass it with `--smoke-arg=--rl-expert-selection=/path/selection.json`; any other `yeto launch` flag the run needs goes the same way. Only the Miles backend @@ -787,8 +793,10 @@ to adopt the image. The steps, in order: flags and directories), generates once, reloads (the weights of `--release`, else the spec's `engine.server.base_dir`, as policy version 1; one of the two is required) and generates again. The reload checks the engine's hot-reload - endpoint only, not the format of a trainer release. A failing step is named, - for example `smoke failed: engine: reload failed: ...`. + endpoint only, not the format of a trainer release, and it must reload in + place: an engine whose reload falls back to a restart fails the smoke, and + the error names its `reload_mode`. A failing step is named, for example + `smoke failed: engine: reload failed: ...`. Whatever the smoke's outcome, a failure or a timeout, its containers are removed and its run stopped (`yeto down`), and its artifacts are deleted: the diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index 412203e5c..fbb43e621 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -24,6 +24,7 @@ from yeto.cli import build_parser from yeto.launch import image_adopt as ia from yeto.launch import image_smoke as sm +from yeto.launch import model_check from yeto.launch import site_images as si from yeto.node import smoke as node_smoke from yeto.rl.adapters.sampler_engines.fake import FakeEngine @@ -228,8 +229,9 @@ def test_the_trainer_plan_cuts_trains_and_resumes_on_one_node(tmp_path): ("--rl-checkpoint-store", "s3://bucket/smoke/adopt-t"), ("--rl-stop-after-rounds", "1")): assert argv[argv.index(flag) + 1] == value assert argv.count("--model") == 1 - for flag in ("--rl-single-island-no-sync", "--trust-remote-code", "--rl-allow-local-data"): + for flag in ("--rl-single-island-no-sync", "--rl-allow-local-data"): assert flag in argv + assert sm.TRUST in argv and plan.data["trust_remote_code"] is True # qwen3-moe: no auto_map, but Miles needs it assert argv[argv.index("--controller") + 1] == "local" assert argv[argv.index("--reward-function") + 1] == sm.REWARD prompts = Path(argv[argv.index("--data") + 1]) @@ -613,7 +615,15 @@ def test_the_trainer_smoke_launch_passes_the_real_launch_checks_in_a_dry_run(tmp from yeto import cli monkeypatch.setattr(cli, "DEFAULT_INNER_LR", cli._DefaultLR(3e-4)) # the production default (conftest unmarks it) + monkeypatch.delenv(model_check.MODE_ENV, raising=False) # conftest turns the model preflight off for every test + class RepositoryNotFoundError(Exception): + pass + + def no_hub(*_args, **_kw): # the cut exists only on the node: the Hub does not know yeto-local/... + raise RepositoryNotFoundError("404 yeto-local/Qwen3-30B-A3B-16layer") + + monkeypatch.setattr(model_check, "hub_files", no_hub) plan = _trainer_plan(tmp_path) for path, text in plan.files.items(): Path(path).parent.mkdir(parents=True, exist_ok=True) @@ -764,3 +774,102 @@ def test_a_tuning_override_and_a_dropped_mtp_are_in_the_notes(tmp_path): assert not any("MTP" in n for n in plan.notes) lr = _trainer_plan(tmp_path, extra_args=("--inner-lr=3e-6",)) assert "--inner-lr=3e-6" in lr.steps[1].argv and "1e-6" not in lr.steps[1].argv + + +STUB_PYTHON = r"""#!/bin/bash +# the image's interpreter on the prune: records what reached it, writes the cut's config.json +out={record} +{{ printf '%s\0' "$@"; printf 'HF_TOKEN=%s\0' "${{HF_TOKEN-}}"; printf 'HF_ENDPOINT=%s\0' "${{HF_ENDPOINT-}}"; }} > "$out" +mkdir -p "$3" && printf '{{}}' > "$3/config.json" +""" + + +def test_shell_words_in_the_model_revision_and_hub_env_reach_the_node_verbatim_and_run_nothing(tmp_path): + """The rendered prune script in a real bash (``docker`` a shim running the container's + bash here, the image's interpreter a stub recording its argv and environment): a + ``$()``, backticks or quotes in ``--model``, ``--model-revision``, ``HF_TOKEN`` or + ``HF_ENDPOINT`` arrive as the same bytes and run nothing.""" + pwn = tmp_path / "pwn" + + def payload(tag): + return f"x'\"$(touch {pwn}-{tag}-a)`touch {pwn}-{tag}-b`;touch {pwn}-{tag}-c;\"'y" + + model, revision = "org/m" + payload("model"), payload("rev") + env = {"HF_TOKEN": payload("token"), "HF_ENDPOINT": "https://hub.example/" + payload("endpoint")} + shim = tmp_path / "bin" / "docker" + shim.parent.mkdir() + shim.write_text(DOCKER_SHIM) + shim.chmod(0o755) + record = tmp_path / "record" + stub = tmp_path / "stub-python" + stub.write_text(STUB_PYTHON.format(record=shlex.quote(str(record)))) + stub.chmod(0o755) + n = node(0, scratch=str(tmp_path / "scratch")) + plan = _trainer_plan(tmp_path, node=n, model=model, model_revision=revision, layers=4) + prune = plan.steps[0].render({sm.REF: PINNED, sm.PYTHON: str(stub)}, env) + assert env["HF_TOKEN"] not in prune.text() + done = subprocess.run(["bash", "-c", prune.script], capture_output=True, text=True, timeout=60, + env={"PATH": f"{shim.parent}{os.pathsep}{os.environ['PATH']}", "HOME": str(tmp_path)}, + cwd=tmp_path) + assert done.returncode == 0, done.stdout + done.stderr + assert sorted(p.name for p in tmp_path.iterdir() if p.name.startswith("pwn")) == [] + seen = record.read_text().split("\0")[:-1] + argv, got = seen[:-2], dict(item.split("=", 1) for item in seen[-2:]) + assert argv[1] == f"hf://{model}" and argv[argv.index("--revision") + 1] == revision + assert got == env + assert re.search(rf"{sm.REVISION_MARK} [0-9a-f]{{40}}", done.stdout) + + +def test_a_sampler_reload_that_falls_back_to_a_restart_fails_and_names_the_reload_mode(capsys): + from yeto.rl.engine.sampler_engine import RELOAD_IN_PLACE, RELOAD_RESTART + + assert node_smoke.IN_PLACE == RELOAD_IN_PLACE + engine = FakeEngine(in_place=False) + record = node_smoke.run_smoke(engine, release=None) + assert (record["ok"], record["step"], record["reload_mode"]) == (False, "reload", RELOAD_RESTART) + assert f"reload_mode {RELOAD_RESTART}" in record["error"] and engine.stopped + lines = [json.loads(line.split(" ", 1)[1]) for line in capsys.readouterr().out.splitlines()] + assert lines[-1]["step"] == "reload" and not lines[-1]["ok"] and lines[-1]["reload_mode"] == RELOAD_RESTART + assert "generate_after_reload" not in record["seconds"] + + +def _with(config, **over): + return {**json.loads(json.dumps(config)), **over} + + +@pytest.mark.parametrize("config, family, model, why", [ + (QWEN, "qwen3-moe", False, "has no auto_map"), + (_with(QWEN, auto_map={"AutoModelForCausalLM": "modeling_x.X"}), "qwen3-moe", True, "auto_map names remote code"), + (_with(QWEN, text_config={"auto_map": {"AutoConfig": "c.C"}}), "qwen3-moe", True, "auto_map names remote code"), + (QWEN, "generic-moe", True, "does not know this model"), + (QWEN, None, True, "does not know this model"), +]) +def test_the_smoke_trusts_remote_code_as_the_model_needs(config, family, model, why): + on, notes = sm.remote_code(config, family, "verl") # a backend that leaves it to the model + assert on is model and why in notes[0] + on, notes = sm.remote_code(config, family, "miles") # pinned Miles refuses a launch without it + assert on is True and why in notes[0] and ("launch passes it anyway" in notes[0]) is (not model) + + +def test_the_smoke_arg_decides_the_remote_code_and_miles_refuses_it_off(tmp_path): + assert sm.remote_code(QWEN, "qwen3-moe", "verl", [sm.TRUST]) == (True, [ + f"the model: {sm.TRUST} on (--smoke-arg={sm.TRUST})"]) + assert sm.remote_code(_with(QWEN, auto_map={"A": "b.C"}), "generic-moe", "verl", [sm.TRUST, sm.NO_TRUST])[0] is False + with pytest.raises(sm.SmokeError, match="launch refuses to start without --trust-remote-code"): + _trainer_plan(tmp_path, extra_args=[sm.NO_TRUST]) + plan = _trainer_plan(tmp_path, config=_with(QWEN, architectures=["SomethingNewForCausalLM"], + model_type="something_new")) + argv = list(plan.steps[1].argv) + assert argv.count(sm.TRUST) == 1 and sm.NO_TRUST not in argv + assert any("does not know this model" in n for n in plan.data["notes"]) + plan = _trainer_plan(tmp_path, extra_args=[sm.TRUST]) + assert list(plan.steps[1].argv).count(sm.TRUST) == 1 + + +def test_the_remote_code_note_reaches_the_evidence(tmp_path): + nodes = [node(0)] + assert _adopt(nodes, tmp_path, _trainer_plan(tmp_path), TrainerNodes(nodes, Launches(tmp_path / "store")), + "trainer").run().ok + (rec,) = si.load(tmp_path / "site-images.yaml") + assert any(n.startswith(f"the model: {sm.TRUST} off") and "launch passes it anyway" in n + for n in rec.evidence["notes"]) diff --git a/tests/test_run_flags.py b/tests/test_run_flags.py index 37a41cc30..83082f164 100644 --- a/tests/test_run_flags.py +++ b/tests/test_run_flags.py @@ -263,11 +263,12 @@ def test_forward_tables_name_flags_of_both_layers(): _NON_RL_LITERALS = frozenset({ # yeto image adopt (yeto.launch.image_adopt): its flags, the card tools / docker ps of its idle # check, and its smoke (yeto.launch.image_smoke: the scripts/prune_layers.py --layers of the - # trainer cut and its --cache-dir; --smoke-arg=--flag=value in its help; the cleanup's yeto down --missing-ok) + # trainer cut and its --cache-dir; --smoke-arg=--flag=value in its help; the cleanup's yeto down --missing-ok; + # --smoke-arg=--no-trust-remote-code, read by the smoke, never passed to yeto launch) "--role", "--strict-arch", "--allow-busy", "--showpids", "--csv", "--filter", "--inventory", "--engine", "--catalog", "--min-image-free-gib", "--model-config", "--model-path", "--smoke-store", "--smoke-layers", "--smoke-arg", "--sampler-spec", "--layers", "--flag", - "--keep-smoke-artifacts", "--cache-dir", "--missing-ok", + "--keep-smoke-artifacts", "--cache-dir", "--missing-ok", "--no-trust-remote-code", # podman / docker CLI flags of the own-SSH-node sampler pool (yeto.launch.ssh_sampler_pool) "--security-opt", "--signal", "--tail", "--type", # the AgentENV-side regctl setting the task image check names (yeto.launch.agentic_setup) diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py index ba295056c..df3b39aea 100644 --- a/yeto/launch/image_smoke.py +++ b/yeto/launch/image_smoke.py @@ -17,7 +17,8 @@ island of that node, no syncer (``--rl-single-island-no-sync``), with the image, the registry's flags for the cut model (recipe, tuning, TP / PP / EP), a small local prompt file and the built-in numeric reward (the launch's own checks need - them) and a train-only replay of synthetic rollouts (Miles' debug-rollout replay, + them), ``--trust-remote-code`` as :func:`remote_code` decides, and a train-only + replay of synthetic rollouts (Miles' debug-rollout replay, ``YETO_TEST_SYNTH_ROLLOUT``: no sampler); ``--rl-stop-after-rounds 1`` ends the round with a cut (the checkpoint) in ``--smoke-store``. The step passes when the trainer's ``rl_round_cut`` event names a cut whose manifest is in the store; @@ -33,7 +34,8 @@ :mod:`yeto.node.smoke`: start the engine, one generation, one reload (the reload of a trainer release: the release ``--release`` names, else the engine's base weights; the reload exercises the engine's hot-reload endpoint, not the format of a trainer -release), one more generation. +release), one more generation. The reload must be in place: one that falls back to a restart +fails the smoke (its ``reload_mode`` named). :func:`trainer_plan` / :func:`sampler_plan` build the steps (what ``--dry-run`` prints); :func:`run_plan` runs them (an ``SshOps`` for the node steps, ``subprocess`` @@ -67,8 +69,10 @@ REF, PYTHON, REVISION = "@REF@", "@PYTHON@", "@REVISION@" PYTHON_SH = "@PYTHON_SH@" # the interpreter inside a shell string (rendered shlex.quote-d) PYTHON_PATH = re.compile(r"/[\w./+-]+") # an image interpreter the smoke runs -SECRET_ENV = ("HF_TOKEN",) # passed to the node's prune from the launcher's environment, never printed +# passed to the node's prune from the launcher's environment: exported by the script (ssh stdin), never in argv PASS_ENV = ("HF_TOKEN", "HF_ENDPOINT") +TRUST = "--trust-remote-code" +NO_TRUST = "--no-trust-remote-code" # a --smoke-arg the smoke reads (yeto launch has no such flag) REWARD = "yeto.rl.numeric_answer_reward:score" # a built-in reward (the replay never scores) PROMPTS = [{"prompt": "What is 2 + 2? Put the answer in \\boxed{}.", "label": "4"}, {"prompt": "What is 3 + 5? Put the answer in \\boxed{}.", "label": "8"}] @@ -83,6 +87,8 @@ REVISION_MARK = "YETO_SMOKE_REVISION" SPACE_MARK = "YETO_SMOKE_SPACE" TRAINER_BACKENDS = ("miles",) # backends with a train-only replay (Miles' debug-rollout replay) +# backends whose launch refuses to start without --trust-remote-code, whatever the model (yeto.launch.rl_args) +TRUST_REQUIRED = {"miles": "pinned Miles' Megatron and SGLang loaders always allow remote model code"} TRAIN_TIMEOUT_S = 3 * 3600.0 PRUNE_TIMEOUT_S = 2 * 3600.0 SAMPLER_TIMEOUT_S = 2 * 3600.0 @@ -329,6 +335,8 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s if engine not in TRAINER_BACKENDS: raise SmokeError(f"no trainer smoke for backend {engine} yet (smoke recipes: {list(TRAINER_BACKENDS)}): " "its train-only replay is not wired") + trust, trust_notes = remote_code(config, layout["recommendation"].family, engine, extra_args) + extra_args = [a for a in extra_args if a not in (TRUST, NO_TRUST)] n = layout["layers"] slug = f"{_slug(model)}-{n}layer" repo = f"{SMOKE_MODEL_ORG}/{slug}" @@ -388,14 +396,14 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s "--gpu", f"ssh:1x{node.cards_per_node}x{node.card}", "--rl-node-inventory", str(inventory), "--rl-image", f"docker:{REF}", "--model-store", f"local://{HUB_IN_CONTAINER}", "--rl-checkpoint-store", run_store, "--cluster-prefix", run_id, - "--controller", "local", "--rl-single-island-no-sync", "--trust-remote-code", + "--controller", "local", "--rl-single-island-no-sync", *((TRUST,) if trust else ()), "--data", str(prompts), "--rl-allow-local-data", "--reward-function", REWARD, *(a for flag, value in LAUNCH_DEFAULTS if _flag_value(extra_args, flag) is None for a in (flag, value)), "--island-env", f"{SYNTH_ENV}={json.dumps(synth, separators=(',', ':'))}", "--island-env", f"{REPLAY_ENV}={REPLAY_PATH}", *extra_args] steps = ( SmokeStep("prune", "node", node_argv=node_argv, prefix=prefix, suffix="\n", timeout_s=PRUNE_TIMEOUT_S, - expect=REVISION_MARK, show=prune_show, env=SECRET_ENV), + expect=REVISION_MARK, show=prune_show, env=PASS_ENV), SmokeStep("train", "launcher", argv=(*base, "--rl-stop-after-rounds", "1"), timeout_s=TRAIN_TIMEOUT_S, check="round_cut"), SmokeStep("resume", "launcher", argv=(*base, "--rl-stop-after-rounds", "2"), timeout_s=TRAIN_TIMEOUT_S, @@ -410,7 +418,7 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s f"TP{plan['tensor_parallel']} PP{plan['pipeline_parallel']} EP{plan['expert_parallel']}, " f"{plan['state_gib_per_card']} GiB state per card", "train-only: synthetic rollouts replayed by the trainer (no sampler); the cut of round 1 is the " - "checkpoint, round 2 resumes from it"] + "checkpoint, round 2 resumes from it", *trust_notes] mtp = _mtp_layers(config) if mtp: notes.append(f"the cut drops the model's {mtp} MTP layer(s) (num_nextn_predict_layers): the smoke does not " @@ -435,10 +443,51 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s "tensor_parallel", "pipeline_parallel", "expert_parallel", "data_parallel")}, "recipe": layout["recipe"].rl_model_recipe, "tuning": layout["tuning"], "run": run_id, "engine": engine, "store": run_store, "workdir": str(workdir), "keep": bool(keep), - "cut_gib": size, "notes": list(notes)}, + "cut_gib": size, "trust_remote_code": trust, "notes": list(notes)}, cleanup=tuple(cleanup), artifacts=artifacts) +def remote_code(config: Mapping[str, Any], family: str | None, engine: str, + extra_args: Sequence[str] = ()) -> tuple[bool, list[str]]: + """``(on, notes)``: whether the smoke's launch passes ``--trust-remote-code``. + + The model: the registry has no such field; its equivalent is the model's + ``config.json`` ``auto_map`` (the classes transformers loads from the repository, + what :func:`yeto.rl.adapters.miles.remote_code_prewarm.auto_map` reads). A config + (or its ``text_config``) with one needs remote code, a registry family without one + does not, and a model the registry does not know (its generic fallback) is taken + to need it: the smoke cannot tell. ``--smoke-arg=--trust-remote-code`` / + ``--smoke-arg=--no-trust-remote-code`` decide instead (the last one given wins). + + The backend: a backend of :data:`TRUST_REQUIRED` refuses a launch without the + flag whatever the model (pinned Miles' loaders always allow remote code: + :func:`yeto.launch.rl_args` states it), so it is on there, and + ``--no-trust-remote-code`` is a :class:`SmokeError`.""" + from ..rl.model_registry.families import FAMILIES # noqa: PLC0415 + + given = [a for a in extra_args if a in (TRUST, NO_TRUST)] + text = config.get("text_config") if isinstance(config.get("text_config"), Mapping) else {} + if given: + model = given[-1] == TRUST + why = f"the model: {TRUST} {'on' if model else 'off'} (--smoke-arg={given[-1]})" + elif config.get("auto_map") or text.get("auto_map"): + model, why = True, f"the model: {TRUST} on (its config.json auto_map names remote code)" + elif family not in {f.family for f in FAMILIES}: + model, why = True, (f"the model: {TRUST} on by default (the model registry does not know this model, " + f"family {family or '?'}: the smoke cannot tell whether it needs remote code)") + else: + model, why = False, (f"the model: {TRUST} off (the registry's family {family} has no auto_map in " + "config.json)") + if engine in TRUST_REQUIRED: + if given and not model: + raise SmokeError(f"--smoke-arg={NO_TRUST}: the {engine} launch refuses to start without {TRUST} " + f"({TRUST_REQUIRED[engine]})") + if not model: + why += f"; the launch passes it anyway: {TRUST_REQUIRED[engine]}" + return True, [why] + return model, [why] + + def _mtp_layers(config: Mapping[str, Any]) -> int: text = config.get("text_config") if isinstance(config.get("text_config"), Mapping) else config return int((text or {}).get("num_nextn_predict_layers") or 0) diff --git a/yeto/node/smoke.py b/yeto/node/smoke.py index dd2f81fee..de35e7227 100644 --- a/yeto/node/smoke.py +++ b/yeto/node/smoke.py @@ -10,8 +10,9 @@ 1. ``start``: starts the engine on its base weights (policy version 0); 2. ``generate``: one completion; 3. ``reload``: loads the release ``--release`` (default: the engine's base weights) - as policy version 1, the reload the engine does for every trainer release (in - place, or a restart for an engine that cannot); + as policy version 1, the reload the engine does for every trainer release; it + must be in place (``reload_mode`` ``in_place``): a reload that falls back to a + restart fails the step, and the error names the ``reload_mode``; 4. ``generate_after_reload``: one completion at version 1; then stops the engine. Every step prints a ``YETO_SMOKE`` line and the run ends with @@ -32,6 +33,7 @@ STEP_MARK = "YETO_SMOKE" RESULT_MARK = "YETO_SMOKE_RESULT" STEPS = ("start", "generate", "reload", "generate_after_reload") +IN_PLACE = "in_place" # yeto.rl.engine.sampler_engine.RELOAD_IN_PLACE (a test keeps them equal) def _emit(mark: str, record: Mapping[str, Any], out: Any) -> None: @@ -88,6 +90,13 @@ def text_of(completions: Any) -> str: elif value is not None and hasattr(value, "reload_mode"): detail["reload_mode"] = value.reload_mode record[f"{name}_mode"] = value.reload_mode + if name == "reload" and value.reload_mode != IN_PLACE: + record.update(step=name, error=( + f"the engine reloaded with reload_mode {value.reload_mode}, not {IN_PLACE}: every trainer " + "release would restart the sampler (the reload fell back to a restart)")) + _emit(STEP_MARK, {"step": name, "ok": False, "seconds": times[name], **detail, + "error": record["error"]}, out) + return record _emit(STEP_MARK, {"step": name, "ok": True, "seconds": times[name], **detail}, out) served = getattr(engine, "served_version", lambda: None)() if served is not None and int(served) != 1: From caa163d2caea718929eca748983eb2ec385e71c8 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 22:37:43 +0800 Subject: [PATCH 4/7] image adopt: read node profiles, the pool's sudo, a global trust rule - yeto image adopt reads the inventory with load_profiles, so a node's container: podman reaches the probe, the idle check, the pull and the smoke (it was dropped as a profile key, with an "ignored here" warning, and every node ran docker). A sampler node with container: podman is adopted with podman also when its runtime is rootfs, as the ssh sampler pool starts it. The trainer smoke runs an ssh: island, docker only: a podman or rootfs node, or --container-sudo, is refused for --role trainer with why. - --pool-config (its provider.container.sudo) or --container-sudo runs the engine as sudo -n in every step, the sampler smoke's start and cleanup included. - The dry run names each node's engine (and sudo) for the probe and the pull. - --trust-remote-code: every RL launch requires it (rl_args), a global rule now, not a Miles one. - The node smoke fails a reload whose load returns no report of its reload_mode. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 36 +++++++--- tests/test_image_smoke.py | 144 +++++++++++++++++++++++++++++++++++-- tests/test_run_flags.py | 1 + yeto/launch/image_adopt.py | 55 ++++++++++++-- yeto/launch/image_smoke.py | 45 ++++++------ yeto/node/smoke.py | 6 ++ 6 files changed, 244 insertions(+), 43 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 8dfc44a26..120233b7e 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -757,10 +757,23 @@ to adopt the image. The steps, in order: rule and the node's card. 4. **pull**: every node of the role (spares included, `roles: [trainer-spare]`) is checked over SSH, and its image root (the docker data root, or - `/var/lib/containerd` with the containerd image store) must have - `--min-image-free-gib` free (default 120). Only when every node passes does the - pull run, on all docker nodes in parallel. A node that fails is named with the - preflight's finding or docker's error line. + `/var/lib/containerd` with the containerd image store, or podman's storage + graphroot) must have `--min-image-free-gib` free (default 120). A podman node + whose graphroot `podman info` does not print, or that the disk probe does not + find, fails: the image store's disk cannot be confirmed. Only when every node + passes does the pull run, on every node in parallel with its own container + engine. A node that fails is named with the preflight's finding or the + engine's error line. + + Each node's container engine is its inventory `container:` (`docker` or + `podman`; default: `docker` for `runtime: docker`). An ssh sampler pool node + with `container: podman` is adopted with podman also when its `runtime:` is + `rootfs` (the pool starts its containers whatever the trainer runtime says). + A pool whose `container.sudo: true` runs `sudo -n podman` uses podman's + rootful store: pass the pool's config with `--pool-config` (its + `provider.container.sudo` is read), or `--container-sudo`, and the host + checks, the pull, the probe and the smoke all run the engine through + `sudo -n`, so the image lands in the store the pool starts from. 5. **smoke**, on the probe node, after its cards are checked idle again: - **trainer**: the model is cut to its first N layers (all their experts, the embeddings and the head, `scripts/prune_layers.py`; MTP layers are dropped, @@ -781,13 +794,17 @@ to adopt the image. The steps, in order: reads, never on a command line and never printed. The model needs `--trust-remote-code` when its `config.json` has an `auto_map`, or when the model registry does not know it; `--smoke-arg=--trust-remote-code` or - `--smoke-arg=--no-trust-remote-code` decides it instead. The Miles launch - requires the flag for every model (its loaders always allow remote code), - so the Miles smoke always passes it; the evidence notes say both. When the registry's flags for the model need + `--smoke-arg=--no-trust-remote-code` decides it instead. Every RL launch + requires the flag, whatever the model and backend (the pinned trainer's + loaders always allow remote code), so the smoke always passes it and refuses + `--no-trust-remote-code`; the evidence notes say what the model alone needs. + When the registry's flags for the model need a file (for example `--rl-expert-selection` for Kimi K3.1), pass it with `--smoke-arg=--rl-expert-selection=/path/selection.json`; any other `yeto launch` flag the run needs goes the same way. Only the Miles backend - has a trainer smoke so far. + has a trainer smoke so far, and only on `runtime: docker` nodes (the `ssh:` + trainer island starts docker containers as the SSH user: a podman or + `rootfs` node, or `--container-sudo`, is refused for `--role trainer`). - **sampler**: the engine of `--sampler-spec` (the pool's sampler spec) starts in the image the way the node runtime starts a sampler (the node's device flags and directories), generates once, reloads (the weights of `--release`, @@ -795,7 +812,8 @@ to adopt the image. The steps, in order: is required) and generates again. The reload checks the engine's hot-reload endpoint only, not the format of a trainer release, and it must reload in place: an engine whose reload falls back to a restart fails the smoke, and - the error names its `reload_mode`. A failing step is named, for example + the error names its `reload_mode`; so does a load that returns no report of + its reload mode. A failing step is named, for example `smoke failed: engine: reload failed: ...`. Whatever the smoke's outcome, a failure or a timeout, its containers are diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index fbb43e621..5dd65ad1c 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -845,16 +845,17 @@ def _with(config, **over): (QWEN, None, True, "does not know this model"), ]) def test_the_smoke_trusts_remote_code_as_the_model_needs(config, family, model, why): - on, notes = sm.remote_code(config, family, "verl") # a backend that leaves it to the model - assert on is model and why in notes[0] - on, notes = sm.remote_code(config, family, "miles") # pinned Miles refuses a launch without it + on, notes = sm.remote_code(config, family) # every RL launch refuses to start without it: a global rule assert on is True and why in notes[0] and ("launch passes it anyway" in notes[0]) is (not model) + assert notes[0].startswith(f"the model: {sm.TRUST} {'on' if model else 'off'}") -def test_the_smoke_arg_decides_the_remote_code_and_miles_refuses_it_off(tmp_path): - assert sm.remote_code(QWEN, "qwen3-moe", "verl", [sm.TRUST]) == (True, [ +def test_the_smoke_arg_decides_the_remote_code_and_the_launch_refuses_it_off(tmp_path): + assert sm.remote_code(QWEN, "qwen3-moe", [sm.TRUST]) == (True, [ f"the model: {sm.TRUST} on (--smoke-arg={sm.TRUST})"]) - assert sm.remote_code(_with(QWEN, auto_map={"A": "b.C"}), "generic-moe", "verl", [sm.TRUST, sm.NO_TRUST])[0] is False + with pytest.raises(sm.SmokeError, match=r"--smoke-arg=--no-trust-remote-code: the launch refuses"): + sm.remote_code(_with(QWEN, auto_map={"A": "b.C"}), "generic-moe", [sm.TRUST, sm.NO_TRUST]) # the last wins + assert sm.remote_code(QWEN, "qwen3-moe", [sm.NO_TRUST, sm.TRUST])[0] is True with pytest.raises(sm.SmokeError, match="launch refuses to start without --trust-remote-code"): _trainer_plan(tmp_path, extra_args=[sm.NO_TRUST]) plan = _trainer_plan(tmp_path, config=_with(QWEN, architectures=["SomethingNewForCausalLM"], @@ -873,3 +874,134 @@ def test_the_remote_code_note_reaches_the_evidence(tmp_path): (rec,) = si.load(tmp_path / "site-images.yaml") assert any(n.startswith(f"the model: {sm.TRUST} off") and "launch passes it anyway" in n for n in rec.evidence["notes"]) + + +# -- the CLI reads node profiles: an inventory's container (podman), the pool's sudo -------------- + + +def _podman_inventory(tmp_path, *, runtime="docker", n=2): + entries = [{"name": f"b300-{i}", "host": f"ops@b300-{i}", "device_family": "cuda", "cpu_arch": "x86_64", + "card": "B300", "cards_per_node": 8, "hbm_gib": 288, "host_memory_gib": 2048, "runtime": runtime, + "container": "podman", "scratch": "/mnt/nvme/yeto"} for i in range(n)] + path = tmp_path / "cluster.yaml" + path.write_text(yaml.safe_dump({"nodes": entries})) + return path + + +@pytest.mark.parametrize("runtime", ["docker", "rootfs"]) +@pytest.mark.parametrize("sudo", [False, True]) +def test_the_cli_probes_and_pulls_a_podman_inventory_with_podman(tmp_path, monkeypatch, runtime, sudo): + """``container: podman`` in the inventory file reaches every step (``load_profiles``), + also on a ``runtime: rootfs`` node (an ssh sampler pool starts its containers + whatever the trainer runtime says); ``container.sudo`` of the pool config runs the + engine through ``sudo -n``.""" + import warnings + + from tests.test_image_adopt import _graphroot + from yeto.launch import image_manifest as im + from yeto.launch.node_inventory import load_profiles + + monkeypatch.setenv(im.CHECK_ENV, "off") # a digest: pinned without a registry + inv = _podman_inventory(tmp_path, runtime=runtime) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + pool = tmp_path / "pool.yaml" + pool.write_text(yaml.safe_dump({"provider": {"kind": "ssh", "runtime": "container", + "container": {"engine": "podman", "sudo": sudo}}})) + nodes = list(load_profiles(inv)) + + class Raw(FakeNodes): + def run(self, node, script, *, timeout=300.0): + self.raw = [*getattr(self, "raw", []), (node.name, script)] + return super().run(node, script, timeout=timeout) + + ops = Raw(nodes, **{n.name: _graphroot() for n in nodes}) + ops.NOW = __import__("time").time() # main() reads the head clock + ops.probe = probe_out(packages={"torch": "2.9.1+cu130", "vllm": "0.11.0"}) # a sampler image + smoked = [] + monkeypatch.setattr(sm, "run_plan", lambda plan, **kw: smoked.append(plan) or sm.StepResult( + "smoke", True, "engine started, generated, reloaded, generated", 1.0, {"reload_mode": "in_place"})) + args = _cli(PINNED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, + "--release", RELEASE, "--pool-config", pool) + with warnings.catch_warnings(): + warnings.simplefilter("error") # no "ignored here": the profile keys are read + assert ia.main(args, ops=ops) == 0 + ce = "sudo -n podman" if sudo else "podman" + probes = [s for _, s in ops.raw if ia.FACT in s] + assert probes and all(s.startswith(f"{ce} run --rm ") for s in probes) + assert sorted(n for n, s in ops.raw if s.startswith(f"{ce} pull -q ")) == ["b300-0", "b300-1"] + assert not any(s.startswith(("docker pull", "docker run")) for _, s in ops.raw) + assert all(f"{ce} info --format '{{{{.Store.GraphRoot}}}}'" in s for _, s in ops.raw if "@@yeto-section" in s) + engine_step = smoked[0].steps[1].render({sm.REF: PINNED, sm.PYTHON: PY}).script + assert shlex.split(engine_step)[:3] == (["sudo", "-n", "podman"] if sudo else ["podman", "run", "--rm"]) + assert smoked[0].cleanup[0].script.startswith(f"{ce} rm -f ") + (rec,) = si.load(tmp_path / "home" / ".yeto" / "site-images.yaml") + assert rec.evidence["pulled"] == ["b300-0", "b300-1"] + + +def test_the_dry_run_names_each_node_s_engine_and_the_sudo(tmp_path, capsys): + inv = _podman_inventory(tmp_path, n=1) + doc = yaml.safe_load(inv.read_text()) + doc["nodes"].append({**doc["nodes"][0], "name": "b300-1", "host": "ops@b300-1", "container": "docker"}) + inv.write_text(yaml.safe_dump(doc)) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + base = (TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, + "--release", RELEASE, "--dry-run") + assert ia.main(_cli(*base)) == 0 + out = capsys.readouterr().out + assert f"2. probe on b300-0: podman run --rm" in out + assert f"then docker pull {sm.REF} on ['b300-1']; podman pull {sm.REF} on ['b300-0'] in parallel" in out + assert ia.main(_cli(*base, "--container-sudo")) == 0 + out = capsys.readouterr().out + assert "2. probe on b300-0: sudo -n podman run --rm" in out + assert f"sudo -n docker pull {sm.REF} on ['b300-1']; sudo -n podman pull {sm.REF} on ['b300-0']" in out + + +@pytest.mark.parametrize("runtime, container, sudo", [("docker", "podman", False), ("rootfs", "podman", False), + ("docker", "docker", True)]) +def test_a_trainer_smoke_off_the_docker_island_path_is_refused_with_why(tmp_path, capsys, runtime, container, sudo): + inv = _podman_inventory(tmp_path, runtime=runtime, n=1) + doc = yaml.safe_load(inv.read_text()) + doc["nodes"][0]["container"] = container + inv.write_text(yaml.safe_dump(doc)) + args = _cli(TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", inv, + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s", "--dry-run", + *(["--container-sudo"] if sudo else [])) + assert ia.main(args) == 2 + err = capsys.readouterr().err + if sudo: + assert "--container-sudo / a pool config's container.sudo is for sampler pool nodes" in err + else: + assert (f"node b300-0 runs {runtime} (container {container}): the trainer smoke runs the image as an ssh: " + "trainer island, which starts docker containers only") in err + + +def test_the_pool_config_decides_the_sudo_unless_the_flag_says_so(tmp_path): + pool = tmp_path / "pool.yaml" + ns = argparse.Namespace + assert ia.container_sudo(ns(container_sudo=False, pool_config=None)) is False + pool.write_text(yaml.safe_dump({"provider": {"container": {"sudo": True}}})) + assert ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) is True + pool.write_text(yaml.safe_dump({"provider": {"runtime": "venv"}})) + assert ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) is False + assert ia.container_sudo(ns(container_sudo=True, pool_config=str(pool))) is True + pool.write_text(yaml.safe_dump({"provider": {"container": "podman"}})) + with pytest.raises(ValueError, match="provider.container is not a mapping"): + ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) + + +@pytest.mark.parametrize("returned", [None, "loaded", {"reload_mode": "in_place"}]) +def test_a_reload_without_a_load_report_fails(returned, capsys): + class NoReport(FakeEngine): + def load(self, release_dir, version): + super().load(release_dir, version) + return returned + + engine = NoReport() + record = node_smoke.run_smoke(engine, release=None) + assert (record["ok"], record["step"]) == (False, "reload") and engine.stopped + assert f"the engine's load returned {type(returned).__name__}, not a LoadReport with a reload_mode" \ + in record["error"] + last = json.loads(capsys.readouterr().out.splitlines()[-1].split(" ", 1)[1]) + assert (last["step"], last["ok"]) == ("reload", False) diff --git a/tests/test_run_flags.py b/tests/test_run_flags.py index 83082f164..fa0b46e8d 100644 --- a/tests/test_run_flags.py +++ b/tests/test_run_flags.py @@ -269,6 +269,7 @@ def test_forward_tables_name_flags_of_both_layers(): "--inventory", "--engine", "--catalog", "--min-image-free-gib", "--model-config", "--model-path", "--smoke-store", "--smoke-layers", "--smoke-arg", "--sampler-spec", "--layers", "--flag", "--keep-smoke-artifacts", "--cache-dir", "--missing-ok", "--no-trust-remote-code", + "--container-sudo", "--pool-config", # podman / docker CLI flags of the own-SSH-node sampler pool (yeto.launch.ssh_sampler_pool) "--security-opt", "--signal", "--tail", "--type", # the AgentENV-side regctl setting the task image check names (yeto.launch.agentic_setup) diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index 380e67968..fbef2102c 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -824,6 +824,11 @@ def add_parser(sub: Any) -> Any: a.add_argument("--strict-arch", action="store_true", help="the image must carry a cubin of exactly the node's card architecture (no CUDA " "minor-version or PTX compatibility)") + a.add_argument("--container-sudo", action="store_true", + help="run the container engine as sudo -n (an ssh sampler pool's container.sudo: its " + "rootful store); default: --pool-config's container.sudo, else off") + a.add_argument("--pool-config", default=None, + help="the ssh sampler pool's config: its provider.container.sudo decides --container-sudo") a.add_argument("--allow-busy", action="store_true", help="probe and smoke a node whose cards run processes or that runs yeto containers (a warning)") a.add_argument("--keep-smoke-artifacts", action="store_true", @@ -871,6 +876,9 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: workdir = Path(site_images.default_path()).parent / "image-adopt" / run_id if request.role == "trainer": + if request.container_sudo: + raise image_smoke.SmokeError("--container-sudo / a pool config's container.sudo is for sampler pool " + "nodes: the ssh: trainer island runs docker as the ssh user") plan = image_smoke.trainer_plan( request.probe_node, model=request.model, config=_model_config(args), engine=request.engine, store=args.smoke_store, run_id=run_id, workdir=workdir, model_revision=args.model_revision, @@ -879,7 +887,34 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: return plan spec = _sampler_spec(args) return image_smoke.sampler_plan(request.probe_node, spec=spec, run_id=run_id, release=args.release, - keep=args.keep_smoke_artifacts) + keep=args.keep_smoke_artifacts, sudo=request.container_sudo) + + +def container_sudo(args: Any) -> bool: + """``--container-sudo``, else the pool config's ``provider.container.sudo`` (the + inventory has no such key), else off.""" + if getattr(args, "container_sudo", False): + return True + path = getattr(args, "pool_config", None) + if not path: + return False + import yaml # noqa: PLC0415 + + cfg = yaml.safe_load(Path(path).expanduser().read_text()) or {} + container = ((cfg.get("provider") or {}) if isinstance(cfg, Mapping) else {}).get("container") or {} + if not isinstance(container, Mapping): + raise ValueError(f"--pool-config {path}: provider.container is not a mapping") + return bool(container.get("sudo", False)) + + +def _by_engine(nodes: Sequence[Node]) -> dict[str, list[str]]: + """The node names per container engine (docker / podman; a node of none is left out).""" + out: dict[str, list[str]] = {} + for n in nodes: + engine = engine_of(n) + if engine: + out.setdefault(engine, []).append(n.name) + return dict(sorted(out.items())) def _sampler_spec(args: Any) -> dict[str, Any]: @@ -893,18 +928,22 @@ def _sampler_spec(args: Any) -> dict[str, Any]: def main(args: Any, *, ops: Any = None, out: Any = None) -> int: """``yeto image adopt``: 0 recorded (or a dry run), 1 a step failed, 2 a bad request.""" from . import image_smoke # noqa: PLC0415 - from .node_inventory import InventoryError, load_inventory # noqa: PLC0415 + from .node_inventory import InventoryError, load_profiles # noqa: PLC0415 + from .preflight.cluster import engine_command # noqa: PLC0415 out = out or sys.stdout try: - nodes = role_nodes(load_inventory(args.inventory), args.role) + # profiles: an inventory's container (podman) and the other node profile keys count here + nodes = role_nodes(load_profiles(args.inventory), args.role) + sudo = container_sudo(args) catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) spec_engine = engine_images.spec_needs(_sampler_spec(args))["engine_pref"] if args.role == "sampler" \ and args.sampler_spec else None request = AdoptRequest(ref=args.ref, model=args.model, role=args.role, nodes=tuple(nodes), engine=args.engine, node=args.node, catalog=catalog, min_image_free_gib=args.min_image_free_gib, attention_backend=args.attention_backend, - strict_arch=args.strict_arch, allow_busy=args.allow_busy, spec_engine=spec_engine) + strict_arch=args.strict_arch, allow_busy=args.allow_busy, spec_engine=spec_engine, + container_sudo=sudo) stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S") slug = re.sub(r"[^a-z0-9]+", "-", args.model.rsplit("/", 1)[-1].lower()).strip("-")[:24] or "model" run_id = f"adopt-{slug}-{args.role}-{stamp}" @@ -922,10 +961,12 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: f"{role}", f"1. manifest: HEAD of {args.ref} in its registry; a tag is pinned to its digest " f"(below: {image_smoke.REF})", - f"2. probe on {node.name}: {probe_script(image_smoke.REF, node)[:200]} ...", + f"2. probe on {node.name}: {probe_script(image_smoke.REF, node, sudo=sudo)[:200]} ...", f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}", - f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then docker pull " - f"{image_smoke.REF} on {role} in parallel", + f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then " + + "; ".join(f"{engine_command(engine, sudo)} pull {image_smoke.REF} on {names}" + for engine, names in _by_engine(request.nodes).items()) + + " in parallel", "5. " + "\n".join(plan.lines()), f"then: a verified-smoke record in {catalog}"] print("\n".join(lines), file=out) diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py index df3b39aea..16b76c3ff 100644 --- a/yeto/launch/image_smoke.py +++ b/yeto/launch/image_smoke.py @@ -87,8 +87,10 @@ REVISION_MARK = "YETO_SMOKE_REVISION" SPACE_MARK = "YETO_SMOKE_SPACE" TRAINER_BACKENDS = ("miles",) # backends with a train-only replay (Miles' debug-rollout replay) -# backends whose launch refuses to start without --trust-remote-code, whatever the model (yeto.launch.rl_args) -TRUST_REQUIRED = {"miles": "pinned Miles' Megatron and SGLang loaders always allow remote model code"} +# A global rule, not a backend's: yeto.launch.rl_args refuses every RL launch (any --rl-backend) without +# --trust-remote-code, whatever the model, so the smoke's launch always passes it +TRUST_REQUIRED = ("yeto launch refuses every RL launch without it (the pinned trainer's loaders always allow " + "remote model code, so the launch states it)") TRAIN_TIMEOUT_S = 3 * 3600.0 PRUNE_TIMEOUT_S = 2 * 3600.0 SAMPLER_TIMEOUT_S = 2 * 3600.0 @@ -322,8 +324,11 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s missing: a backend without a train-only replay, a node without ``scratch``, no store for the checkpoint, a registry placeholder no ``--smoke-arg`` fills. ``keep``: the cleanup leaves the artifacts and prints where they are.""" - if node.runtime != "docker": - raise SmokeError(f"node {node.name} runs {node.runtime}: the trainer smoke runs the image (runtime docker)") + engine_name = profile_of(node).container + if node.runtime != "docker" or engine_name != "docker": + raise SmokeError(f"node {node.name} runs {node.runtime} (container {engine_name}): the trainer smoke runs " + "the image as an ssh: trainer island, which starts docker containers only (inventory " + "runtime: docker); podman and rootfs nodes take sampler images (--role sampler)") if not node.scratch: raise SmokeError(f"node {node.name} has no scratch: the cut model is written under the node's scratch " "(inventory scratch: )") @@ -335,7 +340,7 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s if engine not in TRAINER_BACKENDS: raise SmokeError(f"no trainer smoke for backend {engine} yet (smoke recipes: {list(TRAINER_BACKENDS)}): " "its train-only replay is not wired") - trust, trust_notes = remote_code(config, layout["recommendation"].family, engine, extra_args) + trust, trust_notes = remote_code(config, layout["recommendation"].family, extra_args) extra_args = [a for a in extra_args if a not in (TRUST, NO_TRUST)] n = layout["layers"] slug = f"{_slug(model)}-{n}layer" @@ -447,7 +452,7 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s cleanup=tuple(cleanup), artifacts=artifacts) -def remote_code(config: Mapping[str, Any], family: str | None, engine: str, +def remote_code(config: Mapping[str, Any], family: str | None, extra_args: Sequence[str] = ()) -> tuple[bool, list[str]]: """``(on, notes)``: whether the smoke's launch passes ``--trust-remote-code``. @@ -459,9 +464,9 @@ def remote_code(config: Mapping[str, Any], family: str | None, engine: str, to need it: the smoke cannot tell. ``--smoke-arg=--trust-remote-code`` / ``--smoke-arg=--no-trust-remote-code`` decide instead (the last one given wins). - The backend: a backend of :data:`TRUST_REQUIRED` refuses a launch without the - flag whatever the model (pinned Miles' loaders always allow remote code: - :func:`yeto.launch.rl_args` states it), so it is on there, and + The launch: every RL launch refuses to start without the flag whatever the model + and backend (:data:`TRUST_REQUIRED`, a global rule of :mod:`yeto.launch.rl_args`), + so the result is always on: the note says what the model alone needs, and ``--no-trust-remote-code`` is a :class:`SmokeError`.""" from ..rl.model_registry.families import FAMILIES # noqa: PLC0415 @@ -478,14 +483,11 @@ def remote_code(config: Mapping[str, Any], family: str | None, engine: str, else: model, why = False, (f"the model: {TRUST} off (the registry's family {family} has no auto_map in " "config.json)") - if engine in TRUST_REQUIRED: - if given and not model: - raise SmokeError(f"--smoke-arg={NO_TRUST}: the {engine} launch refuses to start without {TRUST} " - f"({TRUST_REQUIRED[engine]})") - if not model: - why += f"; the launch passes it anyway: {TRUST_REQUIRED[engine]}" - return True, [why] - return model, [why] + if given and not model: + raise SmokeError(f"--smoke-arg={NO_TRUST}: the launch refuses to start without {TRUST} ({TRUST_REQUIRED})") + if not model: + why += f"; the launch passes it anyway: {TRUST_REQUIRED}" + return True, [why] def _mtp_layers(config: Mapping[str, Any]) -> int: @@ -497,11 +499,12 @@ def _mtp_layers(config: Mapping[str, Any]) -> int: def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: str | None = None, - code: tuple[str, bytes] | None = None, keep: bool = False) -> SmokePlan: + code: tuple[str, bytes] | None = None, keep: bool = False, sudo: bool = False) -> SmokePlan: """The sampler smoke's steps: put the yeto tree and the spec on the node, then the node runtime's container start of :mod:`yeto.node.smoke` on the image. The reload loads ``release``, else the spec's ``engine.server.base_dir``: a spec with neither - is refused here. ``keep``: the cleanup leaves the run's directory on the node.""" + is refused here. ``keep``: the cleanup leaves the run's directory on the node; + ``sudo``: the engine runs as ``sudo -n `` (the pool's ``container.sudo``).""" from yeto.node import launch as node_launch # noqa: PLC0415 from yeto.node.code import tree_code_tar # noqa: PLC0415 from yeto.node.profile import CONTAINER_WORK, node_dirs # noqa: PLC0415 @@ -530,7 +533,7 @@ def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: s env = {"PYTHONPATH": tree_in, "PYTHONUNBUFFERED": "1", **profile.family_env()} name = container_name(run_id) argv = node_launch.container_argv(profile, name=name, image=REF, env=env, python=PYTHON_SH, - spec_path=spec_in, module="yeto.node.smoke", + spec_path=spec_in, sudo=sudo, module="yeto.node.smoke", module_args=["--spec", spec_in, *(["--release", release] if release else [])]) steps = (SmokeStep("upload", "node", script=put, timeout_s=600.0, show=f"put the yeto tree {sha} at {tree_host} and the spec at {spec_host}"), @@ -539,7 +542,7 @@ def sampler_plan(node: Node, *, spec: Mapping[str, Any], run_id: str, release: s notes = (f"engine {engine.get('adapter') or engine.get('factory')}: start, generate, reload " f"({'release ' + release if release else 'the base weights'} as version 1), generate; the reload " "exercises the engine's hot-reload endpoint, not the format of a trainer release",) - ce = shlex.quote(profile.container) + ce = ("sudo -n " if sudo else "") + shlex.quote(profile.container) cleanup = [SmokeStep("container", "node", script=f"{ce} rm -f {shlex.quote(name)} >/dev/null 2>&1 || true", timeout_s=300.0)] cleanup.append(SmokeStep("keep", "node", script=f"du -sh {shlex.quote(base)} 2>/dev/null || true", timeout_s=300.0) diff --git a/yeto/node/smoke.py b/yeto/node/smoke.py index de35e7227..f4b6afa98 100644 --- a/yeto/node/smoke.py +++ b/yeto/node/smoke.py @@ -87,6 +87,12 @@ def text_of(completions: Any) -> str: _emit(STEP_MARK, {"step": name, "ok": False, "seconds": times[name], "error": record["error"]}, out) return record + elif name == "reload" and getattr(value, "reload_mode", None) is None: + record.update(step=name, error=( + f"the engine's load returned {type(value).__name__}, not a LoadReport with a reload_mode: the " + f"smoke cannot tell an in-place reload from a restart")) + _emit(STEP_MARK, {"step": name, "ok": False, "seconds": times[name], "error": record["error"]}, out) + return record elif value is not None and hasattr(value, "reload_mode"): detail["reload_mode"] = value.reload_mode record[f"{name}_mode"] = value.reload_mode From 0e9236376f3ebb834f5ecea3687342970f6f8d6c Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:51:00 +0800 Subject: [PATCH 5/7] image adopt: the pool config decides a sampler's nodes, engine and sudo - --pool-config is read the way the ssh sampler pool reads it (parse_config over the adoption's inventory): its nodes: are the nodes (one not in the inventory is an error), their engine is the pool's container.engine (pool_profile, default podman), its container.sudo the sudo. A runtime: venv pool runs no image and is refused; container.pull: never is named in the dry run (the adoption's pull puts the image there). --container-sudo against a pool whose sudo is off exits 2. A config that is not one (no mapping, provider or container not a mapping, bad YAML) exits 2 with the reason, never a traceback. - The cluster preflight takes by_engine (yeto image adopt): its nodes are pulled and their engine's image root is checked whatever their runtime, so a rootfs node with container: docker is pulled; the preflight's own runtime rule is unchanged. - --role trainer refuses a podman or rootfs node anywhere in the role, not only on the smoke node. - The image-removal hint names each holding node's own engine and sudo. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 27 ++++-- tests/test_image_adopt.py | 54 ++++++++++- tests/test_image_smoke.py | 154 ++++++++++++++++++++++++------- yeto/launch/image_adopt.py | 110 +++++++++++++++++----- yeto/launch/preflight/cluster.py | 19 +++- 5 files changed, 293 insertions(+), 71 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 120233b7e..f961e52a1 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -766,14 +766,22 @@ to adopt the image. The steps, in order: engine's error line. Each node's container engine is its inventory `container:` (`docker` or - `podman`; default: `docker` for `runtime: docker`). An ssh sampler pool node - with `container: podman` is adopted with podman also when its `runtime:` is - `rootfs` (the pool starts its containers whatever the trainer runtime says). - A pool whose `container.sudo: true` runs `sudo -n podman` uses podman's - rootful store: pass the pool's config with `--pool-config` (its - `provider.container.sudo` is read), or `--container-sudo`, and the host + `podman`; default: `docker` for `runtime: docker`), whatever its `runtime:`: + a `runtime: rootfs` node with `container: docker` or `podman` is pulled with + that engine, and one with no container engine is named as not pulled. + + For a sampler image, pass the ssh sampler pool's config with `--pool-config`: + it is read the way the pool reads it, so the nodes are the pool's `nodes:` + (one not in the inventory is an error), their engine is the pool's + `container.engine` (default podman, whatever the inventory says), and its + `container.sudo: true` (`sudo -n podman`, the rootful store) makes the host checks, the pull, the probe and the smoke all run the engine through - `sudo -n`, so the image lands in the store the pool starts from. + `sudo -n`, so the image lands in the store the pool starts from. A + `runtime: venv` pool runs no image and is refused. With `container.pull: + never` the pool starts only images already on its nodes: the adoption's pull + is what puts the image there. Without a pool config, `--container-sudo` asks + for `sudo -n`; against a pool config whose `container.sudo` is off it is an + error. 5. **smoke**, on the probe node, after its cards are checked idle again: - **trainer**: the model is cut to its first N layers (all their experts, the embeddings and the head, `scripts/prune_layers.py`; MTP layers are dropped, @@ -803,8 +811,9 @@ to adopt the image. The steps, in order: `--smoke-arg=--rl-expert-selection=/path/selection.json`; any other `yeto launch` flag the run needs goes the same way. Only the Miles backend has a trainer smoke so far, and only on `runtime: docker` nodes (the `ssh:` - trainer island starts docker containers as the SSH user: a podman or - `rootfs` node, or `--container-sudo`, is refused for `--role trainer`). + trainer island starts docker containers as the SSH user: for `--role + trainer`, any podman or `rootfs` node of the role, spares included, or + `--container-sudo` / `--pool-config`, is refused). - **sampler**: the engine of `--sampler-spec` (the pool's sampler spec) starts in the image the way the node runtime starts a sampler (the node's device flags and directories), generates once, reloads (the weights of `--release`, diff --git a/tests/test_image_adopt.py b/tests/test_image_adopt.py index 5d7f6ae23..265ba76d5 100644 --- a/tests/test_image_adopt.py +++ b/tests/test_image_adopt.py @@ -364,8 +364,8 @@ def test_a_failed_pull_names_the_node(tmp_path, catalog_before): as error: adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() assert error.value.holding == ("b300-0", "b300-1") # the probe node, then the nodes whose pull passed - assert f"the image stays pulled on b300-0, b300-1 (a retry reuses it; `docker rmi {PINNED}` there frees the " \ - "room)" in error.value.reason + assert f"the image stays pulled on b300-0, b300-1 (a retry reuses it; `docker rmi {PINNED}` on b300-0, b300-1 " \ + "frees the room)" in error.value.reason assert ops.kinds().count("docker pull") == 3 # every node was pulled in parallel assert catalog_before.read_text() == "version: 1\nimages: []\n" @@ -688,3 +688,53 @@ def test_the_docker_host_probe_is_byte_for_byte_main_s(): (b300(1, mounts={"/mnt/nvme/x": "/x"}), "958b24e9b3fed68eeb27d8221ae0357653a5009b8e016a3a9ba270211cfce5de")): assert hashlib.sha256(cp.probe_script(cp.host_sections(node)).encode()).hexdigest() == want + + +@pytest.mark.parametrize("sudo", [False, True]) +def test_the_removal_hint_names_each_holding_node_s_engine(tmp_path, sudo): + nodes = [_podman(0), b300(1), _podman(2)] + ops = FakeNodes(nodes, **{"b300-0": _graphroot(), "b300-2": _graphroot()}) + a = adopter(request(nodes, tmp_path, container_sudo=sudo), ops, smoke=passing_smoke()) + a.holding = ["b300-0", "b300-1", "b300-2"] + a.report.pinned = PINNED + reason = a._held(ia.AdoptError("smoke", "failed")).reason + pre = "sudo -n " if sudo else "" + assert (f"(a retry reuses it; `{pre}docker rmi {PINNED}` on b300-1; `{pre}podman rmi {PINNED}` on b300-0, " + "b300-2 frees the room)") in reason + assert ("sudo -n" in reason) is sudo + + +def test_a_rootfs_node_with_docker_is_pulled_and_a_rootfs_node_without_an_engine_is_listed(tmp_path): + """The adoption picks nodes by their profile's container, not by runtime: a + ``runtime: rootfs`` node whose inventory says ``container: docker`` is pulled and its + docker image root checked; one of no container engine is named as not pulled.""" + from yeto.launch.node_inventory import NodeProfile + + docker_rootfs = NodeProfile.from_node(b300(1, runtime="rootfs"), container="docker") + nodes = [b300(0), docker_rootfs, b300(2, runtime="rootfs")] + ops = FakeNodes(nodes) + report = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + pull = next(s for s in report.steps if s.name == "pull") + assert sorted(n for n, s in ops.scripts if s.startswith("docker pull -q ")) == ["b300-0", "b300-1"] + assert "not pulled (no container engine): ['b300-2']" in pull.detail + from yeto.launch.preflight import cluster as cp + + pf = cp.ClusterPreflight([docker_rootfs], image=PINNED, ops=FakeNodes([docker_rootfs]), log=lambda m: None, + clock=lambda: FakeCluster.NOW, by_engine=True) + roots = [c for c in pf.hosts() if c.name == "disk_images"] + assert roots and roots[0].scope == "b300-1" # its docker image root is checked + plain = cp.ClusterPreflight([docker_rootfs], image=PINNED, ops=FakeNodes([docker_rootfs]), log=lambda m: None, + clock=lambda: FakeCluster.NOW) + assert not [c for c in plain.hosts() if c.name == "disk_images"] # the preflight's own rule: runtime docker + + +def test_a_rootfs_probe_node_with_docker_has_its_image_root_checked_before_the_probe(tmp_path): + from yeto.launch.node_inventory import NodeProfile + + probe = NodeProfile.from_node(b300(0, runtime="rootfs"), container="docker") + low = Behavior(host={"disk": (0, "\n".join([disk_line("/", 80, 200, dev="/dev/sda2", mount="/"), + disk_line("/var/lib/containerd", 40, mount="/")]))}) + ops = FakeNodes([probe, b300(1)], **{"b300-0": low}) + with pytest.raises(ia.AdoptError, match=r"step probe failed: node b300-0: disk_images: /var/lib/containerd"): + adopter(request([probe, b300(1)], tmp_path), ops, smoke=passing_smoke()).run() + assert ops.kinds() == ["date", "host"] # no probe ran diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index 5dd65ad1c..d4cf8d80c 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -906,8 +906,7 @@ def test_the_cli_probes_and_pulls_a_podman_inventory_with_podman(tmp_path, monke spec = tmp_path / "spec.json" spec.write_text(json.dumps(FAKE_SPEC)) pool = tmp_path / "pool.yaml" - pool.write_text(yaml.safe_dump({"provider": {"kind": "ssh", "runtime": "container", - "container": {"engine": "podman", "sudo": sudo}}})) + _pool_config(pool, inv, sudo=sudo) nodes = list(load_profiles(inv)) class Raw(FakeNodes): @@ -943,6 +942,9 @@ def test_the_dry_run_names_each_node_s_engine_and_the_sudo(tmp_path, capsys): inv = _podman_inventory(tmp_path, n=1) doc = yaml.safe_load(inv.read_text()) doc["nodes"].append({**doc["nodes"][0], "name": "b300-1", "host": "ops@b300-1", "container": "docker"}) + rootfs = {**doc["nodes"][0], "name": "b300-2", "host": "ops@b300-2", "runtime": "rootfs"} + rootfs.pop("container") + doc["nodes"].append(rootfs) # no container engine: named, not pulled inv.write_text(yaml.safe_dump(doc)) spec = tmp_path / "spec.json" spec.write_text(json.dumps(FAKE_SPEC)) @@ -951,7 +953,8 @@ def test_the_dry_run_names_each_node_s_engine_and_the_sudo(tmp_path, capsys): assert ia.main(_cli(*base)) == 0 out = capsys.readouterr().out assert f"2. probe on b300-0: podman run --rm" in out - assert f"then docker pull {sm.REF} on ['b300-1']; podman pull {sm.REF} on ['b300-0'] in parallel" in out + assert f"then docker pull {sm.REF} on ['b300-1']; podman pull {sm.REF} on ['b300-0'] in parallel; not pulled " \ + "(no container engine): b300-2" in out assert ia.main(_cli(*base, "--container-sudo")) == 0 out = capsys.readouterr().out assert "2. probe on b300-0: sudo -n podman run --rm" in out @@ -973,35 +976,122 @@ def test_a_trainer_smoke_off_the_docker_island_path_is_refused_with_why(tmp_path if sudo: assert "--container-sudo / a pool config's container.sudo is for sampler pool nodes" in err else: - assert (f"node b300-0 runs {runtime} (container {container}): the trainer smoke runs the image as an ssh: " - "trainer island, which starts docker containers only") in err + assert (f"trainer nodes ['b300-0 ({runtime}, container {container})']: an ssh: trainer island starts " + "docker containers only") in err -def test_the_pool_config_decides_the_sudo_unless_the_flag_says_so(tmp_path): - pool = tmp_path / "pool.yaml" +def test_every_trainer_node_is_held_to_the_docker_island_not_only_the_smoke_node(tmp_path, capsys): + inv = _podman_inventory(tmp_path, n=3) + doc = yaml.safe_load(inv.read_text()) + doc["nodes"][0]["container"] = doc["nodes"][2]["container"] = "docker" # the smoke node and a spare: docker + doc["nodes"][2]["roles"] = ["trainer-spare"] + inv.write_text(yaml.safe_dump(doc)) + args = _cli(TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", inv, + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s", "--dry-run") + assert ia.main(args) == 2 + assert "trainer nodes ['b300-1 (docker, container podman)']" in capsys.readouterr().err + doc["nodes"][1]["container"] = "docker" + inv.write_text(yaml.safe_dump(doc)) + assert ia.main(args) == 0 + + +def _pool_config(path, inventory, **container): + """A pool config the ssh sampler pool takes (``parse_config``), over ``inventory``.""" + extra = container.pop("provider", {}) + provider = {"kind": "ssh", "inventory": str(inventory), "workdir": "/srv/yeto/run1", "runtime": "container", + "container": {"engine": "podman", "image": "auto", **container}, **extra} + path.write_text(yaml.safe_dump({"provider": provider})) + return path + + +def test_the_pool_config_decides_the_sudo_and_the_flag_must_agree(tmp_path): + inv = _podman_inventory(tmp_path) + profiles = list(__import__("yeto.launch.node_inventory", fromlist=["x"]).load_profiles(inv)) ns = argparse.Namespace - assert ia.container_sudo(ns(container_sudo=False, pool_config=None)) is False - pool.write_text(yaml.safe_dump({"provider": {"container": {"sudo": True}}})) - assert ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) is True - pool.write_text(yaml.safe_dump({"provider": {"runtime": "venv"}})) - assert ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) is False - assert ia.container_sudo(ns(container_sudo=True, pool_config=str(pool))) is True - pool.write_text(yaml.safe_dump({"provider": {"container": "podman"}})) - with pytest.raises(ValueError, match="provider.container is not a mapping"): - ia.container_sudo(ns(container_sudo=False, pool_config=str(pool))) - - -@pytest.mark.parametrize("returned", [None, "loaded", {"reload_mode": "in_place"}]) -def test_a_reload_without_a_load_report_fails(returned, capsys): - class NoReport(FakeEngine): - def load(self, release_dir, version): - super().load(release_dir, version) - return returned - - engine = NoReport() - record = node_smoke.run_smoke(engine, release=None) - assert (record["ok"], record["step"]) == (False, "reload") and engine.stopped - assert f"the engine's load returned {type(returned).__name__}, not a LoadReport with a reload_mode" \ - in record["error"] - last = json.loads(capsys.readouterr().out.splitlines()[-1].split(" ", 1)[1]) - assert (last["step"], last["ok"]) == ("reload", False) + assert ia.container_sudo(ns(container_sudo=False)) is False and ia.container_sudo(ns(container_sudo=True)) + on = ia.pool_view(str(_pool_config(tmp_path / "on.yaml", inv, sudo=True)), profiles) + off = ia.pool_view(str(_pool_config(tmp_path / "off.yaml", inv)), profiles) + assert ia.container_sudo(ns(container_sudo=False), on) is True + assert ia.container_sudo(ns(container_sudo=True), on) is True + assert ia.container_sudo(ns(container_sudo=False), off) is False + with pytest.raises(ValueError, match="--container-sudo contradicts --pool-config .*container.sudo is off"): + ia.container_sudo(ns(container_sudo=True), off) + + +@pytest.mark.parametrize("text, message", [ + ("provider: [a, b]\n", "provider is not a mapping"), + ("- a\n", "not a pool config"), + ("provider: {container: podman}\n", "provider.container is not a mapping"), + ("provider: {kind: ssh\n", "cannot be read (ParserError"), +]) +def test_a_pool_config_that_is_not_one_is_refused_without_a_traceback(tmp_path, capsys, text, message): + inv = _podman_inventory(tmp_path) + pool = tmp_path / "pool.yaml" + pool.write_text(text) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + args = _cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, + "--release", RELEASE, "--pool-config", pool, "--dry-run") + assert ia.main(args) == 2 + err = capsys.readouterr().err + assert message in err and "Traceback" not in err + + +def test_a_venv_pool_a_trainer_and_a_contradicting_flag_exit_2(tmp_path, capsys): + inv = _podman_inventory(tmp_path) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + venv = tmp_path / "venv.yaml" + venv.write_text(yaml.safe_dump({"provider": {"kind": "ssh", "inventory": str(inv), "workdir": "/srv/yeto/run1", + "runtime": "venv", "venv": {"python": "/opt/venv/bin/python"}}})) + base = (TAGGED, "--model", "org/m", "--inventory", inv, "--dry-run") + assert ia.main(_cli(*base, "--role", "sampler", "--sampler-spec", spec, "--release", RELEASE, + "--pool-config", venv)) == 2 + assert "a runtime: venv pool runs its samplers from a venv on the host, not from an image" in \ + capsys.readouterr().err + pool = _pool_config(tmp_path / "pool.yaml", inv) + assert ia.main(_cli(*base, "--role", "trainer", "--pool-config", pool)) == 2 + assert "--pool-config is an ssh sampler pool's config: it is for --role sampler" in capsys.readouterr().err + assert ia.main(_cli(*base, "--role", "sampler", "--sampler-spec", spec, "--release", RELEASE, + "--pool-config", pool, "--container-sudo")) == 2 + assert "--container-sudo contradicts --pool-config" in capsys.readouterr().err + + +def test_the_pool_s_engine_and_nodes_win_over_the_inventory(tmp_path, capsys): + """An inventory that names no container (docker by default) and a pool config whose + engine is podman: the pool starts podman containers, so the adoption is podman + throughout; only the pool's ``nodes:`` take part, and one not in the inventory is an + error.""" + inv = _podman_inventory(tmp_path, n=3) + doc = yaml.safe_load(inv.read_text()) + for entry in doc["nodes"]: + entry.pop("container") + inv.write_text(yaml.safe_dump(doc)) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + base = (TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, + "--release", RELEASE, "--dry-run") + assert ia.main(_cli(*base)) == 0 # no pool config: the inventory's docker, as before + assert "docker pull" in capsys.readouterr().out + pool = _pool_config(tmp_path / "pool.yaml", inv, provider={"nodes": ["b300-0", "b300-2"]}) + assert ia.main(_cli(*base, "--pool-config", pool)) == 0 + out = capsys.readouterr().out + assert "on 2 node(s) ['b300-0', 'b300-2']" in out and "b300-1" not in out + assert "2. probe on b300-0: podman run --rm" in out + assert f"then podman pull {sm.REF} on ['b300-0', 'b300-2'] in parallel" in out and "docker" not in out + assert "container.pull is never" not in out + bad = _pool_config(tmp_path / "bad.yaml", inv, provider={"nodes": ["b300-0", "b300-9"]}) + assert ia.main(_cli(*base, "--pool-config", bad)) == 2 + assert "nodes ['b300-9'] are not in the inventory" in capsys.readouterr().err + + +def test_a_pool_that_never_pulls_still_gets_the_image_pulled_by_the_adoption(tmp_path, capsys): + inv = _podman_inventory(tmp_path) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + pool = _pool_config(tmp_path / "pool.yaml", inv, pull="never") + assert ia.main(_cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", inv, "--sampler-spec", spec, + "--release", RELEASE, "--pool-config", pool, "--dry-run")) == 0 + out = capsys.readouterr().out + assert f"podman pull {sm.REF} on ['b300-0', 'b300-1'] in parallel; the pool's container.pull is never (it " \ + "starts only images already on its nodes): this pull is what puts the image there" in out diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index fbef2102c..9c4b9df43 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -585,15 +585,19 @@ def _held(self, error: AdoptError) -> AdoptError: stays there, a retry reuses it, `` rmi`` frees the room.""" if not self.holding or error.holding: return error - from .node_inventory import profile_of # noqa: PLC0415 + from .preflight.cluster import engine_command # noqa: PLC0415 ref = self.report.pinned or self.request.ref + by_name = {n.name: n for n in self.request.nodes} + per: dict[str, list[str]] = {} # each holding node's own engine (and sudo) + for name in self.holding: + node = by_name.get(name) + engine = (engine_of(node) if node is not None else None) or "docker" + per.setdefault(engine_command(engine, self.request.container_sudo), []).append(name) nodes = ", ".join(self.holding) - engine = profile_of(self.request.probe_node).container - engine = ("sudo -n " if self.request.container_sudo else "") + (engine if engine in ("docker", "podman") - else "docker") + remove = "; ".join(f"`{command} rmi {ref}` on {', '.join(names)}" for command, names in sorted(per.items())) return AdoptError(error.step, f"{error.reason}; the image stays pulled on {nodes} (a retry reuses it; " - f"`{engine} rmi {ref}` there frees the room)", holding=self.holding) + f"{remove} frees the room)", holding=self.holding) def _hold(self, *names: str) -> None: self.holding += [n for n in names if n not in self.holding] @@ -672,7 +676,8 @@ def _probe_host(self, node: Node, ref: str) -> None: req = Requirements(min_image_root_free_gib=float(self.request.min_image_free_gib)) checks = ClusterPreflight([node], image=ref, ops=self.ops, req=req, log=self.log, clock=self.clock, - engine=container_engine(node), sudo=self.request.container_sudo).hosts() + engine=container_engine(node), sudo=self.request.container_sudo, + by_engine=True).hosts() failed = [c for c in checks if c.status == FAIL and c.name in ("ssh", "host_probe", "disk_images")] if failed: raise AdoptError("probe", "; ".join(f"node {c.scope}: {c.name}: {c.detail}" + (f" ({c.fix})" if c.fix @@ -758,7 +763,7 @@ def _pull(self, ref: str) -> tuple[str, dict[str, Any]]: checks, pulled = [], True for engine, nodes in sorted(groups.items()): pf = ClusterPreflight(nodes, image=ref, ops=self.ops, req=req, log=self.log, clock=self.clock, - engine=engine, sudo=self.request.container_sudo) + engine=engine, sudo=self.request.container_sudo, by_engine=True) found, ok = pf.pull() checks += found pulled = pulled and ok @@ -873,12 +878,19 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: """The smoke plan, with the image as :data:`.image_smoke.REF` (the trainer's backend: the registry's, which has a smoke only for the default backend).""" from . import image_smoke # noqa: PLC0415 + from .node_inventory import profile_of # noqa: PLC0415 workdir = Path(site_images.default_path()).parent / "image-adopt" / run_id if request.role == "trainer": if request.container_sudo: raise image_smoke.SmokeError("--container-sudo / a pool config's container.sudo is for sampler pool " "nodes: the ssh: trainer island runs docker as the ssh user") + off = [f"{n.name} ({n.runtime}, container {engine_of(n) or profile_of(n).container})" for n in request.nodes + if n.runtime != "docker" or engine_of(n) != "docker"] + if off: # every node of the role runs the island's image, not only the smoke node + raise image_smoke.SmokeError(f"trainer nodes {off}: an ssh: trainer island starts docker containers " + "only (inventory runtime: docker); podman and rootfs nodes take sampler " + "images (--role sampler)") plan = image_smoke.trainer_plan( request.probe_node, model=request.model, config=_model_config(args), engine=request.engine, store=args.smoke_store, run_id=run_id, workdir=workdir, model_revision=args.model_revision, @@ -890,21 +902,62 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: keep=args.keep_smoke_artifacts, sudo=request.container_sudo) -def container_sudo(args: Any) -> bool: - """``--container-sudo``, else the pool config's ``provider.container.sudo`` (the - inventory has no such key), else off.""" - if getattr(args, "container_sudo", False): - return True - path = getattr(args, "pool_config", None) - if not path: - return False +@dataclass(frozen=True) +class PoolView: + """The ssh sampler pool a sampler image is adopted for (``--pool-config``): its nodes + as the pool starts them (:func:`.ssh_sampler_pool.pool_profile`: the pool's + ``container.engine``, whatever the inventory says), its ``container.sudo`` and + ``container.pull``.""" + + path: str + nodes: tuple[Node, ...] + sudo: bool + pull: str + + +def pool_view(path: str, profiles: Sequence[Node]) -> PoolView: + """The pool config at ``path`` read the way the pool reads it + (:func:`.ssh_sampler_pool.parse_config` over the adoption's inventory ``profiles``: + its ``nodes:``, its container section). Raises ValueError for a file that is not a + pool config, a pool the pool itself refuses, and a ``runtime: venv`` pool (it runs + no image).""" import yaml # noqa: PLC0415 - cfg = yaml.safe_load(Path(path).expanduser().read_text()) or {} - container = ((cfg.get("provider") or {}) if isinstance(cfg, Mapping) else {}).get("container") or {} - if not isinstance(container, Mapping): + from . import ssh_sampler_pool # noqa: PLC0415 + + try: + cfg = yaml.safe_load(Path(path).expanduser().read_text()) + except (OSError, yaml.YAMLError) as error: + raise ValueError(f"--pool-config {path}: cannot be read ({type(error).__name__}: {error})"[:600]) from None + if not isinstance(cfg, Mapping): + raise ValueError(f"--pool-config {path}: not a pool config (a mapping with a provider section)") + provider = cfg.get("provider") + if not isinstance(provider, Mapping): + raise ValueError(f"--pool-config {path}: provider is not a mapping") + if provider.get("container") is not None and not isinstance(provider.get("container"), Mapping): raise ValueError(f"--pool-config {path}: provider.container is not a mapping") - return bool(container.get("sudo", False)) + try: + conf = ssh_sampler_pool.parse_config(dict(cfg), inventory=list(profiles)) + except (ValueError, TypeError, KeyError) as error: + raise ValueError(f"--pool-config {path}: {error}") from None + if conf.runtime != "container" or conf.container is None: + raise ValueError(f"--pool-config {path}: a runtime: {conf.runtime} pool runs its samplers from a venv on " + "the host, not from an image: there is no image to adopt for it") + return PoolView(str(path), tuple(ssh_sampler_pool.pool_profile(n, conf) for n in conf.nodes), + bool(conf.container.sudo), str(conf.container.pull)) + + +def container_sudo(args: Any, pool: PoolView | None = None) -> bool: + """``--container-sudo``, else the pool config's ``container.sudo`` (the inventory has + no such key), else off. The flag against a pool that runs its engine without sudo is + a ValueError: the adoption would fill another store than the one the pool starts from.""" + flag = bool(getattr(args, "container_sudo", False)) + if pool is None: + return flag + if flag and not pool.sudo: + raise ValueError(f"--container-sudo contradicts --pool-config {pool.path}: its container.sudo is off (the " + "pool runs the engine as the ssh user); drop the flag or fix the pool config") + return pool.sudo def _by_engine(nodes: Sequence[Node]) -> dict[str, list[str]]: @@ -927,6 +980,8 @@ def _sampler_spec(args: Any) -> dict[str, Any]: def main(args: Any, *, ops: Any = None, out: Any = None) -> int: """``yeto image adopt``: 0 recorded (or a dry run), 1 a step failed, 2 a bad request.""" + import yaml # noqa: PLC0415 + from . import image_smoke # noqa: PLC0415 from .node_inventory import InventoryError, load_profiles # noqa: PLC0415 from .preflight.cluster import engine_command # noqa: PLC0415 @@ -934,8 +989,14 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: out = out or sys.stdout try: # profiles: an inventory's container (podman) and the other node profile keys count here - nodes = role_nodes(load_profiles(args.inventory), args.role) - sudo = container_sudo(args) + profiles = load_profiles(args.inventory) + pool = None + if getattr(args, "pool_config", None): + if args.role != "sampler": + raise ValueError("--pool-config is an ssh sampler pool's config: it is for --role sampler") + pool = pool_view(args.pool_config, profiles) # the pool's nodes, engine, sudo and pull + nodes = list(pool.nodes) if pool else role_nodes(profiles, args.role) + sudo = container_sudo(args, pool) catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) spec_engine = engine_images.spec_needs(_sampler_spec(args))["engine_pref"] if args.role == "sampler" \ and args.sampler_spec else None @@ -951,7 +1012,7 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: if args.role == "trainer" and not request.engine: # the record names the backend the smoke ran request = dataclasses.replace(request, engine=str(plan.data["engine"])) except (InventoryError, site_images.SiteImagesError, image_smoke.SmokeError, FileNotFoundError, OSError, - ValueError) as error: + ValueError, TypeError, yaml.YAMLError) as error: print(f"yeto image adopt: {error}", file=sys.stderr) return 2 if args.dry_run: @@ -966,7 +1027,10 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then " + "; ".join(f"{engine_command(engine, sudo)} pull {image_smoke.REF} on {names}" for engine, names in _by_engine(request.nodes).items()) - + " in parallel", + + " in parallel" + + "".join(f"; not pulled (no container engine): {n.name}" for n in request.nodes if not engine_of(n)) + + (f"; the pool's container.pull is never (it starts only images already on its nodes): this " + "pull is what puts the image there" if pool and pool.pull == "never" else ""), "5. " + "\n".join(plan.lines()), f"then: a verified-smoke record in {catalog}"] print("\n".join(lines), file=out) diff --git a/yeto/launch/preflight/cluster.py b/yeto/launch/preflight/cluster.py index c9a73a199..e5c6524d7 100644 --- a/yeto/launch/preflight/cluster.py +++ b/yeto/launch/preflight/cluster.py @@ -538,6 +538,9 @@ class NodeState: pulled: bool = True engine: str = "docker" # the container engine whose image root and pull are checked sudo: bool = False # the engine runs as sudo -n (a pool's container.sudo: its rootful store) + # the node takes part by its profile's container engine, whatever its runtime (yeto image adopt); + # False: the preflight's own rule, the nodes of runtime docker + by_engine: bool = False @property def name(self) -> str: @@ -722,7 +725,7 @@ def add(check: str, status: str, detail: str, fix: str = "", **data: Any) -> Non add("disk", PASS, f"{free:.0f} GiB free: {where}", free_gib=free) info = parse_docker_info(h["docker"].text) if _ok(h.get("docker")) else None image_roots = {} - if info is not None and node.runtime == "docker": + if info is not None and (state.engine == "docker" if state.by_engine else node.runtime == "docker"): # the containerd image store (Docker 29 default) keeps images and container layers # under /var/lib/containerd, which does not follow docker's data-root snap = docker_snapshotter(info) @@ -1117,14 +1120,19 @@ def __init__(self, nodes: Sequence[Node], *, image: str | None = None, ops: SshO req: Requirements | None = None, steps: Steps | None = None, out_dir: Path | None = None, log: Callable[[str], None] = lambda m: print(m, file=sys.stderr, flush=True), clock: Callable[[], float] = time.time, max_parallel: int = 32, - inventory: Sequence[Node] | None = None, engine: str = "docker", sudo: bool = False) -> None: + inventory: Sequence[Node] | None = None, engine: str = "docker", sudo: bool = False, + by_engine: bool = False) -> None: """``engine``: the container engine whose image root the host probe checks and that :meth:`pull` pulls with (``docker``, the trainer's; ``podman`` for ``yeto image adopt`` on podman nodes); ``sudo``: it runs as ``sudo -n `` - (an ssh sampler pool's ``container.sudo``: the rootful store).""" + (an ssh sampler pool's ``container.sudo``: the rootful store); ``by_engine``: the + nodes were chosen by their container engine (``yeto image adopt``): every one is + pulled and has its engine's image root checked, whatever its ``runtime`` (default: + the preflight's rule, the nodes of ``runtime: docker``).""" self.nodes = list(nodes) self.engine = engine self.sudo = bool(sudo) + self.by_engine = bool(by_engine) self.inventory = list(inventory) if inventory is not None else None # decides "grouped" # nodes, or node pairs, at once. At least 2: the two ends of a pair (ib_write_bw # server and client, the two NCCL ranks) must run together, or the server waits @@ -1140,7 +1148,7 @@ def __init__(self, nodes: Sequence[Node], *, image: str | None = None, ops: SshO self.log = log self.clock = clock self.multi = len(self.nodes) > 1 - self.states = [NodeState(n, engine=engine, sudo=self.sudo) for n in self.nodes] + self.states = [NodeState(n, engine=engine, sudo=self.sudo, by_engine=self.by_engine) for n in self.nodes] # -- helpers def _raw(self, step: str, name: str, text: str) -> None: @@ -1272,7 +1280,8 @@ def one(state: NodeState) -> list[Check]: def _pull(self, live: Sequence[NodeState]) -> list[Check]: engine, command = self.engine, engine_command(self.engine, self.sudo) # docker: the nodes that run docker (the trainer's); another engine: every node it was asked for - docker = [s for s in live if s.node.runtime == "docker"] if engine == "docker" else list(live) + docker = ([s for s in live if s.node.runtime == "docker"] if engine == "docker" and not self.by_engine + else list(live)) self.log(f"[preflight] {command} pull on {len(docker)} node(s)") def one(state: NodeState) -> Check: From c60bf59eec8e154b86f56db4461f14447a5829bd Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 03:30:48 +0800 Subject: [PATCH 6/7] image adopt: a trainer's flash attention needs sm90+ cards; the smoke trains with the checked backend - fit: a trainer with --attention-backend flash on a node below sm90 (an A10G, sm86: its backward pass fails with "Unsupported compute capability", unfused trains) is not a fit on any node of the role; the reason names --attention-backend unfused. The image floor's flash lift no longer turns that into a warning. A sampler is not held to it. - --attention-backend takes auto | flash | fused | unfused; the trainer smoke launches with it (--rl-training-attention-backend), and a --smoke-arg of that flag is the backend the fit checks; the two naming different backends exit 2. - The dry run's fit line names the trainer's attention backend. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 7 ++++- tests/test_image_adopt.py | 57 ++++++++++++++++++++++++++++++++++++-- tests/test_image_smoke.py | 57 +++++++++++++++++++++++++++++++++++++- yeto/launch/image_adopt.py | 43 ++++++++++++++++++++++++---- yeto/launch/image_smoke.py | 20 +++++++++++-- 5 files changed, 173 insertions(+), 11 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index f961e52a1..098232c3e 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -754,7 +754,12 @@ to adopt the image. The steps, in order: check`): the smoke runs real kernels on the card. `--strict-arch` asks for a cubin of exactly the node's architecture. A ROCm node's `gfx` target must be built (feature suffixes such as `:xnack-` are ignored). A mismatch names the - rule and the node's card. + rule and the node's card. A trainer's `--attention-backend flash` needs sm90+ + cards on every node of the role: below that (an A10G, `sm86`) its backward pass + fails, so the fit refuses it and names `--attention-backend unfused` instead. The + smoke trains with the backend the fit checked (`--rl-training-attention-backend`, + also taken from a `--smoke-arg`; the two must agree). A sampler is not held to + this floor. 4. **pull**: every node of the role (spares included, `roles: [trainer-spare]`) is checked over SSH, and its image root (the docker data root, or `/var/lib/containerd` with the containerd image store, or podman's storage diff --git a/tests/test_image_adopt.py b/tests/test_image_adopt.py index 265ba76d5..bcc4a2839 100644 --- a/tests/test_image_adopt.py +++ b/tests/test_image_adopt.py @@ -320,9 +320,62 @@ def test_the_trainer_floor_still_applies_to_a_known_trainer_image(tmp_path): facts = ia.parse_probe(probe_out(arch_list=["sm_80", "sm_90"])) problems, _, _ = ia.fit_problems(request([a100], tmp_path), ref, facts, "miles") assert len(problems) == 1 and "node b300-0: trainer image" in problems[0] and "sm90+" in problems[0] - lifted = dataclasses.replace(request([a100], tmp_path), attention_backend="flash") + lifted = dataclasses.replace(request([a100], tmp_path), attention_backend="unfused") problems, warnings, _ = ia.fit_problems(lifted, ref, facts, "miles") - assert problems == [] and "the flash attention backend takes another path" in warnings[0] + assert problems == [] and "the unfused attention backend takes another path" in warnings[0] + flash = dataclasses.replace(request([a100], tmp_path), attention_backend="flash") + problems, warnings, _ = ia.fit_problems(flash, ref, facts, "miles") # flash's own floor, not the lift + assert len(problems) == 1 and "flash attention needs sm90+ cards; on A100-80GB (sm80)" in problems[0] + assert warnings == [] + + +A10G_FACTS = probe_out(arch_list=["sm_80", "sm_86", "sm_90", "sm_100", "sm_103"], + packages={**MILES_FACTS["packages"], "vllm": "0.11.0"}) + + +@pytest.mark.parametrize("card, backend, role, refused", [ + ("A10G", "flash", "trainer", True), # sm86: flash's backward fails (the rehearsal) + ("L40S", "flash", "trainer", True), # sm89: still below sm90 + ("H100", "flash", "trainer", False), # sm90: the floor itself + ("B300", "flash", "trainer", False), # sm103 + ("A10G", "unfused", "trainer", False), # unfused trains on sm86 + ("A10G", "fused", "trainer", False), # the floor is flash's only + ("A10G", "auto", "trainer", False), + ("A10G", "flash", "sampler", False), # inference attention: no such floor +]) +def test_the_trainer_s_flash_attention_needs_sm90(tmp_path, card, backend, role, refused): + node = b300(0, card=card, hbm_gib=24.0 if card == "A10G" else 80.0) + req = request([node], tmp_path, role=role, attention_backend=backend) + problems, _, _ = ia.fit_problems(req, PINNED, ia.parse_probe(A10G_FACTS), "miles" if role == "trainer" else "vllm") + if refused: + assert problems == [f"node b300-0: the trainer's flash attention needs sm90+ cards; on {card} " + f"({ia.node_card_arch(node)}) its backward pass fails (\"Unsupported compute " + "capability\"): pass --attention-backend unfused (the smoke trains with it; it holds " + "the full score matrix, short sequences only)"] + else: + assert problems == [] + + +def test_flash_on_sm86_stops_the_adoption_at_fit_on_any_node_of_the_role(tmp_path): + nodes = [b300(0, card="H100", hbm_gib=80.0), b300(1, card="A10G", hbm_gib=24.0)] + req = request(nodes, tmp_path, attention_backend="flash") + with pytest.raises(ia.AdoptError, match=r"step fit failed: node b300-1: the trainer's flash attention needs " + r"sm90\+ cards; on A10G \(sm86\)") as raised: + adopter(req, FakeNodes(nodes, probe=A10G_FACTS), smoke=passing_smoke()).run() + assert "node b300-0:" not in str(raised.value) # the H100 node passes the floor + assert not (tmp_path / "site-images.yaml").exists() + ok = request(nodes, tmp_path, attention_backend="unfused") + adopter(ok, FakeNodes(nodes, probe=A10G_FACTS), smoke=passing_smoke()).run() + assert [r.ref for r in si.load(tmp_path / "site-images.yaml")] == [PINNED] + + +@pytest.mark.parametrize("arch, refused", [("sm86", True), ("sm90", False), ("sm100", False), ("gfx950", False), + (None, False)]) +def test_the_flash_floor_reads_the_node_s_architecture(arch, refused, monkeypatch): + node = b300(0) + monkeypatch.setattr(ia, "node_card_arch", lambda n: arch) + assert (ia.flash_trainer_problem(node, "flash") is not None) is refused + assert ia.flash_trainer_problem(node, "unfused") is None and ia.flash_trainer_problem(node, None) is None def test_a_catalog_sampler_image_is_held_to_its_record(tmp_path): diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index d4cf8d80c..c6ca86286 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -670,7 +670,7 @@ def test_an_image_interpreter_that_is_not_a_plain_path_is_refused(tmp_path, pyth assert ops.scripts == [] and ops.launch.calls == [] # nothing ran -def test_the_hf_token_goes_to_the_node_from_the_launcher_and_is_never_printed(tmp_path): +def test_the_hub_token_goes_to_the_node_from_the_launcher_and_is_never_printed(tmp_path): plan = _trainer_plan(tmp_path) prune = plan.steps[0] rendered = prune.render({sm.REF: PINNED, sm.PYTHON: PY}, {"HF_TOKEN": "tok-123", "OTHER": "x"}) @@ -1095,3 +1095,58 @@ def test_a_pool_that_never_pulls_still_gets_the_image_pulled_by_the_adoption(tmp out = capsys.readouterr().out assert f"podman pull {sm.REF} on ['b300-0', 'b300-1'] in parallel; the pool's container.pull is never (it " \ "starts only images already on its nodes): this pull is what puts the image there" in out + + +def _launch_value(argv, flag): + return sm._flag_value(list(argv), flag) + + +def test_the_smoke_trains_with_the_attention_backend_the_fit_checks(tmp_path): + auto = _trainer_plan(tmp_path) + assert sm.ATTENTION not in auto.steps[1].argv # auto: the recipe decides, as before + plan = _trainer_plan(tmp_path, attention_backend="unfused") + for step in plan.steps[1:]: # train and resume + assert _launch_value(step.argv, sm.ATTENTION) == "unfused" and list(step.argv).count(sm.ATTENTION) == 1 + same = _trainer_plan(tmp_path, attention_backend="unfused", extra_args=(f"{sm.ATTENTION}=unfused",)) + assert list(same.steps[1].argv).count(f"{sm.ATTENTION}=unfused") == 1 and sm.ATTENTION not in same.steps[1].argv + with pytest.raises(sm.SmokeError, match="--attention-backend flash but --smoke-arg " + "--rl-training-attention-backend unfused"): + _trainer_plan(tmp_path, attention_backend="flash", extra_args=(sm.ATTENTION, "unfused")) + + +@pytest.mark.parametrize("asked, smoke_arg, want", [ + ("auto", None, "auto"), ("unfused", None, "unfused"), ("auto", "flash", "flash"), ("flash", "flash", "flash"), +]) +def test_the_attention_backend_comes_from_the_flag_or_the_smoke_arg(asked, smoke_arg, want): + extra = (f"{sm.ATTENTION}={smoke_arg}",) if smoke_arg else () + assert sm.smoke_attention(asked, extra) == want + + +def test_the_cli_holds_the_fit_to_the_smoke_s_attention_backend(tmp_path, capsys, monkeypatch): + seen = {} + + class Captured: + def __init__(self, request, **kw): + seen["request"] = request + self.report = ia.AdoptReport(request) + + def run(self): + raise ia.AdoptError("manifest", "stopped by the test") + + base = (TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", + _inventory(tmp_path, card="A10G", hbm_gib=24, cards_per_node=1), + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s") + assert ia.main(_cli(*base, "--attention-backend", "unfused", "--dry-run"), ops=SimpleNamespace(run=None)) == 0 + out = capsys.readouterr().out + assert "3. fit: " in out and "; the trainer's unfused attention (flash: sm90+ cards)" in out + assert f"{sm.ATTENTION} unfused" in out + monkeypatch.setattr(ia, "Adopter", Captured) + assert ia.main(_cli(*base, f"--smoke-arg={sm.ATTENTION}=flash")) == 1 + assert seen["request"].attention_backend == "flash" # what the fit refuses on the A10G node + assert ia.flash_trainer_problem(seen["request"].probe_node, seen["request"].attention_backend) + capsys.readouterr() + assert ia.main(_cli(*base, "--attention-backend", "flash", f"--smoke-arg={sm.ATTENTION}=unfused", + "--dry-run")) == 2 + assert "the fit would check another backend than the smoke trains with" in capsys.readouterr().err + with pytest.raises(SystemExit): + _cli(*base, "--attention-backend", "flashy") diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index 9c4b9df43..a7aac7715 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -426,6 +426,28 @@ def node_card_arch(node: Node) -> str | None: return str(arch).lower() if arch else None +# The trainer's flash attention (Megatron --attention-backend flash) trains on Hopper and +# newer only: on A10G (sm86) cards the Miles image's forward pass runs and the backward +# fails ("Unsupported compute capability"), while unfused trains (own-cluster rehearsal, +# 2026-11-26). A sampler's inference attention is not held to it. +FLASH_TRAINER_MIN_ARCH = "sm90" + + +def flash_trainer_problem(node: Node, attention_backend: str | None) -> str | None: + """The problem of a trainer on ``node`` with the ``flash`` attention backend below + :data:`FLASH_TRAINER_MIN_ARCH` (None: another backend, a card at or above it, or a + card of no CUDA architecture known here).""" + if (attention_backend or "auto") != "flash": + return None + arch = node_card_arch(node) + have, need = _cc(arch or ""), _cc(FLASH_TRAINER_MIN_ARCH) + if have is None or need is None or have[1] >= need[1]: + return None + return (f"node {node.name}: the trainer's flash attention needs {FLASH_TRAINER_MIN_ARCH}+ cards; on {node.card} " + f"({arch}) its backward pass fails (\"Unsupported compute capability\"): pass --attention-backend " + "unfused (the smoke trains with it; it holds the full score matrix, short sequences only)") + + def card_arch_fit(facts: ImageFacts, node: Node, *, strict: bool = False) -> tuple[str | None, str | None]: """``(problem, note)`` of the image's built card architectures on ``node``'s cards (problem None: they serve them, or the node's architecture is unknown; note: how). @@ -523,6 +545,10 @@ def fit_problems(request: AdoptRequest, ref: str, facts: ImageFacts, if note: notes.append(note) if request.role == "trainer": + flash = flash_trainer_problem(node, request.attention_backend) + if flash: # the backend's own floor, before the image's (which flash would lift) + problems.append(flash) + continue found = trainer_image_check.image_problem(ref, node.card, attention_backend=request.attention_backend) if found: (problems if found[1] else warnings).append(f"node {node.name}: {found[0]}") @@ -824,8 +850,10 @@ def add_parser(sub: Any) -> Any: a.add_argument("--catalog", default=None, help="the site image catalog (default: the inventory's site_images:)") a.add_argument("--min-image-free-gib", type=float, default=120.0, help="free GiB the image root (docker data root / containerd store) of every node needs") - a.add_argument("--attention-backend", default="auto", - help="the trainer's attention backend, for the trainer image floor (default auto)") + a.add_argument("--attention-backend", default="auto", choices=["auto", "flash", "fused", "unfused"], + help="the trainer's attention backend: the fit holds the image floor and flash's sm90+ floor " + "to it, and the smoke trains with it (--rl-training-attention-backend; default auto: the " + "recipe's)") a.add_argument("--strict-arch", action="store_true", help="the image must carry a cubin of exactly the node's card architecture (no CUDA " "minor-version or PTX compatibility)") @@ -895,7 +923,7 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: request.probe_node, model=request.model, config=_model_config(args), engine=request.engine, store=args.smoke_store, run_id=run_id, workdir=workdir, model_revision=args.model_revision, model_path=args.model_path, layers=args.smoke_layers, extra_args=tuple(args.smoke_arg), - keep=args.keep_smoke_artifacts) + keep=args.keep_smoke_artifacts, attention_backend=request.attention_backend) return plan spec = _sampler_spec(args) return image_smoke.sampler_plan(request.probe_node, spec=spec, run_id=run_id, release=args.release, @@ -1000,9 +1028,12 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) spec_engine = engine_images.spec_needs(_sampler_spec(args))["engine_pref"] if args.role == "sampler" \ and args.sampler_spec else None + # trainer: the backend the fit checks is the one the smoke trains with (--attention-backend or a --smoke-arg) + attention = image_smoke.smoke_attention(args.attention_backend, tuple(args.smoke_arg)) \ + if args.role == "trainer" else args.attention_backend request = AdoptRequest(ref=args.ref, model=args.model, role=args.role, nodes=tuple(nodes), engine=args.engine, node=args.node, catalog=catalog, - min_image_free_gib=args.min_image_free_gib, attention_backend=args.attention_backend, + min_image_free_gib=args.min_image_free_gib, attention_backend=attention, strict_arch=args.strict_arch, allow_busy=args.allow_busy, spec_engine=spec_engine, container_sudo=sudo) stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S") @@ -1023,7 +1054,9 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: f"1. manifest: HEAD of {args.ref} in its registry; a tag is pinned to its digest " f"(below: {image_smoke.REF})", f"2. probe on {node.name}: {probe_script(image_smoke.REF, node, sudo=sudo)[:200]} ...", - f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}", + f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}" + + (f"; the trainer's {request.attention_backend} attention (flash: {FLASH_TRAINER_MIN_ARCH}+ cards)" + if args.role == "trainer" else ""), f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then " + "; ".join(f"{engine_command(engine, sudo)} pull {image_smoke.REF} on {names}" for engine, names in _by_engine(request.nodes).items()) diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py index 16b76c3ff..2bc67c76e 100644 --- a/yeto/launch/image_smoke.py +++ b/yeto/launch/image_smoke.py @@ -79,6 +79,7 @@ # launch flags the smoke sets unless --smoke-arg gives them: a rate (one step: it barely matters); no model # preflight from the launcher (the cut exists only on the node: the prune step made and checked it) LAUNCH_DEFAULTS = (("--inner-lr", "1e-6"), ("--preflight-model", "off")) +ATTENTION = "--rl-training-attention-backend" # the trainer's attention backend (yeto image adopt --attention-backend) BYTES_PER_PARAM = {"bf16": 2.0, "fp16": 2.0, "fp32": 4.0, "fp8": 1.0, "int8": 1.0, "mxfp4": 0.53, "int4": 0.53, "nvfp4": 0.56} MAX_LAYERS = 16 # the MFU 16L cut @@ -302,6 +303,17 @@ def _flag_value(args: Sequence[str], flag: str) -> str | None: return found +def smoke_attention(attention_backend: str | None, extra_args: Sequence[str]) -> str: + """The trainer's attention backend the fit checks and the smoke trains with: + ``--attention-backend``, else a ``--smoke-arg`` of :data:`ATTENTION`, else ``auto`` + (the recipe's). The two naming different backends is a :class:`SmokeError`.""" + asked, given = attention_backend or "auto", _flag_value(extra_args, ATTENTION) + if given is not None and asked != "auto" and given != asked: + raise SmokeError(f"--attention-backend {asked} but --smoke-arg {ATTENTION} {given}: the fit would check " + "another backend than the smoke trains with; give one") + return given or asked + + def _replace_flag(flags: list[str], extra: Sequence[str]) -> list[str]: """``flags`` without the ``--flag value`` pairs ``extra`` gives again (the operator's value wins: a registry placeholder such as ````).""" @@ -319,11 +331,12 @@ def _replace_flag(flags: list[str], extra: Sequence[str]) -> list[str]: def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: str | None, store: str | None, run_id: str, workdir: Path, model_revision: str | None = None, model_path: str | None = None, layers: int | None = None, extra_args: Sequence[str] = (), python: str | None = None, - keep: bool = False) -> SmokePlan: + keep: bool = False, attention_backend: str = "auto") -> SmokePlan: """The trainer smoke's steps (module doc). Raises :class:`SmokeError` for what is missing: a backend without a train-only replay, a node without ``scratch``, no store for the checkpoint, a registry placeholder no ``--smoke-arg`` fills. - ``keep``: the cleanup leaves the artifacts and prints where they are.""" + ``keep``: the cleanup leaves the artifacts and prints where they are; + ``attention_backend`` (not ``auto``): the launch trains with it (:data:`ATTENTION`).""" engine_name = profile_of(node).container if node.runtime != "docker" or engine_name != "docker": raise SmokeError(f"node {node.name} runs {node.runtime} (container {engine_name}): the trainer smoke runs " @@ -342,6 +355,9 @@ def trainer_plan(node: Node, *, model: str, config: Mapping[str, Any], engine: s "its train-only replay is not wired") trust, trust_notes = remote_code(config, layout["recommendation"].family, extra_args) extra_args = [a for a in extra_args if a not in (TRUST, NO_TRUST)] + attention = smoke_attention(attention_backend, extra_args) + if attention != "auto" and _flag_value(extra_args, ATTENTION) is None: + extra_args += [ATTENTION, attention] # as a --smoke-arg: it replaces a registry flag of its own n = layout["layers"] slug = f"{_slug(model)}-{n}layer" repo = f"{SMOKE_MODEL_ORG}/{slug}" From 14f21262565f12c9897ac673037e207be8aad7d1 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 04:52:46 +0800 Subject: [PATCH 7/7] image adopt: fit the backend the smoke resolves; the pool's inventory and catalog; spec and flag checks - The fit checks the trainer attention backend the smoke's launch resolves: its train argv through the yeto launch parser and training_attention, so under --attention-backend auto a recipe that trains with flash (deepseek-v4-flash, Qwen3.8-Flash-Next) is held to the sm90+ flash floor. Those recipes run flash only (run_config.FLASH_ONLY_RECIPES, now one constant): the fit then names sm90+ cards rather than unfused, and another backend for them exits 2. The dry-run fit line names the backend and its source. - --pool-config: the inventory is the pool's provider.inventory (the pool requires one) and the catalog its site_images:. --inventory or --catalog naming another file exits 2 with both paths; --inventory may be left out. - A sampler spec that is not a JSON object, or whose engine, engine.server, engine.options or rollout_fields is not one, exits 2 without a traceback. - The smoke's attention backend must be auto | flash | fused | unfused, and an abbreviation of --rl-training-attention-backend in a --smoke-arg is refused (yeto launch takes long options by their full name only). - A sampler adopted without --pool-config prints a NOTE that its engine comes from the inventory. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 24 ++-- tests/test_image_smoke.py | 205 ++++++++++++++++++++++++++++++++++- yeto/launch/image_adopt.py | 177 +++++++++++++++++++++++++----- yeto/launch/image_smoke.py | 34 +++++- yeto/rl/engine/run_config.py | 4 +- 5 files changed, 405 insertions(+), 39 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 098232c3e..497208667 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -757,9 +757,13 @@ to adopt the image. The steps, in order: rule and the node's card. A trainer's `--attention-backend flash` needs sm90+ cards on every node of the role: below that (an A10G, `sm86`) its backward pass fails, so the fit refuses it and names `--attention-backend unfused` instead. The - smoke trains with the backend the fit checked (`--rl-training-attention-backend`, - also taken from a `--smoke-arg`; the two must agree). A sampler is not held to - this floor. + backend the fit checks is the one the smoke's launch resolves: with the default + `auto` that is the recipe's own (`deepseek-v4-flash` and Qwen3.8-Flash-Next train + with flash, so they are held to sm90+ too; those recipes have no other path, so + the fit names other cards, and another backend for them exits 2). The dry run's + fit line names the backend and where it comes from. The smoke trains with that + backend (`--rl-training-attention-backend`, also taken from a `--smoke-arg`, + written in full; the two must agree). A sampler is not held to this floor. 4. **pull**: every node of the role (spares included, `roles: [trainer-spare]`) is checked over SSH, and its image root (the docker data root, or `/var/lib/containerd` with the containerd image store, or podman's storage @@ -776,17 +780,21 @@ to adopt the image. The steps, in order: that engine, and one with no container engine is named as not pulled. For a sampler image, pass the ssh sampler pool's config with `--pool-config`: - it is read the way the pool reads it, so the nodes are the pool's `nodes:` - (one not in the inventory is an error), their engine is the pool's + it is read the way the pool reads it, so the inventory is the pool's + `provider.inventory` (`--inventory` may be left out; one naming another file is + an error), the catalog is that inventory's `site_images:`, the one the pool + resolves `image: auto` from (a `--catalog` naming another file is an error), the + nodes are the pool's `nodes:` (one not in the inventory is an error), their + engine is the pool's `container.engine` (default podman, whatever the inventory says), and its `container.sudo: true` (`sudo -n podman`, the rootful store) makes the host checks, the pull, the probe and the smoke all run the engine through `sudo -n`, so the image lands in the store the pool starts from. A `runtime: venv` pool runs no image and is refused. With `container.pull: never` the pool starts only images already on its nodes: the adoption's pull - is what puts the image there. Without a pool config, `--container-sudo` asks - for `sudo -n`; against a pool config whose `container.sudo` is off it is an - error. + is what puts the image there. Without a pool config, each node's engine is + the inventory's (a NOTE says so) and `--container-sudo` asks for `sudo -n`; + against a pool config whose `container.sudo` is off it is an error. 5. **smoke**, on the probe node, after its cards are checked idle again: - **trainer**: the model is cut to its first N layers (all their experts, the embeddings and the head, `scripts/prune_layers.py`; MTP layers are dropped, diff --git a/tests/test_image_smoke.py b/tests/test_image_smoke.py index c6ca86286..c478f6a29 100644 --- a/tests/test_image_smoke.py +++ b/tests/test_image_smoke.py @@ -1082,7 +1082,9 @@ def test_the_pool_s_engine_and_nodes_win_over_the_inventory(tmp_path, capsys): assert "container.pull is never" not in out bad = _pool_config(tmp_path / "bad.yaml", inv, provider={"nodes": ["b300-0", "b300-9"]}) assert ia.main(_cli(*base, "--pool-config", bad)) == 2 - assert "nodes ['b300-9'] are not in the inventory" in capsys.readouterr().err + err = capsys.readouterr().err # the pool's own refusal, named as the pool config's + assert err.startswith(f"yeto image adopt: --pool-config {bad}: ") + assert "nodes ['b300-9'] are not in the inventory" in err def test_a_pool_that_never_pulls_still_gets_the_image_pulled_by_the_adoption(tmp_path, capsys): @@ -1138,7 +1140,7 @@ def run(self): "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s") assert ia.main(_cli(*base, "--attention-backend", "unfused", "--dry-run"), ops=SimpleNamespace(run=None)) == 0 out = capsys.readouterr().out - assert "3. fit: " in out and "; the trainer's unfused attention (flash: sm90+ cards)" in out + assert "3. fit: " in out and "; trainer attention unfused (--attention-backend)\n" in out assert f"{sm.ATTENTION} unfused" in out monkeypatch.setattr(ia, "Adopter", Captured) assert ia.main(_cli(*base, f"--smoke-arg={sm.ATTENTION}=flash")) == 1 @@ -1150,3 +1152,202 @@ def run(self): assert "the fit would check another backend than the smoke trains with" in capsys.readouterr().err with pytest.raises(SystemExit): _cli(*base, "--attention-backend", "flashy") + + + +DSV4 = REGISTRY_CONFIGS / "configs" / "deepseek_v4_flash.json" + + +class _CaptureAdopter: + seen: dict = {} + + def __init__(self, request, **kw): + _CaptureAdopter.seen["request"] = request + self.report = ia.AdoptReport(request) + + def run(self): + raise ia.AdoptError("manifest", "stopped by the test") + + +@pytest.mark.parametrize("card, refused", [("A100-80GB", True), ("L40S", True), ("H100", False), ("B300", False)]) +def test_a_recipe_that_trains_with_flash_is_held_to_the_flash_floor_under_auto(tmp_path, capsys, monkeypatch, card, + refused): + """deepseek-v4-flash trains with flash whatever --attention-backend auto says: the fit + checks the backend the smoke's launch resolves, so an A100 / L40S is refused before + any cut or training, an H100 / B300 passes.""" + from tests.test_image_adopt import A10G_FACTS + + inv = _inventory(tmp_path, card=card, hbm_gib=80 if card != "B300" else 288) + base = (TAGGED, "--model", "deepseek-ai/DeepSeek-V4-Flash", "--role", "trainer", "--inventory", inv, + "--model-config", DSV4, "--smoke-store", "s3://b/s") + assert ia.main(_cli(*base, "--dry-run"), ops=SimpleNamespace(run=None)) == 0 + out = capsys.readouterr().out + assert "--rl-model-recipe deepseek-v4-flash" in out and sm.ATTENTION not in out # the launch is unchanged + assert "; trainer attention flash (the deepseek-v4-flash recipe), held to sm90+ cards\n" in out + monkeypatch.setattr(ia, "Adopter", _CaptureAdopter) + assert ia.main(_cli(*base)) == 1 + req = _CaptureAdopter.seen["request"] + assert (req.attention_backend, req.attention_source, req.flash_only) == ("flash", "the deepseek-v4-flash recipe", + True) + problems, _, _ = ia.fit_problems(req, PINNED, ia.parse_probe(A10G_FACTS), "miles") + flash = [p for p in problems if "flash attention" in p] + if refused: + assert flash == [f"node b300-0: the trainer's flash attention (the deepseek-v4-flash recipe) needs sm90+ " + f"cards; on {card} ({ia.node_card_arch(req.probe_node)}) its backward pass fails " + "(\"Unsupported compute capability\"): the recipe trains with flash only (its kernels have " + "no unfused or fused path): adopt the image on sm90+ cards"] + else: + assert flash == [] + + +def test_a_flash_only_recipe_refuses_another_backend_and_the_generic_recipe_is_not_held(tmp_path, capsys, monkeypatch): + inv = _inventory(tmp_path, card="A100-80GB", hbm_gib=80) + dsv4 = (TAGGED, "--model", "deepseek-ai/DeepSeek-V4-Flash", "--role", "trainer", "--inventory", inv, + "--model-config", DSV4, "--smoke-store", "s3://b/s", "--dry-run") + assert ia.main(_cli(*dsv4, "--attention-backend", "unfused")) == 2 + assert "--attention-backend unfused: the smoke's recipe trains with flash attention only" in capsys.readouterr().err + assert ia.main(_cli(*dsv4, f"--smoke-arg={sm.ATTENTION}=fused")) == 2 + assert f"--smoke-arg {sm.ATTENTION} fused: the smoke's recipe" in capsys.readouterr().err + monkeypatch.setattr(ia, "Adopter", _CaptureAdopter) + qwen = (TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", + _inventory(tmp_path, card="A10G", hbm_gib=24, cards_per_node=1), + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s") + assert ia.main(_cli(*qwen)) == 1 + req = _CaptureAdopter.seen["request"] + assert (req.attention_backend, req.attention_source, req.flash_only) == ("fused", "the generic recipe", False) + assert ia.flash_trainer_problem(req.probe_node, req.attention_backend) is None + assert ia.main(_cli(*qwen, f"--smoke-arg={sm.ATTENTION}=flash")) == 1 + req = _CaptureAdopter.seen["request"] + assert (req.attention_backend, req.attention_source) == ("flash", f"--smoke-arg {sm.ATTENTION}") + assert "pass --attention-backend unfused" in ia.flash_trainer_problem(req.probe_node, "flash") + + +def test_an_unparsable_smoke_launch_keeps_the_asked_backend(tmp_path): + plan = _trainer_plan(tmp_path, attention_backend="unfused") + argv = ("py", "-m", "yeto.cli", "launch", "--no-such") + broken = SimpleNamespace(steps=[SimpleNamespace(name="train", argv=argv)]) + assert ia.smoke_training_attention(broken, "unfused", from_flag=True) == ("unfused", "--attention-backend", False) + assert ia.smoke_training_attention(broken, "auto", from_flag=False) == ("auto", "the smoke's launch", False) + assert ia.smoke_training_attention(plan, "unfused", from_flag=True) == ("unfused", "--attention-backend", False) + + +def _pool_with_inventory(tmp_path, inventory, name="pool.yaml", **provider): + return _pool_config(tmp_path / name, inventory, provider=provider) + + +def test_the_pool_s_inventory_and_catalog_win_and_the_command_line_must_agree(tmp_path, capsys): + inv = _podman_inventory(tmp_path) + doc = yaml.safe_load(inv.read_text()) + doc["site_images"] = "pool-site-images.yaml" + inv.write_text(yaml.safe_dump(doc)) + pool_catalog = tmp_path / "pool-site-images.yaml" + other = tmp_path / "other" + other.mkdir() + copy = other / "cluster.yaml" + copy.write_text(inv.read_text()) # the same nodes, another file + link = tmp_path / "link.yaml" + link.symlink_to(inv) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + pool = _pool_config(tmp_path / "pool.yaml", inv) + base = (TAGGED, "--model", "org/m", "--role", "sampler", "--sampler-spec", spec, "--release", RELEASE, + "--pool-config", pool, "--dry-run") + # no --inventory: the pool's; the catalog is its inventory's site_images: + assert ia.main(_cli(*base)) == 0 + out = capsys.readouterr().out + assert f"then: a verified-smoke record in {pool_catalog}" in out and "['b300-0', 'b300-1']" in out + # the same file under another name (a symlink) agrees + assert ia.main(_cli(*base, "--inventory", link, "--catalog", pool_catalog)) == 0 + capsys.readouterr() + # another inventory file + assert ia.main(_cli(*base, "--inventory", copy)) == 2 + err = capsys.readouterr().err + assert f"--inventory {copy} is not the inventory of --pool-config {pool} (provider.inventory {inv})" in err + assert "Traceback" not in err + # another catalog + elsewhere = tmp_path / "elsewhere.yaml" + assert ia.main(_cli(*base, "--catalog", elsewhere)) == 2 + err = capsys.readouterr().err + assert f"--catalog {elsewhere} is not the site image catalog of --pool-config {pool} ({pool_catalog}," in err + # neither an inventory nor a pool that names one + assert ia.main(_cli(TAGGED, "--model", "org/m", "--role", "sampler", "--sampler-spec", spec, "--release", + RELEASE, "--dry-run")) == 2 + assert "--inventory is required (or a --pool-config whose provider.inventory names one)" in capsys.readouterr().err + + +def test_a_pool_without_an_inventory_of_its_own_is_refused_as_the_pool_refuses_it(tmp_path, capsys): + inv = _podman_inventory(tmp_path) + pool = _pool_config(tmp_path / "pool.yaml", inv) + doc = yaml.safe_load(pool.read_text()) + doc["provider"].pop("inventory") + pool.write_text(yaml.safe_dump(doc)) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + args = (TAGGED, "--model", "org/m", "--role", "sampler", "--sampler-spec", spec, "--release", RELEASE, + "--pool-config", pool, "--inventory", inv, "--dry-run") + assert ia.main(_cli(*args)) == 2 + err = capsys.readouterr().err + assert f"yeto image adopt: --pool-config {pool}: provider.inventory is required" in err and "Traceback" not in err + assert ia.pool_inventory(str(pool)) is None + + +@pytest.mark.parametrize("text, message", [ + ("[1, 2]", "not a sampler spec (a JSON object), got list"), + ('"x"', "not a sampler spec (a JSON object), got str"), + ("null", "not a sampler spec (a JSON object), got NoneType"), + ('{"engine": 5}', "engine is not an object (got int)"), + ('{"engine": {"server": [1]}}', "engine.server is not an object (got list)"), + ('{"engine": {"adapter": "vllm-server"}, "rollout_fields": "x"}', "rollout_fields is not an object (got str)"), +]) +def test_a_sampler_spec_that_is_not_one_exits_2_without_a_traceback(tmp_path, capsys, text, message): + spec = tmp_path / "spec.json" + spec.write_text(text) + args = _cli(TAGGED, "--model", "org/m", "--role", "sampler", "--inventory", _inventory(tmp_path), + "--sampler-spec", spec, "--release", RELEASE, "--dry-run") + assert ia.main(args) == 2 + err = capsys.readouterr().err + assert f"yeto image adopt: --sampler-spec {spec}: {message}" in err and "Traceback" not in err + + +@pytest.mark.parametrize("asked, extra, message", [ + ("flashy", (), "--attention-backend 'flashy' is not an attention backend"), + ("auto", (f"{sm.ATTENTION}=sdpa",), f"--smoke-arg {sm.ATTENTION} 'sdpa' is not an attention backend"), + ("auto", ("--rl-training-attention=flash",), "--smoke-arg --rl-training-attention: an abbreviation of " + f"{sm.ATTENTION}; yeto launch takes long options by their full name " + f"only: write {sm.ATTENTION}"), + ("auto", ("--rl-training-attention-b", "flash"), "--smoke-arg --rl-training-attention-b: an abbreviation"), +]) +def test_the_smoke_s_attention_backend_is_a_known_value_by_its_full_flag(asked, extra, message): + with pytest.raises(sm.SmokeError, match=re.escape(message)): + sm.smoke_attention(asked, extra) + + +def test_an_abbreviated_attention_flag_exits_2_and_other_flags_pass(tmp_path, capsys): + base = (TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", _inventory(tmp_path), + "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", "--smoke-store", "s3://b/s", "--dry-run") + assert ia.main(_cli(*base, "--smoke-arg=--rl-training-attention=unfused")) == 2 + assert "an abbreviation of --rl-training-attention-backend" in capsys.readouterr().err + # not abbreviations of the flag: other options start with them too (argparse called them ambiguous) + assert sm.smoke_attention("auto", ("--tuning=full", "--rl", "--", "--rl-train", "--rl-tr")) == "auto" + assert sm._abbreviates("--rl-traini", sm.ATTENTION) and not sm._abbreviates(sm.ATTENTION, sm.ATTENTION) + assert sm.smoke_attention("auto", (f"{sm.ATTENTION}=unfused",)) == "unfused" + + +def test_a_sampler_without_a_pool_config_notes_where_its_engine_comes_from(tmp_path, capsys): + spec = tmp_path / "spec.json" + spec.write_text(json.dumps(FAKE_SPEC)) + base = (TAGGED, "--model", "org/m", "--role", "sampler", "--sampler-spec", spec, "--release", RELEASE, + "--dry-run") + note = "yeto image adopt: NOTE: engine from inventory ({}); pass --pool-config to adopt with the pool's " \ + "container engine" + assert ia.main(_cli(*base, "--inventory", _inventory(tmp_path))) == 0 + assert note.format("docker") in capsys.readouterr().err + inv = _podman_inventory(tmp_path) + assert ia.main(_cli(*base, "--inventory", inv)) == 0 + assert note.format("podman") in capsys.readouterr().err + assert ia.main(_cli(*base, "--inventory", inv, "--pool-config", _pool_config(tmp_path / "pool.yaml", inv))) == 0 + assert "NOTE: engine from inventory" not in capsys.readouterr().err + assert ia.main(_cli(TAGGED, "--model", "Qwen/Qwen3-30B-A3B", "--role", "trainer", "--inventory", + _inventory(tmp_path), "--model-config", REGISTRY_CONFIGS / "qwen3_30b_a3b.json", + "--smoke-store", "s3://b/s", "--dry-run"), ops=SimpleNamespace(run=None)) == 0 + assert "NOTE: engine from inventory" not in capsys.readouterr().err diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py index a7aac7715..5106dc46f 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -35,6 +35,7 @@ import dataclasses import datetime import json +import os import re import shlex import sys @@ -103,6 +104,9 @@ class AdoptRequest: catalog: str | None = None min_image_free_gib: float = 120.0 attention_backend: str = "auto" + # where the trainer's backend comes from (the flag, the recipe) and whether its recipe runs flash only + attention_source: str = "" + flash_only: bool = False strict_arch: bool = False allow_busy: bool = False container_sudo: bool = False @@ -433,19 +437,27 @@ def node_card_arch(node: Node) -> str | None: FLASH_TRAINER_MIN_ARCH = "sm90" -def flash_trainer_problem(node: Node, attention_backend: str | None) -> str | None: +def flash_trainer_problem(node: Node, attention_backend: str | None, *, source: str = "", + flash_only: bool = False) -> str | None: """The problem of a trainer on ``node`` with the ``flash`` attention backend below :data:`FLASH_TRAINER_MIN_ARCH` (None: another backend, a card at or above it, or a - card of no CUDA architecture known here).""" + card of no CUDA architecture known here). ``source``: where the backend comes from + (the flag, the recipe); ``flash_only``: the recipe has no other attention path, so + the way out is other cards, not ``unfused``.""" if (attention_backend or "auto") != "flash": return None arch = node_card_arch(node) have, need = _cc(arch or ""), _cc(FLASH_TRAINER_MIN_ARCH) if have is None or need is None or have[1] >= need[1]: return None - return (f"node {node.name}: the trainer's flash attention needs {FLASH_TRAINER_MIN_ARCH}+ cards; on {node.card} " - f"({arch}) its backward pass fails (\"Unsupported compute capability\"): pass --attention-backend " - "unfused (the smoke trains with it; it holds the full score matrix, short sequences only)") + head = (f"node {node.name}: the trainer's flash attention{f' ({source})' if source else ''} needs " + f"{FLASH_TRAINER_MIN_ARCH}+ cards; on {node.card} ({arch}) its backward pass fails (\"Unsupported " + "compute capability\")") + if flash_only: + return head + (": the recipe trains with flash only (its kernels have no unfused or fused path): adopt the " + f"image on {FLASH_TRAINER_MIN_ARCH}+ cards") + return head + (": pass --attention-backend unfused (the smoke trains with it; it holds the full score matrix, " + "short sequences only)") def card_arch_fit(facts: ImageFacts, node: Node, *, strict: bool = False) -> tuple[str | None, str | None]: @@ -545,7 +557,8 @@ def fit_problems(request: AdoptRequest, ref: str, facts: ImageFacts, if note: notes.append(note) if request.role == "trainer": - flash = flash_trainer_problem(node, request.attention_backend) + flash = flash_trainer_problem(node, request.attention_backend, source=request.attention_source, + flash_only=request.flash_only) if flash: # the backend's own floor, before the image's (which flash would lift) problems.append(flash) continue @@ -841,13 +854,17 @@ def add_parser(sub: Any) -> Any: a.add_argument("ref", help="the image: REGISTRY/IMAGE:TAG or REGISTRY/IMAGE@sha256:") a.add_argument("--model", required=True, help="the model the image is built for (an HF id)") a.add_argument("--role", required=True, choices=site_images.ROLES) - a.add_argument("--inventory", required=True, help="the SSH node inventory (YAML / JSON)") + a.add_argument("--inventory", default=None, + help="the SSH node inventory (YAML / JSON); required unless --pool-config names one (its " + "provider.inventory, which it must then match)") a.add_argument("--engine", default=None, help="trainer: the --rl-backend (default: the model registry's recommendation; the smoke runs " "miles); sampler: vllm | sglang | vllm-ascend (default: the sampler spec's engine.adapter, " "else the engine found in the image); a spec that runs another engine is refused") a.add_argument("--node", default=None, help="the node that probes and smokes (default: the first of the role)") - a.add_argument("--catalog", default=None, help="the site image catalog (default: the inventory's site_images:)") + a.add_argument("--catalog", default=None, + help="the site image catalog (default: the pool's with --pool-config, else the inventory's " + "site_images:; with --pool-config it must be the pool's)") a.add_argument("--min-image-free-gib", type=float, default=120.0, help="free GiB the image root (docker data root / containerd store) of every node needs") a.add_argument("--attention-backend", default="auto", choices=["auto", "flash", "fused", "unfused"], @@ -861,7 +878,9 @@ def add_parser(sub: Any) -> Any: help="run the container engine as sudo -n (an ssh sampler pool's container.sudo: its " "rootful store); default: --pool-config's container.sudo, else off") a.add_argument("--pool-config", default=None, - help="the ssh sampler pool's config: its provider.container.sudo decides --container-sudo") + help="the ssh sampler pool's config (--role sampler): its nodes:, container engine and sudo " + "decide the nodes, the engine and --container-sudo; its provider.inventory and that " + "inventory's site_images: are the inventory and the catalog") a.add_argument("--allow-busy", action="store_true", help="probe and smoke a node whose cards run processes or that runs yeto containers (a warning)") a.add_argument("--keep-smoke-artifacts", action="store_true", @@ -930,29 +949,52 @@ def _plan(args: Any, request: AdoptRequest, run_id: str) -> Any: keep=args.keep_smoke_artifacts, sudo=request.container_sudo) +def smoke_training_attention(plan: Any, attention: str, *, from_flag: bool) -> tuple[str, str, bool]: + """``(backend, source, flash_only)`` of the trainer smoke's launch: its train argv + through the ``yeto launch`` parser and :func:`.trainer_image_check.training_attention` + (under ``auto``, the recipe's own backend: flash for ``deepseek-v4-flash``), where it + comes from, and whether the recipe runs flash only + (:data:`yeto.rl.engine.run_config.FLASH_ONLY_RECIPES`, Qwen3.8-Flash-Next). An argv + the parser does not take keeps ``attention`` (the launch reports it); ``from_flag``: + an explicit backend came from ``--attention-backend`` (else from a ``--smoke-arg``).""" + from ..rl.engine import run_config as rc # noqa: PLC0415 + from ..rl.up_consistency import trainer_args # noqa: PLC0415 + + train = next(s for s in plan.steps if s.name == "train") + argv = [str(a) for a in train.argv] + args = trainer_args(argv[argv.index("launch") + 1:]) if "launch" in argv else None + if args is None: + return attention, "--attention-backend" if from_flag else "the smoke's launch", False + backend, why = trainer_image_check.training_attention(args) + if why == "--rl-training-attention-backend": + why = "--attention-backend" if from_flag else f"--smoke-arg {why}" + flash_only = (getattr(args, "rl_model_recipe", None) in rc.FLASH_ONLY_RECIPES + or rc.qwen3_8_next_variant(args, None) is not None) + return backend, why, flash_only + + @dataclass(frozen=True) class PoolView: """The ssh sampler pool a sampler image is adopted for (``--pool-config``): its nodes as the pool starts them (:func:`.ssh_sampler_pool.pool_profile`: the pool's ``container.engine``, whatever the inventory says), its ``container.sudo`` and - ``container.pull``.""" + ``container.pull``, the inventory it names (``provider.inventory``) and its site + image catalog (that inventory's ``site_images:``, the catalog the pool resolves + ``image: auto`` from).""" path: str nodes: tuple[Node, ...] sudo: bool pull: str + inventory: str | None = None + site_images: str | None = None -def pool_view(path: str, profiles: Sequence[Node]) -> PoolView: - """The pool config at ``path`` read the way the pool reads it - (:func:`.ssh_sampler_pool.parse_config` over the adoption's inventory ``profiles``: - its ``nodes:``, its container section). Raises ValueError for a file that is not a - pool config, a pool the pool itself refuses, and a ``runtime: venv`` pool (it runs - no image).""" +def pool_document(path: str) -> Mapping[str, Any]: + """The pool config at ``path`` as a mapping with a ``provider`` mapping; ValueError + (prefixed ``--pool-config :``) for a file that cannot be read or is not one.""" import yaml # noqa: PLC0415 - from . import ssh_sampler_pool # noqa: PLC0415 - try: cfg = yaml.safe_load(Path(path).expanduser().read_text()) except (OSError, yaml.YAMLError) as error: @@ -964,6 +1006,25 @@ def pool_view(path: str, profiles: Sequence[Node]) -> PoolView: raise ValueError(f"--pool-config {path}: provider is not a mapping") if provider.get("container") is not None and not isinstance(provider.get("container"), Mapping): raise ValueError(f"--pool-config {path}: provider.container is not a mapping") + return cfg + + +def pool_inventory(path: str) -> str | None: + """The inventory file the pool config at ``path`` names (``provider.inventory``, + ``~`` expanded as the pool expands it), else None (the pool refuses that).""" + named = pool_document(path)["provider"].get("inventory") + return os.path.expanduser(str(named)) if named else None + + +def pool_view(path: str, profiles: Sequence[Node]) -> PoolView: + """The pool config at ``path`` read the way the pool reads it + (:func:`.ssh_sampler_pool.parse_config` over the inventory ``profiles``: its + ``nodes:``, its container section, its catalog). Raises ValueError for a file that is + not a pool config, a pool the pool itself refuses, and a ``runtime: venv`` pool (it + runs no image).""" + from . import ssh_sampler_pool # noqa: PLC0415 + + cfg = pool_document(path) try: conf = ssh_sampler_pool.parse_config(dict(cfg), inventory=list(profiles)) except (ValueError, TypeError, KeyError) as error: @@ -972,7 +1033,8 @@ def pool_view(path: str, profiles: Sequence[Node]) -> PoolView: raise ValueError(f"--pool-config {path}: a runtime: {conf.runtime} pool runs its samplers from a venv on " "the host, not from an image: there is no image to adopt for it") return PoolView(str(path), tuple(ssh_sampler_pool.pool_profile(n, conf) for n in conf.nodes), - bool(conf.container.sudo), str(conf.container.pull)) + bool(conf.container.sudo), str(conf.container.pull), inventory=pool_inventory(path), + site_images=conf.site_images) def container_sudo(args: Any, pool: PoolView | None = None) -> bool: @@ -988,6 +1050,38 @@ def container_sudo(args: Any, pool: PoolView | None = None) -> bool: return pool.sudo +def _same_file(a: str, b: str) -> bool: + return os.path.realpath(os.path.expanduser(str(a))) == os.path.realpath(os.path.expanduser(str(b))) + + +def _pool_inventory_choice(pool_config: str, inventory: str | None) -> str: + """The inventory a sampler adopted for the pool at ``pool_config`` is read from: the + pool's own ``provider.inventory`` (its nodes are the ones the pool starts; the pool + requires one). None of it, or an ``--inventory`` naming another file, is a ValueError.""" + named = pool_inventory(pool_config) + if not named: + raise ValueError(f"--pool-config {pool_config}: provider.inventory is required (the pool reads its nodes " + "from it; ssh provider: inventory (an SSH node inventory file) is required)") + if inventory and not _same_file(inventory, named): + raise ValueError(f"--inventory {inventory} is not the inventory of --pool-config {pool_config} " + f"(provider.inventory {named}): the pool's nodes come from its inventory; drop --inventory " + "or pass the same file") + return named + + +def _catalog_choice(catalog: str | None, pool: PoolView | None, inventory: str) -> str: + """``--catalog``, else the pool's site image catalog (``--pool-config``: the one it + resolves ``image: auto`` from), else the inventory's. A ``--catalog`` that is not the + pool's is a ValueError: the record would land where the pool never looks.""" + if pool is not None and pool.site_images: + if catalog and not _same_file(catalog, pool.site_images): + raise ValueError(f"--catalog {catalog} is not the site image catalog of --pool-config {pool.path} " + f"({pool.site_images}, its inventory's site_images:): the pool would not find the " + "record; drop --catalog or pass that file") + return str(pool.site_images) + return catalog or str(site_images.inventory_catalog_path(inventory)) + + def _by_engine(nodes: Sequence[Node]) -> dict[str, list[str]]: """The node names per container engine (docker / podman; a node of none is left out).""" out: dict[str, list[str]] = {} @@ -1003,7 +1097,19 @@ def _sampler_spec(args: Any) -> dict[str, Any]: if not args.sampler_spec: raise image_smoke.SmokeError("the sampler smoke runs the pool's sampler spec: pass --sampler-spec") - return json.loads(Path(args.sampler_spec).expanduser().read_text()) + spec = json.loads(Path(args.sampler_spec).expanduser().read_text()) + if not isinstance(spec, Mapping): + raise image_smoke.SmokeError(f"--sampler-spec {args.sampler_spec}: not a sampler spec (a JSON object), " + f"got {type(spec).__name__}") + engine = spec.get("engine") + sections = {"engine": engine, "rollout_fields": spec.get("rollout_fields")} + if isinstance(engine, Mapping): + sections.update({"engine.server": engine.get("server"), "engine.options": engine.get("options")}) + for name, value in sections.items(): + if value is not None and not isinstance(value, Mapping): + raise image_smoke.SmokeError(f"--sampler-spec {args.sampler_spec}: {name} is not an object " + f"(got {type(value).__name__})") + return dict(spec) def main(args: Any, *, ops: Any = None, out: Any = None) -> int: @@ -1016,16 +1122,24 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: out = out or sys.stdout try: - # profiles: an inventory's container (podman) and the other node profile keys count here - profiles = load_profiles(args.inventory) - pool = None - if getattr(args, "pool_config", None): + inventory = args.inventory + pool_config = getattr(args, "pool_config", None) + if pool_config: if args.role != "sampler": raise ValueError("--pool-config is an ssh sampler pool's config: it is for --role sampler") - pool = pool_view(args.pool_config, profiles) # the pool's nodes, engine, sudo and pull + inventory = _pool_inventory_choice(pool_config, inventory) + if not inventory: + raise ValueError("--inventory is required (or a --pool-config whose provider.inventory names one)") + # profiles: an inventory's container (podman) and the other node profile keys count here + profiles = load_profiles(inventory) + pool = pool_view(pool_config, profiles) if pool_config else None # the pool's nodes, engine, sudo, pull nodes = list(pool.nodes) if pool else role_nodes(profiles, args.role) sudo = container_sudo(args, pool) - catalog = args.catalog or str(site_images.inventory_catalog_path(args.inventory)) + catalog = _catalog_choice(args.catalog, pool, inventory) + if args.role == "sampler" and not pool: + engines = ", ".join(_by_engine(nodes)) or "none" + print(f"yeto image adopt: NOTE: engine from inventory ({engines}); pass --pool-config to adopt with the " + "pool's container engine", file=sys.stderr) spec_engine = engine_images.spec_needs(_sampler_spec(args))["engine_pref"] if args.role == "sampler" \ and args.sampler_spec else None # trainer: the backend the fit checks is the one the smoke trains with (--attention-backend or a --smoke-arg) @@ -1040,6 +1154,14 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: slug = re.sub(r"[^a-z0-9]+", "-", args.model.rsplit("/", 1)[-1].lower()).strip("-")[:24] or "model" run_id = f"adopt-{slug}-{args.role}-{stamp}" plan = _plan(args, request, run_id) + if args.role == "trainer": # the fit checks the backend the smoke's launch resolves (auto: the recipe's) + backend, source, flash_only = smoke_training_attention(plan, attention, + from_flag=args.attention_backend != "auto") + if flash_only and backend != "flash": + raise image_smoke.SmokeError(f"{source} {backend}: the smoke's recipe trains with flash attention only " + "(its kernels have no unfused or fused path); drop it") + request = dataclasses.replace(request, attention_backend=backend, attention_source=source, + flash_only=flash_only) if args.role == "trainer" and not request.engine: # the record names the backend the smoke ran request = dataclasses.replace(request, engine=str(plan.data["engine"])) except (InventoryError, site_images.SiteImagesError, image_smoke.SmokeError, FileNotFoundError, OSError, @@ -1055,7 +1177,8 @@ def main(args: Any, *, ops: Any = None, out: Any = None) -> int: f"(below: {image_smoke.REF})", f"2. probe on {node.name}: {probe_script(image_smoke.REF, node, sudo=sudo)[:200]} ...", f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}" - + (f"; the trainer's {request.attention_backend} attention (flash: {FLASH_TRAINER_MIN_ARCH}+ cards)" + + (f"; trainer attention {request.attention_backend} ({request.attention_source})" + + (f", held to {FLASH_TRAINER_MIN_ARCH}+ cards" if request.attention_backend == "flash" else "") if args.role == "trainer" else ""), f"4. pull: ssh + host probe (image root >= {args.min_image_free_gib:g} GiB free), then " + "; ".join(f"{engine_command(engine, sudo)} pull {image_smoke.REF} on {names}" diff --git a/yeto/launch/image_smoke.py b/yeto/launch/image_smoke.py index 2bc67c76e..e5e370b72 100644 --- a/yeto/launch/image_smoke.py +++ b/yeto/launch/image_smoke.py @@ -48,9 +48,11 @@ from __future__ import annotations +import argparse import base64 import copy import dataclasses +import functools import json import os import re @@ -80,6 +82,7 @@ # preflight from the launcher (the cut exists only on the node: the prune step made and checked it) LAUNCH_DEFAULTS = (("--inner-lr", "1e-6"), ("--preflight-model", "off")) ATTENTION = "--rl-training-attention-backend" # the trainer's attention backend (yeto image adopt --attention-backend) +ATTENTION_BACKENDS = ("auto", "flash", "fused", "unfused") # the launch flag's choices BYTES_PER_PARAM = {"bf16": 2.0, "fp16": 2.0, "fp32": 4.0, "fp8": 1.0, "int8": 1.0, "mxfp4": 0.53, "int4": 0.53, "nvfp4": 0.56} MAX_LAYERS = 16 # the MFU 16L cut @@ -303,11 +306,40 @@ def _flag_value(args: Sequence[str], flag: str) -> str | None: return found +@functools.lru_cache(maxsize=1) +def _launch_options() -> frozenset[str]: + """The long options of ``yeto launch``.""" + from ..cli import build_parser # noqa: PLC0415 + + parser = build_parser() + action = next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction)) # noqa: SLF001 + return frozenset(o for a in action.choices["launch"]._actions for o in a.option_strings # noqa: SLF001 + if o.startswith("--")) + + +def _abbreviates(name: str, flag: str) -> bool: + """``name`` is an abbreviation of ``flag`` as argparse took one: a proper prefix that + no other ``yeto launch`` option starts with (a prefix that other options share is + ambiguous, not an abbreviation).""" + if not name.startswith("--") or len(name) <= 2 or name == flag or not flag.startswith(name): + return False + return not any(o.startswith(name) for o in _launch_options() if o != flag) + + def smoke_attention(attention_backend: str | None, extra_args: Sequence[str]) -> str: """The trainer's attention backend the fit checks and the smoke trains with: ``--attention-backend``, else a ``--smoke-arg`` of :data:`ATTENTION`, else ``auto`` - (the recipe's). The two naming different backends is a :class:`SmokeError`.""" + (the recipe's). The two naming different backends, a value outside + :data:`ATTENTION_BACKENDS` and an abbreviation of the flag are a :class:`SmokeError`.""" + for arg in extra_args: # yeto launch takes long options by their full name only (no abbreviations) + name = str(arg).split("=", 1)[0] + if name != ATTENTION and _abbreviates(name, ATTENTION): + raise SmokeError(f"--smoke-arg {name}: an abbreviation of {ATTENTION}; yeto launch takes long options " + f"by their full name only: write {ATTENTION}") asked, given = attention_backend or "auto", _flag_value(extra_args, ATTENTION) + for where, value in (("--attention-backend", asked), (f"--smoke-arg {ATTENTION}", given)): + if value is not None and value not in ATTENTION_BACKENDS: + raise SmokeError(f"{where} {value!r} is not an attention backend (one of {list(ATTENTION_BACKENDS)})") if given is not None and asked != "auto" and given != asked: raise SmokeError(f"--attention-backend {asked} but --smoke-arg {ATTENTION} {given}: the fit would check " "another backend than the smoke trains with; give one") diff --git a/yeto/rl/engine/run_config.py b/yeto/rl/engine/run_config.py index 01c27bf20..dd1c12e8c 100644 --- a/yeto/rl/engine/run_config.py +++ b/yeto/rl/engine/run_config.py @@ -48,6 +48,8 @@ # bridge). The recipe is driven by the provider's layer pattern and router # fields, not by one checkpoint (adapters/miles/models/nemotron_h.py). RECIPE_NEMOTRON_H = "nemotron_h" +# recipes whose kernels hard-require flash attention (no unfused / fused path) +FLASH_ONLY_RECIPES = frozenset({RECIPE_DEEPSEEK_V4_FLASH, RECIPE_QWEN3_8_NEXT}) # Kimi-K3.1-Pro (kimi_k31): KDA + DSA MLA + 896-expert latent MoE through the # Miles plugin spec; 128 experts per MoE layer trained in place from an # expert_selection.json (adapters/miles/models/kimi_k31), raw bridge mode. @@ -1140,7 +1142,7 @@ def resolve_rl_run_config( # attention refuse any other backend. backend_override = getattr(args, "rl_training_attention_backend", "auto") or "auto" if backend_override != "auto": - if recipe_name in {RECIPE_DEEPSEEK_V4_FLASH, RECIPE_QWEN3_8_NEXT} and backend_override != "flash": + if recipe_name in FLASH_ONLY_RECIPES and backend_override != "flash": raise ValueError( f"the {recipe_name} recipe requires --rl-training-attention-backend flash " "(its kernels have no unfused/fused path)"