From afe883564ffe87b68be7e364c41a14698c20105e Mon Sep 17 00:00:00 2001 From: junyyang-amd Date: Tue, 17 Nov 2026 17:36:29 +0000 Subject: [PATCH 1/2] tools/rl/accept.py: RL acceptance harness and the mesh_sglang check (A1) Co-Authored-By: Claude Opus 5.5 --- tests/test_rl_accept.py | 191 ++++++++++++ tools/rl/accept.py | 533 +++++++++++++++++++++++++++++++++ tools/rl/checks/mesh_sglang.py | 136 +++++++++ 3 files changed, 860 insertions(+) create mode 100644 tests/test_rl_accept.py create mode 100755 tools/rl/accept.py create mode 100644 tools/rl/checks/mesh_sglang.py diff --git a/tests/test_rl_accept.py b/tests/test_rl_accept.py new file mode 100644 index 00000000000..c3ec161f55f --- /dev/null +++ b/tests/test_rl_accept.py @@ -0,0 +1,191 @@ +# SPDX-License-Identifier: MIT +"""tools/rl/accept.py: the ATOM worker command lines it starts, ``--dry-run``, +and the verdict, exit status and JSON of ``mesh_sglang`` on canned answers.""" + +import json +import shlex +import sys +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import pytest + +from atom.model_engine.arg_utils import EngineArgs +from atom.utils.arg_parser import FlexibleArgumentParser + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "rl")) +import accept +from checks import mesh_sglang + +SERVER = "exec python3 -m atom.entrypoints.openai_server " + + +@pytest.fixture +def models(tmp_path, monkeypatch): + """An HF cache holding the checkpoints, so nothing is downloaded.""" + for repo in ("Qwen3-1.7B-Base", "Qwen3-1.7B"): + (tmp_path / "hf" / "hub" / f"models--Qwen--{repo}" / "snapshots" / "s").mkdir( + parents=True + ) + monkeypatch.setattr(accept, "HF_HOME", str(tmp_path / "hf")) + + +def _server_argv(step: str) -> list[str]: + """The openai_server argv inside one dry-run ``docker run ... bash -c``.""" + script = shlex.split(step)[-1] + return shlex.split(script.split(SERVER, 1)[1]) + + +def _parse(argv): + return EngineArgs.add_cli_args(FlexibleArgumentParser()).parse_known_args(argv) + + +def test_atom_workers_start_as_rl_servers_on_their_own_ports(): + h = accept.Harness(106, dry_run=True) + h.start_atom_workers(2, "/ckpt", tp=2) + parsed = [_parse(_server_argv(step)) for step in h.steps] + for (ns, unknown), port in zip(parsed, (18200, 18202)): + assert (ns.model, ns.enable_rl, ns.tensor_parallel_size) == ("/ckpt", True, 2) + assert ns.port == port + 1 + assert unknown == ["--host", "0.0.0.0", "--server-port", str(port)] + assert [s.split("HIP_VISIBLE_DEVICES=")[1].split()[0] for s in h.steps] == [ + "0,1", + "2,3", + ] + + +def test_pd_pair_moves_kv_over_mooncake_tcp(): + h = accept.Harness(111, dry_run=True) + h.start_pd_pair("/ckpt") + configs = [ + json.loads(_parse(_server_argv(s))[0].kv_transfer_config) for s in h.steps + ] + assert [c["kv_role"] for c in configs] == ["kv_producer", "kv_consumer"] + assert {c["protocol"] for c in configs} == {"tcp"} + assert configs[0]["handshake_port"] != configs[1]["handshake_port"] + + +def test_dry_run_prints_each_container_and_runs_nothing(models, monkeypatch, capsys): + def refuse(argv, *args, **kwargs): + raise AssertionError(f"dry run ran {argv}") + + monkeypatch.setattr(accept.subprocess, "run", refuse) + assert accept.main(["mesh_sglang", "--dry-run"]) == 0 + runs = [ + s for s in capsys.readouterr().out.splitlines() if s.startswith("docker run") + ] + assert [shlex.split(s)[shlex.split(s).index("--name") + 1] for s in runs] == [ + "rl-106-sglang-18200", + "rl-106-sglang-18201", + "rl-106-mesh-build", + "rl-106-mesh-18202", + ] + assert " ".join(accept.LONG_ROLLOUT) in runs[-1] + + +def fake_mesh(stale=(), selector_required=True): + """A Harness whose ATOMesh answers over two SGLang workers as SMG's protocol + says, except that workers in ``stale`` ignore an update and, without + ``selector_required``, a fan-out with no selector goes to every worker.""" + + class FakeMesh(accept.Harness): + def __init__(self, issue, dry_run=False): + super().__init__(issue, dry_run) + self.versions = {"w0": "default", "w1": "default"} + + def model_dir(self, repo): + return "/ckpt/" + repo + + def start_sglang_workers(self, n, model): + return [f"http://w{i}" for i in range(n)] + + def start_mesh(self, urls, backend="atom", pd=False, model_path=None): + self.mesh_url = "http://mesh" + return self.mesh_url + + def entry(self, wid): + return {"id": wid, "url": f"http://{wid}", "engine": "sglang"} + + def call_mesh(self, method, path, body=None): + url = urlsplit(path) + parts = url.path.strip("/").split("/")[2:] + if parts == ["workers"]: + rows = [self.entry(w) for w in self.versions] + return 200, {"protocol_version": 1, "workers": rows, "total": 2} + if parts[0] == "workers": + if parts[1] not in self.versions: + return 404, {"error": "worker_not_found"} + if len(parts) == 2: + return 200, self.entry(parts[1]) + if "%20" in parts[3]: + return 400, {"error": "invalid_engine_path"} + version = self.versions[parts[1]] + return 200, {"status": 200, "body": {"weight_version": version}} + selector = parse_qs(url.query).get("selector", [""])[0] + if not selector and selector_required: + return 400, {"error": "selector_required"} + if selector.startswith("="): + return 400, {"error": "invalid_selector"} + if selector == "engine=vllm": + return 400, {"error": "no_workers_match"} + for wid in self.versions: + if parts[1] == "update_weights_from_disk" and wid not in stale: + self.versions[wid] = body["weight_version"] + results = {w: {"status": 200} for w in self.versions} + return 200, {"results": results, "failed": [], "total": 2, "succeeded": 2} + + return FakeMesh + + +@pytest.fixture +def on_node(tmp_path, monkeypatch): + monkeypatch.setattr(accept.socket, "gethostname", lambda: accept.NODE_HOST) + monkeypatch.setattr(accept, "OUT_DIR", tmp_path / "out") + return tmp_path / "out" / "mesh_sglang.json" + + +def _run(monkeypatch, capsys, harness): + monkeypatch.setattr(accept, "Harness", harness) + code = accept.main(["mesh_sglang"]) + return code, capsys.readouterr().out.strip() + + +def test_mesh_sglang_passes_when_every_route_answers_as_smg( + on_node, monkeypatch, capsys +): + code, out = _run(monkeypatch, capsys, fake_mesh()) + assert (code, out) == (0, "PASS mesh_sglang") + record = json.loads(on_node.read_text()) + assert record["passed"] and record["check"] == "mesh_sglang" + routes = record["data"]["routes"] + assert all(r["ok"] for r in routes.values()) + assert routes["model_info w1 after"]["body"]["body"] == { + "weight_version": mesh_sglang.VERSION + } + assert {f"probe {code}" for code in mesh_sglang.PROBES} <= routes.keys() + + +@pytest.mark.parametrize( + "harness,reason", + [ + (fake_mesh(stale=("w1",)), "model_info w1 after"), + (fake_mesh(selector_required=False), "probe selector_required"), + ], +) +def test_mesh_sglang_fails_naming_the_route( + on_node, monkeypatch, capsys, harness, reason +): + code, out = _run(monkeypatch, capsys, harness) + assert code == 1 and out == f"FAIL mesh_sglang: {reason}" + record = json.loads(on_node.read_text()) + assert not record["passed"] and record["reason"] == reason + + +def test_a_harness_error_is_a_fail(on_node, monkeypatch, capsys): + class Busy(fake_mesh()): + def start_sglang_workers(self, n, model): + raise accept.HarnessError("GPU [0] busy") + + code, out = _run(monkeypatch, capsys, Busy) + assert code == 1 and out == "FAIL mesh_sglang: HarnessError: GPU [0] busy" + assert not json.loads(on_node.read_text())["passed"] diff --git a/tools/rl/accept.py b/tools/rl/accept.py new file mode 100755 index 00000000000..84624696fbf --- /dev/null +++ b/tools/rl/accept.py @@ -0,0 +1,533 @@ +#!/usr/bin/env python3 +"""RL acceptance checks on pit2-p03-g24. + + python3 tools/rl/accept.py [--dry-run] + +Runs ``checks/.py``, which exports ``ISSUE`` (its containers are named +``rl--``), ``plan(h) -> list[str]`` (what ``--dry-run`` prints) +and ``run(h) -> Verdict``. Off the node, the script reruns itself there over +ssh once the node sees this tree. It writes ``OUT_DIR/.json`` and +container logs under ``OUT_DIR/logs//``, prints ``PASS `` or +``FAIL : `` and exits 0 only on PASS. Stdlib only: the node's +own python3 runs it. +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib +import json +import os +import shlex +import signal +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import asdict, dataclass, field +from pathlib import Path + +NODE = "junyan.yang@amd.com@pit2-p03-g24" +NODE_HOST = "pit2-p03-g24" +NODE_IP = "10.19.0.124" +TREE = Path(__file__).resolve().parents[2] +OUT_DIR = Path("/share_nfs/junyan_tmp_r120/rl-accept") +HF_HOME = "/share_nfs/junyan_tmp_r120/hf" +GATE_DIR = "/var/tmp/junyan_agent_team_gate" +ATOM_IMAGE = "rocm/atom-dev:nightly_202611081546" +# lmsysorg/sglang-rocm is untagged on the node; this is its image id. +SGLANG_IMAGE = "sha256:2456fff6cfaffb822026d089a0629a4859c84d2448864ffd6d5fa4f945ef2c86" +MESH_IMAGE = "atom-gate:local" +FIRST_PORT = 18200 +GPU_COUNT = 8 +GPU_BUSY_MB = 1024 +READY_TIMEOUT_S = 900 +CONTROL_TIMEOUT_S = 900 +# SMG's long-rollout launch profile, with which every check runs ATOMesh. +LONG_ROLLOUT = [ + "--enable-rl", + "--disable-health-check", + "--disable-circuit-breaker", + "--request-timeout-secs", + "14400", +] +# Explicit device flags (no --privileged on this node), as ~/issue455/pd_up.sh. +GPU_FLAGS = [ + "--network", "host", "--ipc", "host", "--shm-size", "32g", + "--device", "/dev/kfd", "--device", "/dev/dri", "--device", "/dev/infiniband", + "--group-add", "video", "--cap-add", "IPC_LOCK", "--ulimit", "memlock=-1:-1", +] # fmt: skip +# The image lacks jsonschema, which atom imports; the log names the atom that runs. +ATOM_PRELUDE = ( + "python3 -c 'import jsonschema' 2>/dev/null || pip install -q jsonschema " + "|| exit 1; python3 -c 'import atom; print(\"atom from\", atom.__file__)'; " +) +_TOPICS = ["a lighthouse", "the moon", "bread", "a river", "chess", "rain"] +_TOPICS += ["a violin", "glaciers"] +_FORMS = ["Write a short poem about", "Explain to a child", "List three facts about"] +_FORMS += ["Tell a story about"] +# 32 fixed prompts for "equals fresh": temperature 0, 64 new tokens, one at a time. +PROMPTS = [f"{form} {topic}." for form in _FORMS for topic in _TOPICS] +SAMPLING = {"temperature": 0, "max_new_tokens": 64} + + +class HarnessError(RuntimeError): + pass + + +@dataclass +class Verdict: + passed: bool + reason: str = "" + data: dict = field(default_factory=dict) + + +def http(method: str, url: str, body=None, timeout: float = CONTROL_TIMEOUT_S): + """(status, parsed JSON or text) of one call; an HTTP error is an answer.""" + data = None if body is None else json.dumps(body).encode() + headers = {} if data is None else {"Content-Type": "application/json"} + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + status, raw = resp.status, resp.read() + except urllib.error.HTTPError as e: + status, raw = e.code, e.read() + try: + return status, json.loads(raw) + except ValueError: + return status, raw.decode(errors="replace") + + +def _git(*args: str) -> bytes: + cmd = ["git", "-C", str(TREE), *args] + return subprocess.run(cmd, capture_output=True, check=True).stdout + + +def tree_digest() -> str: + """Digest of this tree's HEAD, its diff and its untracked files.""" + digest = hashlib.sha256( + _git("rev-parse", "HEAD") + _git("diff", "HEAD", "--binary") + ) + for name in _git("ls-files", "-o", "--exclude-standard", "-z").split(b"\0"): + if name: + digest.update(name + (TREE / name.decode()).read_bytes()) + return digest.hexdigest() + + +def wait_for_tree(want: str | None) -> None: + """Wait until this host sees the tree the caller digested (NFS lags).""" + for _ in range(30): + if want is None or tree_digest() == want: + return + time.sleep(3) + raise HarnessError(f"{NODE_HOST} still sees a different tree after 90 s") + + +class Harness: + """Containers, ports and GPUs of one check, and the calls a check makes. + + Workers take GPUs from 0 upward and ports from FIRST_PORT upward; a busy + GPU or port is refused, never skipped. With ``dry_run`` nothing runs: each + command is appended to ``steps`` instead. + """ + + def __init__(self, issue: int, dry_run: bool = False): + self.issue, self.dry_run = issue, dry_run + self.steps: list[str] = [] + self.containers: list[str] = [] + self.mesh_url: str | None = None + self._next_gpu, self._next_port = 0, FIRST_PORT + self._mesh_built = False + self._user = f"{os.getuid()}:{os.getgid()}" + + # -- processes --------------------------------------------------------- + + def sh(self, argv: list[str], check: bool = True) -> str: + if self.dry_run: + self.steps.append(shlex.join(argv)) + return "" + res = subprocess.run(argv, capture_output=True, text=True, check=False) + if check and res.returncode: + raise HarnessError( + f"{shlex.join(argv[:4])} ... exited {res.returncode}: {res.stderr[-2000:]}" + ) + return res.stdout + + def take_gpus(self, n: int) -> list[int]: + gpus = list(range(self._next_gpu, self._next_gpu + n)) + self._next_gpu += n + self.refuse_busy(gpus) + return gpus + + def refuse_busy(self, gpus: list[int]) -> None: + if max(gpus) >= GPU_COUNT: + raise HarnessError(f"needs GPU {max(gpus)}; the node has {GPU_COUNT}") + if not self.dry_run: + rows = json.loads(self.sh(["amd-smi", "monitor", "-v", "--json"])) + used = {r["gpu"]: r["vram_used"]["value"] for r in rows} + busy = [g for g in gpus if used.get(g, 0) > GPU_BUSY_MB] + if busy: + raise HarnessError(f"GPU {busy} busy (> {GPU_BUSY_MB} MB in use)") + + def take_port(self) -> int: + port, self._next_port = self._next_port, self._next_port + 1 + if not self.dry_run: + with socket.socket() as s: + if s.connect_ex(("127.0.0.1", port)) == 0: + raise HarnessError(f"port {port} is already in use") + return port + + def container(self, role: str, image: str, cmd: list[str], gpus=None, flags=()): + """Start ``rl--`` detached; removed at teardown.""" + name = f"rl-{self.issue}-{role}" + argv = ["docker", "run", "-d", "--name", name, *flags] + if gpus is not None: + argv += [ + *GPU_FLAGS, + "-e", + f"HIP_VISIBLE_DEVICES={','.join(map(str, gpus))}", + ] + argv += ["-v", "/share_nfs:/share_nfs", "-e", f"HF_HOME={HF_HOME}"] + argv += ["-e", "AITER_LOG_LEVEL=WARNING", image, *cmd] + if not self.dry_run: + self.sh(["docker", "rm", "-f", name], check=False) + self.containers.append(name) + self.sh(argv) + return name + + def wait_ready(self, name: str, url: str, path="/health", ok=lambda body: True): + if self.dry_run: + return + deadline = time.monotonic() + READY_TIMEOUT_S + while time.monotonic() < deadline: + try: + status, body = http("GET", url + path, timeout=10) + if status == 200 and ok(body): + return + except OSError: + pass + state = self.sh(["docker", "inspect", "-f", "{{.State.Running}}", name]) + if state.strip() != "true": + raise HarnessError( + f"{name} exited before ready: {self.logs(name)[-2000:]}" + ) + time.sleep(5) + raise HarnessError(f"{name} not ready after {READY_TIMEOUT_S} s") + + def logs(self, name: str) -> str: + cmd = ["docker", "logs", "--tail", "5000", name] + res = subprocess.run( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False + ) + return res.stdout.decode(errors="replace") + + def teardown(self, log_dir: Path) -> None: + if self.dry_run: + return + log_dir.mkdir(parents=True, exist_ok=True) + for name in self.containers: + (log_dir / f"{name}.log").write_text(self.logs(name)) + self.sh(["docker", "rm", "-f", name], check=False) + + # -- models and workers ------------------------------------------------ + + def model_dir(self, repo: str) -> str: + """The snapshot of ``repo`` (``Qwen/Qwen3-1.7B``), downloaded if missing.""" + hub = Path(HF_HOME, "hub", "models--" + repo.replace("/", "--"), "snapshots") + if not sorted(hub.glob("*")): + fetch = f"from huggingface_hub import snapshot_download; snapshot_download({repo!r})" + self.sh( + [ + "docker", + "run", + "--rm", + "--user", + self._user, + "-e", + f"HF_HOME={HF_HOME}", + "-v", + "/share_nfs:/share_nfs", + ATOM_IMAGE, + "python3", + "-c", + fetch, + ] + ) + snaps = sorted(hub.glob("*")) + if snaps: + return str(snaps[-1]) + if self.dry_run: + return str(hub / "") + raise HarnessError(f"{repo}: no snapshot under {hub} after download") + + def start_sglang_workers(self, n: int, model: str) -> list[str]: + urls = [] + for _ in range(n): + gpus, port = self.take_gpus(1), self.take_port() + cmd = ["python3", "-m", "sglang.launch_server", "--model-path", model] + cmd += ["--host", "0.0.0.0", "--port", str(port), "--tp-size", "1"] + name = self.container(f"sglang-{port}", SGLANG_IMAGE, cmd, gpus) + urls.append((name, f"http://{NODE_IP}:{port}")) + for name, url in urls: + self.wait_ready(name, url) + return [url for _, url in urls] + + @staticmethod + def atom_argv(model: str, port: int, engine_port: int, extra=()) -> list[str]: + """Arguments of ``python -m atom.entrypoints.openai_server`` for a worker.""" + return [ + "--model", + model, + "--host", + "0.0.0.0", + "--server-port", + str(port), + "--port", + str(engine_port), + "--enable-rl", + *extra, + ] + + def _start_atom(self, model: str, gpus: list[int], extra=()) -> tuple[str, str]: + port, engine_port = self.take_port(), self.take_port() + argv = self.atom_argv(model, port, engine_port, extra) + run = ( + ATOM_PRELUDE + + "exec python3 -m atom.entrypoints.openai_server " + + shlex.join(argv) + ) + flags = ["-w", str(TREE), "-e", f"PYTHONPATH={TREE}"] + name = self.container( + f"atom-{port}", ATOM_IMAGE, ["bash", "-c", run], gpus, flags + ) + return name, f"http://{NODE_IP}:{port}" + + def start_atom_workers( + self, n: int, model: str, tp: int = 1, extra=() + ) -> list[str]: + """``n`` ATOM workers on the tree's code, ``--enable-rl``, ``tp`` GPUs each.""" + tp_args = ["-tp", str(tp)] if tp > 1 else [] + started = [ + self._start_atom(model, self.take_gpus(tp), [*tp_args, *extra]) + for _ in range(n) + ] + for name, url in started: + self.wait_ready(name, url) + return [url for _, url in started] + + def start_pd_pair(self, model: str, extra=()) -> list[str]: + """P and D, one GPU each, KV over mooncake ``tcp``: ``[p_url, d_url]``.""" + started = [] + for role in ("producer", "consumer"): + kv = { + "kv_connector": "mooncake", + "kv_role": f"kv_{role}", + "proxy_ip": NODE_IP, + "handshake_port": self.take_port(), + "protocol": "tcp", + } + kv_args = ["--kv-transfer-config", json.dumps(kv)] + started.append( + self._start_atom(model, self.take_gpus(1), [*kv_args, *extra]) + ) + for name, url in started: + self.wait_ready(name, url) + return [url for _, url in started] + + def start_trainer(self, gpus: list[int], argv: list[str]) -> str: + """Run ``argv`` on ``gpus`` in the ATOM image with the tree importable; its name.""" + for g in gpus: + if g < self._next_gpu: + raise HarnessError(f"trainer GPU {g} is already a worker's") + self.refuse_busy(gpus) + self._next_gpu = max(self._next_gpu, max(gpus) + 1) + flags = ["-w", str(TREE), "-e", f"PYTHONPATH={TREE}"] + return self.container("trainer", ATOM_IMAGE, argv, gpus, flags) + + # -- ATOMesh ----------------------------------------------------------- + + def mesh_target(self) -> str: + """The tree's cargo target dir, as the gate names it.""" + tag = hashlib.md5(str(TREE).encode()).hexdigest()[:12] + return f"{GATE_DIR}/cargo-target/{tag}" + + def build_mesh(self) -> None: + if self._mesh_built: + return + home = os.path.expanduser("~") + name = f"rl-{self.issue}-mesh-build" + self.containers.append(name) + self.sh( + [ + "docker", + "run", + "--rm", + "--name", + name, + "--user", + self._user, + "-e", + f"HOME={home}", + "-v", + f"{home}:{home}", + "-v", + "/share_nfs:/share_nfs", + "-v", + f"{GATE_DIR}:{GATE_DIR}", + "-w", + f"{TREE}/atom/mesh", + "-e", + f"CARGO_HOME={home}/.cargo", + "-e", + f"RUSTUP_HOME={home}/.rustup", + "-e", + f"CARGO_TARGET_DIR={self.mesh_target()}", + "-e", + f"PATH={home}/.cargo/bin:/usr/local/bin:/usr/bin:/bin", + MESH_IMAGE, + "cargo", + "build", + "--release", + "--bin", + "atomesh", + ] + ) + self._mesh_built = True + + def start_mesh( + self, urls: list[str], backend="atom", pd=False, model_path=None + ) -> str: + """ATOMesh over ``urls`` (``[p_url, d_url]`` with ``pd``), long-rollout profile.""" + self.build_mesh() + port, prom = self.take_port(), self.take_port() + args = [ + "launch", + "--host", + "0.0.0.0", + "--port", + str(port), + "--prometheus-port", + str(prom), + "--backend", + backend, + "--policy", + "round_robin", + *LONG_ROLLOUT, + ] + if pd: + args += ["--pd-disaggregation", "--prefill", urls[0], "--decode", urls[1]] + else: + args += ["--worker-urls", *urls] + if model_path: + args += ["--model-path", model_path] + flags = [ + "--network", + "host", + "--user", + self._user, + "-v", + f"{GATE_DIR}:{GATE_DIR}", + ] + binary = f"{self.mesh_target()}/release/atomesh" + name = self.container(f"mesh-{port}", MESH_IMAGE, [binary, *args], flags=flags) + self.mesh_url = f"http://127.0.0.1:{port}" + + def listed(body) -> bool: + return isinstance(body, dict) and body.get("total") == len(urls) + + self.wait_ready(name, self.mesh_url, "/v1/rl/workers", listed) + return self.mesh_url + + def call_mesh(self, method: str, path: str, body=None): + return http(method, self.mesh_url + path, body) + + def rl_fanout(self, path: str, body, selector: str): + query = urllib.parse.urlencode({"selector": selector}) + return self.call_mesh("POST", f"/v1/rl/engine/{path}?{query}", body) + + def rl_worker_call(self, worker_id: str, path: str, body=None): + """GET without ``body``, else POST, through the per-worker proxy.""" + wid = urllib.parse.quote(worker_id, safe="") + method = "GET" if body is None else "POST" + return self.call_mesh(method, f"/v1/rl/workers/{wid}/engine/{path}", body) + + # -- outputs ----------------------------------------------------------- + + def generate(self, url: str, prompts: list[str]) -> list[dict]: + """SGLang-shaped ``/generate`` bodies, one prompt at a time, greedy.""" + out = [] + for prompt in prompts: + req = {"text": prompt, "sampling_params": SAMPLING} + status, body = http("POST", url + "/generate", req) + if status != 200: + raise HarnessError(f"/generate on {url} answered {status}: {body}") + out.append(body) + return out + + def equals_fresh(self, checkpoint: str, outputs: list[dict], launch) -> bool: + """Whether ``outputs`` (``generate`` over ``PROMPTS``) have the token ids + of a fresh server ``launch(checkpoint)`` starts and returns the URL of.""" + fresh = self.generate(launch(checkpoint), PROMPTS[: len(outputs)]) + return [o["output_ids"] for o in outputs] == [f["output_ids"] for f in fresh] + + def write_result(self, check: str, verdict: Verdict, elapsed_s: float) -> Path: + dirty = bool(_git("status", "--porcelain").strip()) + commit = _git("rev-parse", "HEAD").decode().strip() + record = {"check": check, "commit": commit, "dirty": dirty} + record |= {"elapsed_s": round(elapsed_s, 1), **asdict(verdict)} + OUT_DIR.mkdir(parents=True, exist_ok=True) + path = OUT_DIR / f"{check}.json" + path.write_text(json.dumps(record, indent=2) + "\n") + return path + + +def _exit_on_signal(signum, _frame): + sys.exit(128 + signum) # unwinds through teardown + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="RL acceptance checks on " + NODE_HOST) + ap.add_argument("check", help="module name under tools/rl/checks") + ap.add_argument( + "--dry-run", action="store_true", help="print the steps; run nothing" + ) + ap.add_argument("--tree-digest", help=argparse.SUPPRESS) + args = ap.parse_args(argv) + sys.modules.setdefault("accept", sys.modules[__name__]) + sys.path.insert(0, str(Path(__file__).resolve().parent)) + check = importlib.import_module(f"checks.{args.check}") + h = Harness(check.ISSUE, dry_run=args.dry_run) + if args.dry_run: + print("\n".join(check.plan(h))) + return 0 + if socket.gethostname() != NODE_HOST: + rerun = ["python3", "tools/rl/accept.py", args.check] + rerun += ["--tree-digest", tree_digest()] + remote = f"cd {shlex.quote(str(TREE))} && {shlex.join(rerun)}" + ssh = ["ssh", "-o", "BatchMode=yes", NODE, remote] + return subprocess.run(ssh, check=False).returncode + for sig in (signal.SIGTERM, signal.SIGHUP): + signal.signal(sig, _exit_on_signal) + started = time.monotonic() + try: + wait_for_tree(args.tree_digest) + verdict = check.run(h) + except Exception as e: # noqa: BLE001 - any failure is the check's FAIL + verdict = Verdict(False, f"{type(e).__name__}: {e}") + finally: + h.teardown(OUT_DIR / "logs" / args.check) + h.write_result(args.check, verdict, time.monotonic() - started) + print( + f"PASS {args.check}" + if verdict.passed + else f"FAIL {args.check}: {verdict.reason}" + ) + return 0 if verdict.passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/rl/checks/mesh_sglang.py b/tools/rl/checks/mesh_sglang.py new file mode 100644 index 00000000000..357b6ce5c0a --- /dev/null +++ b/tools/rl/checks/mesh_sglang.py @@ -0,0 +1,136 @@ +"""A1: ATOMesh's /v1/rl routes over two SGLang workers. + +Lists the workers, reads each one and its ``model_info`` through the +per-worker proxy, runs pause -> ``update_weights_from_disk`` -> continue as +fan-outs, reads ``model_info`` again, and probes SMG's error answers. PASS +when every route answered as SMG's protocol says and both workers report the +new ``weight_version``. +""" + +from __future__ import annotations + +import urllib.parse + +from accept import Verdict + +ISSUE = 106 +OLD, NEW = "Qwen/Qwen3-1.7B-Base", "Qwen/Qwen3-1.7B" +SELECTOR = "engine=sglang" +VERSION = "mesh-sglang-v2" +# error code: (method, path, status); `{id}` is the first listed worker's id. +PROBES = { + "selector_required": ("GET", "/v1/rl/engine/model_info", 400), + "invalid_selector": ("GET", "/v1/rl/engine/model_info?selector=%3Dsglang", 400), + "no_workers_match": ("GET", "/v1/rl/engine/model_info?selector=engine%3Dvllm", 400), + "worker_not_found": ("GET", "/v1/rl/workers/no-such-worker", 404), + "invalid_engine_path": ("GET", "/v1/rl/workers/{id}/engine/model%20info", 400), +} +CYCLE = ("pause_generation", "update_weights_from_disk", "continue_generation") + + +def _launch(h) -> str: + """Two SGLang workers on OLD behind ATOMesh; the NEW checkpoint's path.""" + h.start_mesh(h.start_sglang_workers(2, h.model_dir(OLD)), backend="sglang") + return h.model_dir(NEW) + + +def _update_body(new: str) -> dict: + return {"model_path": new, "weight_version": VERSION, "flush_cache": True} + + +def plan(h) -> list[str]: + new = _launch(h) + bodies = {"update_weights_from_disk": _update_body(new)} + cycle = [ + f"POST /v1/rl/engine/{p}?selector={SELECTOR} {bodies.get(p, {})}" for p in CYCLE + ] + probes = [f"{m} {p} -> {s} {code}" for code, (m, p, s) in PROBES.items()] + return [ + *h.steps, + "GET /v1/rl/workers; GET /v1/rl/workers/{id} for each", + "GET /v1/rl/workers/{id}/engine/model_info for each", + *cycle, + "GET /v1/rl/workers/{id}/engine/model_info for each", + *probes, + ] + + +def run(h) -> Verdict: + new = _launch(h) + obs = {"workers": h.call_mesh("GET", "/v1/rl/workers")} + listed = obs["workers"][1] + ids = ( + [w["id"] for w in listed.get("workers", [])] if isinstance(listed, dict) else [] + ) + quoted = {i: urllib.parse.quote(i, safe="") for i in ids} + obs["worker"] = {i: h.call_mesh("GET", f"/v1/rl/workers/{quoted[i]}") for i in ids} + obs["model_info_before"] = {i: h.rl_worker_call(i, "model_info") for i in ids} + bodies = {"update_weights_from_disk": _update_body(new)} + for path in CYCLE: + obs[path] = h.rl_fanout(path, bodies.get(path, {}), SELECTOR) + obs["model_info_after"] = {i: h.rl_worker_call(i, "model_info") for i in ids} + first = quoted[ids[0]] if ids else "none" + for code, (method, path, _) in PROBES.items(): + obs[code] = h.call_mesh(method, path.format(id=first)) + return judge(obs) + + +def _version(outcome) -> str | None: + """``weight_version`` of a proxied ``model_info`` (an RlCallOutcome).""" + status, body = outcome + inner = body.get("body") if isinstance(body, dict) else None + return ( + inner.get("weight_version") + if status == 200 and isinstance(inner, dict) + else None + ) + + +def _fanout_ok(answer) -> bool: + """200, both workers called, none failed, each engine answered 200.""" + status, body = answer + if status != 200 or not isinstance(body, dict): + return False + results = body.get("results", {}).values() + return ( + body.get("total") == body.get("succeeded") == 2 + and body.get("failed") == [] + and all(r.get("status") == 200 for r in results) + ) + + +def judge(obs: dict) -> Verdict: + """The verdict on ``obs``: each value an HTTP (status, body) answer, or a + ``{worker id: answer}`` map for the per-worker reads.""" + routes: dict[str, dict] = {} + + def record(route: str, ok: bool, answer) -> None: + routes[route] = {"ok": ok, "status": answer[0], "body": answer[1]} + + status, body = obs["workers"] + workers = body.get("workers", []) if isinstance(body, dict) else [] + record( + "GET /v1/rl/workers", + status == 200 + and body.get("protocol_version") == 1 + and body.get("total") == len(workers) == 2 + and all(w.get("engine") == "sglang" for w in workers), + obs["workers"], + ) + for w in workers: + answer = obs["worker"].get(w["id"], (None, None)) + record(f"GET /v1/rl/workers/{w['id']}", answer == (200, w), answer) + for wid, answer in obs["model_info_before"].items(): + got = _version(answer) + record(f"model_info {wid} before", got not in (None, VERSION), answer) + for wid, answer in obs["model_info_after"].items(): + record(f"model_info {wid} after", _version(answer) == VERSION, answer) + for path in CYCLE: + record(f"POST /v1/rl/engine/{path}", _fanout_ok(obs[path]), obs[path]) + for code, (_, _, want) in PROBES.items(): + status, body = obs[code] + error = body.get("error") if isinstance(body, dict) else None + record(f"probe {code}", status == want and error == code, obs[code]) + failed = [route for route, r in routes.items() if not r["ok"]] + reason = "; ".join(failed) + return Verdict(not failed, reason, {"routes": routes}) From 1a93edfc58387ce9af8948e2d4ecd40a9da543fb Mon Sep 17 00:00:00 2001 From: junyyang-amd Date: Tue, 17 Nov 2026 18:08:14 +0000 Subject: [PATCH 2/2] tools/rl/accept.py: mount the tree, clear an interrupted run's containers, drop a doc label Containers that run the tree's code mount it at its own path, so a tree outside /share_nfs is not silently replaced by the image's own atom. A run on the node first removes its issue's rl--* containers, which an earlier run whose ssh client went away left holding GPUs. A test pins that a probe answering the right status with the wrong error code fails. Co-Authored-By: Claude Opus 5.5 --- tests/test_rl_accept.py | 55 ++++++++++++++++++++++++++++++---- tools/rl/accept.py | 20 ++++++++++--- tools/rl/checks/mesh_sglang.py | 2 +- 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/tests/test_rl_accept.py b/tests/test_rl_accept.py index c3ec161f55f..eecd8d7cb7e 100644 --- a/tests/test_rl_accept.py +++ b/tests/test_rl_accept.py @@ -54,6 +54,19 @@ def test_atom_workers_start_as_rl_servers_on_their_own_ports(): ] +def test_containers_running_the_tree_mount_it_at_its_own_path(): + """Mounting /share_nfs alone leaves a tree elsewhere unmounted: docker then + creates the -w directory empty and the image's own atom runs.""" + h = accept.Harness(106, dry_run=True) + h.start_atom_workers(1, "/ckpt") + h.start_trainer([1], ["python3", "train.py"]) + h.build_mesh() + tree = f"{accept.TREE}:{accept.TREE}" + for step in h.steps: + argv = shlex.split(step) + assert tree in [argv[i + 1] for i, a in enumerate(argv) if a == "-v"], step + + def test_pd_pair_moves_kv_over_mooncake_tcp(): h = accept.Harness(111, dry_run=True) h.start_pd_pair("/ckpt") @@ -83,10 +96,11 @@ def refuse(argv, *args, **kwargs): assert " ".join(accept.LONG_ROLLOUT) in runs[-1] -def fake_mesh(stale=(), selector_required=True): +def fake_mesh(stale=(), no_selector="selector_required"): """A Harness whose ATOMesh answers over two SGLang workers as SMG's protocol - says, except that workers in ``stale`` ignore an update and, without - ``selector_required``, a fan-out with no selector goes to every worker.""" + says, except that workers in ``stale`` ignore an update. A fan-out with no + selector is refused with 400 and the error code ``no_selector``, or goes to + every worker when that is None.""" class FakeMesh(accept.Harness): def __init__(self, issue, dry_run=False): @@ -96,6 +110,9 @@ def __init__(self, issue, dry_run=False): def model_dir(self, repo): return "/ckpt/" + repo + def remove_leftovers(self): + pass + def start_sglang_workers(self, n, model): return [f"http://w{i}" for i in range(n)] @@ -122,8 +139,8 @@ def call_mesh(self, method, path, body=None): version = self.versions[parts[1]] return 200, {"status": 200, "body": {"weight_version": version}} selector = parse_qs(url.query).get("selector", [""])[0] - if not selector and selector_required: - return 400, {"error": "selector_required"} + if not selector and no_selector: + return 400, {"error": no_selector} if selector.startswith("="): return 400, {"error": "invalid_selector"} if selector == "engine=vllm": @@ -169,7 +186,8 @@ def test_mesh_sglang_passes_when_every_route_answers_as_smg( "harness,reason", [ (fake_mesh(stale=("w1",)), "model_info w1 after"), - (fake_mesh(selector_required=False), "probe selector_required"), + (fake_mesh(no_selector=None), "probe selector_required"), + (fake_mesh(no_selector="invalid_selector"), "probe selector_required"), ], ) def test_mesh_sglang_fails_naming_the_route( @@ -189,3 +207,28 @@ def start_sglang_workers(self, n, model): code, out = _run(monkeypatch, capsys, Busy) assert code == 1 and out == "FAIL mesh_sglang: HarnessError: GPU [0] busy" assert not json.loads(on_node.read_text())["passed"] + + +def test_a_run_first_removes_its_issues_leftover_containers( + on_node, monkeypatch, capsys +): + """An earlier run whose ssh went away never tore down; its containers hold + GPUs, so the next run removes them before taking any.""" + real_run, calls = accept.subprocess.run, [] + + def run(argv, *args, **kwargs): + if argv[0] != "docker": + return real_run(argv, *args, **kwargs) + calls.append(argv) + names = "rl-106-sglang-18200\nrl-1060-x\nrl-107-sglang-18200\n" + out = names if argv[1] == "ps" else "" + return accept.subprocess.CompletedProcess(argv, 0, out, "") + + class Leftovers(fake_mesh()): + remove_leftovers = accept.Harness.remove_leftovers + + monkeypatch.setattr(accept.subprocess, "run", run) + code, out = _run(monkeypatch, capsys, Leftovers) + assert (code, out) == (0, "PASS mesh_sglang") + assert ["docker", "rm", "-f", "rl-106-sglang-18200"] in calls + assert not [c for c in calls if c[1] == "rm" and "rl-107-sglang-18200" in c] diff --git a/tools/rl/accept.py b/tools/rl/accept.py index 84624696fbf..d6251f4a62c 100755 --- a/tools/rl/accept.py +++ b/tools/rl/accept.py @@ -66,6 +66,8 @@ "python3 -c 'import jsonschema' 2>/dev/null || pip install -q jsonschema " "|| exit 1; python3 -c 'import atom; print(\"atom from\", atom.__file__)'; " ) +# The tree mounted at its own path, wherever it lives, and run from there. +TREE_FLAGS = ["-v", f"{TREE}:{TREE}", "-w", str(TREE), "-e", f"PYTHONPATH={TREE}"] _TOPICS = ["a lighthouse", "the moon", "bread", "a river", "chess", "rain"] _TOPICS += ["a violin", "glaciers"] _FORMS = ["Write a short poem about", "Explain to a child", "List three facts about"] @@ -225,6 +227,15 @@ def logs(self, name: str) -> str: ) return res.stdout.decode(errors="replace") + def remove_leftovers(self) -> None: + """Remove ``rl--*`` containers an interrupted run left behind: + without a tty, ssh going away does not stop the run, so its teardown + never ran and its workers still hold their GPUs.""" + names = self.sh(["docker", "ps", "-a", "--format", "{{.Names}}"]) + mine = [n for n in names.split() if n.startswith(f"rl-{self.issue}-")] + if mine: + self.sh(["docker", "rm", "-f", *mine], check=False) + def teardown(self, log_dir: Path) -> None: if self.dry_run: return @@ -300,9 +311,8 @@ def _start_atom(self, model: str, gpus: list[int], extra=()) -> tuple[str, str]: + "exec python3 -m atom.entrypoints.openai_server " + shlex.join(argv) ) - flags = ["-w", str(TREE), "-e", f"PYTHONPATH={TREE}"] name = self.container( - f"atom-{port}", ATOM_IMAGE, ["bash", "-c", run], gpus, flags + f"atom-{port}", ATOM_IMAGE, ["bash", "-c", run], gpus, TREE_FLAGS ) return name, f"http://{NODE_IP}:{port}" @@ -345,8 +355,7 @@ def start_trainer(self, gpus: list[int], argv: list[str]) -> str: raise HarnessError(f"trainer GPU {g} is already a worker's") self.refuse_busy(gpus) self._next_gpu = max(self._next_gpu, max(gpus) + 1) - flags = ["-w", str(TREE), "-e", f"PYTHONPATH={TREE}"] - return self.container("trainer", ATOM_IMAGE, argv, gpus, flags) + return self.container("trainer", ATOM_IMAGE, argv, gpus, TREE_FLAGS) # -- ATOMesh ----------------------------------------------------------- @@ -378,6 +387,8 @@ def build_mesh(self) -> None: "/share_nfs:/share_nfs", "-v", f"{GATE_DIR}:{GATE_DIR}", + "-v", + f"{TREE}:{TREE}", "-w", f"{TREE}/atom/mesh", "-e", @@ -515,6 +526,7 @@ def main(argv=None) -> int: started = time.monotonic() try: wait_for_tree(args.tree_digest) + h.remove_leftovers() verdict = check.run(h) except Exception as e: # noqa: BLE001 - any failure is the check's FAIL verdict = Verdict(False, f"{type(e).__name__}: {e}") diff --git a/tools/rl/checks/mesh_sglang.py b/tools/rl/checks/mesh_sglang.py index 357b6ce5c0a..078c2112f9c 100644 --- a/tools/rl/checks/mesh_sglang.py +++ b/tools/rl/checks/mesh_sglang.py @@ -1,4 +1,4 @@ -"""A1: ATOMesh's /v1/rl routes over two SGLang workers. +"""ATOMesh's /v1/rl routes over two SGLang workers. Lists the workers, reads each one and its ``model_info`` through the per-worker proxy, runs pause -> ``update_weights_from_disk`` -> continue as