diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 68cf4d9bc..497208667 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -704,3 +704,214 @@ 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 --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 (`--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, 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. 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 + 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 + 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`), 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 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, 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, + 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`, 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. 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, and only on `runtime: docker` nodes (the `ssh:` + 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`, + 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, 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`; 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 + 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` (`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 +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 +``` + +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 (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 (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: + +``` +[launcher] ssh trainer image REGISTRY/IMAGE@sha256:... (adopted 2026-11-26T10:00:00Z on b300-0) (source: site image catalog ...) +``` + +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_adopt.py b/tests/test_image_adopt.py index 5d7f6ae23..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): @@ -364,8 +417,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 +741,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 new file mode 100644 index 000000000..c478f6a29 --- /dev/null +++ b/tests/test_image_smoke.py @@ -0,0 +1,1353 @@ +"""``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 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 +from yeto.rl.engine.object_store import DirectoryObjectStore + +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 +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): + 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 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) + (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, **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"), **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=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) + + +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", 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): + (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", 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, 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() + + +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", 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=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(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", 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 ---------------------------------------------------------------- + + +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 + 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}"), + ("--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 + 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]) + 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 + 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): + 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", [ + ({"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 + + +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 train writes its + cut's manifest into the store ``store``), and the cleanup's ``yeto down``.""" + + 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" + 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="") + + +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 + 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(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 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("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_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), 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): + 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(tmp_path / "store")), "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(" 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 + + +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) # 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_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})"]) + 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"], + 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"]) + + +# -- 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_config(pool, inv, 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"}) + 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)) + 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; 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 + 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"trainer nodes ['b300-0 ({runtime}, container {container})']: an ssh: trainer island starts " + "docker containers only") in err + + +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)) 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 + 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): + 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 + + +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 "; 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 + 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") + + + +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/tests/test_run_flags.py b/tests/test_run_flags.py index 677df16f0..fa0b46e8d 100644 --- a/tests/test_run_flags.py +++ b/tests/test_run_flags.py @@ -261,8 +261,15 @@ def test_forward_tables_name_flags_of_both_layers(): # flags: syncer, docker, git, pip, ray, torchrun, sky, ... Pinned so that an island # flag renamed in the schema but still spelled the old way in the launcher fails. _NON_RL_LITERALS = frozenset({ - # yeto image adopt (yeto.launch.image_adopt): its flags, and the card tools / docker ps of its idle check + # 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; + # --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", "--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/cli.py b/yeto/cli.py index d03ded2dc..d48e21919 100644 --- a/yeto/cli.py +++ b/yeto/cli.py @@ -1177,6 +1177,10 @@ def build_parser() -> 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..5106dc46f 100644 --- a/yeto/launch/image_adopt.py +++ b/yeto/launch/image_adopt.py @@ -32,8 +32,10 @@ from __future__ import annotations +import dataclasses import datetime import json +import os import re import shlex import sys @@ -44,6 +46,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") @@ -100,9 +104,13 @@ 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 + 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: @@ -143,15 +151,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.""" @@ -190,6 +189,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 " @@ -429,6 +430,36 @@ 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, *, 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). ``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 + 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]: """``(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). @@ -498,6 +529,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; " @@ -523,6 +557,11 @@ 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, 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 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]}") @@ -535,10 +574,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 @@ -581,15 +624,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] @@ -615,6 +662,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) @@ -663,7 +715,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 @@ -749,7 +802,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 @@ -782,3 +835,372 @@ 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", 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 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"], + 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)") + 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 (--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", + 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, + 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 + 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, + model_path=args.model_path, layers=args.smoke_layers, extra_args=tuple(args.smoke_arg), + 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, + 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``, 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_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 + + 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 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: + 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), inventory=pool_inventory(path), + site_images=conf.site_images) + + +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 _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]] = {} + 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]: + 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()) + 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: + """``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 + + out = out or sys.stdout + try: + 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") + 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 = _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) + 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=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") + 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, + ValueError, TypeError, yaml.YAMLError) 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, sudo=sudo)[:200]} ...", + f"3. fit: CPU, device runtime, built card architectures and the {args.role} engine on {role}" + + (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}" + for engine, names in _by_engine(request.nodes).items()) + + " 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) + 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..e5e370b72 --- /dev/null +++ b/yeto/launch/image_smoke.py @@ -0,0 +1,785 @@ +"""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; 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, 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), ``--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; +3. ``resume`` (on the launcher): the same launch with ``--rl-stop-after-rounds 2``: it + 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: 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. 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`` +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, 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 + +import argparse +import base64 +import copy +import dataclasses +import functools +import json +import os +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@" +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 +# 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"}] +# 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) +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 +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) +# 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 +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).""" + + +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: + ``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 + 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) + 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: + 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) +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) + 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}:"] + 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()}") + for step in self.cleanup: + out.append(f" finally: {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, 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"}`` (``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 + 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) + 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: + 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 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 + + +@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, 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") + 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 ````).""" + 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, + 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; + ``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 " + "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: )") + if not store: + raise SmokeError("the trainer smoke writes its checkpoint to a run store: pass --smoke-store s3://BUCKET/PREFIX") + 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)}): " + "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}" + 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}" + 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_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; 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}" + + ("" 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 + 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 + 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", run_store, "--cluster-prefix", run_id, + "--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=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, + check="resume"), + ) + import yaml # noqa: PLC0415 + + plan = layout["plan"] + 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", *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 " + "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, "store": run_store, "workdir": str(workdir), "keep": bool(keep), + "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, + 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 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 + + 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 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: + 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, 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; + ``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 + from yeto.node.smoke import base_dir # 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") + 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}" + 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()} + name = container_name(run_id) + argv = node_launch.container_argv(profile, name=name, image=REF, env=env, python=PYTHON_SH, + 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}"), + 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; the reload " + "exercises the engine's hot-reload endpoint, not the format of a trainer release",) + 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) + 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), + 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 + + 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) + + 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) + 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 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: 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..f4b6afa98 --- /dev/null +++ b/yeto/node/smoke.py @@ -0,0 +1,157 @@ +"""``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; 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 +``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") +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: + 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 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 + 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: + 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()) 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)"