diff --git a/docs/NODE_RUNTIME.md b/docs/NODE_RUNTIME.md index fba8f595d..78aafb5df 100644 --- a/docs/NODE_RUNTIME.md +++ b/docs/NODE_RUNTIME.md @@ -278,10 +278,12 @@ One shell call reads, in this order: | ECC | the same query | the volatile uncorrectable ECC count grew since the previous check (a count that went down is the new baseline) | | NVLink fabric | the `Fabric` blocks of `nvidia-smi -q` | a GPU that has a fabric state is not `Completed/Success` (a PCIe card's `N/A` passes) | | fabric manager | `systemctl is-active nvidia-fabricmanager` | it was active and is now `inactive` or `failed` (a node without NVSwitch, never active, passes) | -| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than at the first check | +| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than at the first check or than the node's `min_ib_gbps` in the inventory, whichever is higher; without `NCCL_IB_HCA`, no port of the fabric is active, or, with `min_ib_gbps`, an active one is slower | The XIDs and the ECC count only count from the second check on. What the kernel log -holds at the first check is history: the preflight judged the node then. +holds at the first check is history: the preflight judged the node then. The nodes of +an island added at run time are judged on their first check by absolute rules instead +([OWN_CLUSTERS.md](OWN_CLUSTERS.md), "Adding an island"). A kernel log without timestamps (dmesg's default has them) is followed by its last line, how often that line ends the log, and the line before it, so lines that rotate diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 81b716d6d..bd45423b4 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -477,3 +477,193 @@ constraint. it was. `yeto cluster probe` and `yeto cluster check` always print the note. To drop the rule, delete the `fabric_group` lines. + +## Islands that lag, join or leave + +A fleet of `ssh:` trainer islands on your own machines uses the same fleet mechanisms as any +other island fleet ([FLEET_TRAINER_ISLANDS.md](FLEET_TRAINER_ISLANDS.md)). This section +covers what is specific to `ssh:` islands: how a slow or stuck island is reported, and what +is checked before an island joins. + +### An island that lags + +An island can fall behind or stop pushing while its process and its connection stay up: a +slow node, a hung collective, a trainer that waits on something. The syncer does not wait +for it. When a round's quorum deadline passes, the syncer merges the pushes that arrived and +records the silent island as absent. Later rounds do not wait for it either. Once the island +delivers again, its late push is carried into a later round with a discount, or refused when +it lags past `--rl-sync-max-base-lag`. The island then catches up to the newest merged +weights and answers rounds again. The other islands keep merging the whole time. + +The island's fleet controller reports such an island. It reads the syncer's merges, and +when none of the island's pushes was merged in `N` merge cycles it writes: + +- `island_straggler` in the launch's `fleet.jsonl`, with `missed_cycles`, `merges`, + `fragments`, `last_merged_step`, `newest_step`, `absent` and `action`; +- the same fields under `straggler` in the island's record (`fleet/trainers//state.json`, + shown by `yeto island status`). + +A merge cycle is one outer step of every fragment, so with 4 fragments and `N = 3` the +island is reported after 12 merges without it. A push the syncer refused does not count as +merged. Counting starts when the island joins the syncer: + +- A launch counts only what the syncer records after the launch started. A relaunched or + moved island's new launch never counts the merges an earlier launch of it missed. Records + stamped up to 10 minutes before the launch started still count, in case the syncer host's + clock runs behind. +- An island also counts as joined once a merge lists it `absent`: the syncer expects it. An + island that a restarted launcher adopted joined before that launcher started, and is + counted this way. +- Only the island's controller restarts the count. When the island stops running (its + controller relaunches it, or it is stopped), its count starts again once it runs again: at + its next join after a relaunch, so the time it takes to start is not counted. +- A reconnect of the same trainer, or a syncer that takes over, writes a new join to the + syncer's tape. That join keeps the count and the report: an island whose link keeps + dropping and that never delivers is still reported. + +The report is written once per stretch. `island_straggler_cleared` closes the stretch, and its +`reason` says why: a push of the island is merged again, it was `relaunched`, it was stopped +or removed (island STOP), it is no longer running, or `controller restarted`. The last one is +written by a launcher that starts, or adopts the island, while its record still holds a +report from an earlier launcher; the new launcher then judges the island again. The +record's `straggler` is set back to `null` at the same time. + +The dashboard shows both events in its event stream. While the island is reported, its +trainer card carries a `straggler` badge and its row in "Islands now" says `straggler`. + +`action` is what the controller does about it. The default is `wait`: nothing is stopped or +relaunched, because the syncer already merges without the island. A lost or unhealthy node +is handled by the island's own launch, not by this report. + +Set `N` in `fleet.trainer_argv`, so every island launch gets the same value: + +```json +"trainer_argv": ["...", "--rl-island-straggler-cycles", "3"] +``` + +`3` is the default. `0` turns the report off. The value must be a whole number of 0 or more; +`yeto launch --dry-run` refuses anything else. + +The controller reads the syncer's tape in one of two places: + +- from the syncer's own file, when the syncer runs on the same host as the controller + (`--controller head`); +- otherwise, in a fleet launched island by island (`fleet.launch: per_island`), from its + copy in the run store, `tapes/syncer//.jsonl`. The syncer launch + uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` is an + `s3://` store. Each island launch reads it every 30 s. Its first read starts at the end of + the syncer incarnation that got furthest (the newest syncer term, then the newest step). + +How late the report can be, with the store copy: + +- Normally one upload interval and one read interval after the merges it counts (about + 1 minute). +- One read takes at most 16 chunks, about 8 minutes of tape. A backlog left by a store + outage is read in about one fifteenth of the outage's length: 1 hour of outage is caught + up in about 4 minutes. +- A restarted syncer writes to a new incarnation. The launch finds it at its next full + listing, which comes every 10 reads (about 5 minutes), and reads it from its start. +- If the first read fails, every later read tries it again. Until one works nothing is + read, and the syncer's earlier records are never read. + +When the report cannot work, the launch prints `island straggler watch off` and writes +`island_straggler_unavailable` once, with the `reason`, in `fleet.jsonl`. Nothing is +reported then, and training is not affected. This happens: + +- with `--rl-island-straggler-cycles 0`; +- in a per-island fleet whose run store is not an object store, or with the upload off + (`YETO_RL_TAPE_UPLOAD_S=0`); +- in a fleet launched as one launch (`fleet.launch: synced_group`) whose syncer runs on a VM + of its own (any `--controller` other than `head`). That syncer's tape stays on its VM: + the launch does not upload it to the run store, so the controller has nothing to read. + Run the syncer on the controller's host (`--controller head`) or launch the fleet island + by island to get the report. +- when the launch reads no syncer record for 10 reads in a row (the store copy is missing + or stale). This is counted only after the first record about the launch's islands, so a + fleet whose trainers are still starting is not reported. Once records are read again, + the launch writes `island_straggler_available`. + +### Adding an island + +With `fleet.launch: per_island`, add an `ssh:` island with its own node inventory. Its +inventory lists the island's trainer nodes, in the format of `--rl-node-inventory`: + +```bash +yeto fleet island add --config run.json --name north --gpu ssh:2x8xb300@bm --usd-per-h 0 \ + --samplers north.samplers.json --inventory north.inventory.yaml --dry-run +yeto fleet island add --config run.json --name north --gpu ssh:2x8xb300@bm --usd-per-h 0 \ + --samplers north.samplers.json --inventory north.inventory.yaml +``` + +The island's launch gets `--rl-node-inventory` with the inventory's absolute path. Before +anything is written, and in the dry run too, the command checks the inventory's trainer +nodes and prints the nodes the island takes: + +| Check | Refused when | +|---|---| +| Count | Without `lease_store`: the inventory does not list as many trainer nodes as `--gpu` says. With `lease_store` it may list more, as for a launch: the island takes as many as it needs of the free, healthy ones (below). | +| In this fleet | A node is a trainer node of another `ssh:` island whose inventory has no `lease_store`, or another one: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). For an island on the same `lease_store` (`file:///x` and `/x` are one store), its launch's lease says which nodes it holds; a lease is taken by node name, so the same machine under another name in its inventory counts as its node. | +| Health | One SSH call per node runs the node health check of its device family, the check the island's launch runs while it trains. A node joining has no earlier check to compare with, so it is judged on absolute rules: a hardware Xid in the kernel log of this boot, a volatile uncorrectable ECC count above 0, NVSwitch GPUs whose `nvidia-fabricmanager` is not `active`, fewer GPUs than `cards_per_node`, an NVLink fabric not `Completed`. A multi-node island also needs its ports `Active`: those of `NCCL_IB_HCA` (the island's own `--island-env` value wins over the node's `env`), else the fabric's ports that NCCL takes. Each port runs at no less than the node's `min_ib_gbps` when the inventory sets it; else at no less than half the fastest of these ports on the island's nodes of the same fabric group. A check that does not read is refused: no answer, `nvidia-smi` or the fabric state timed out, a check still stuck on the node, an output cut off, the IB tools unread, or a kernel log the SSH user cannot read (`dmesg` restricted: add the user to the `adm` or `systemd-journal` group). With `--force` such a check is a WARNING and the node joins. A node found unhealthy is refused with `--force` too. A device family without a health check, or a node with `node_health: off`, is a note. | +| Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | +| Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (`/trainer`, or `-m/trainer` after a move) is not a refusal. A lease that does not read is refused. Without `lease_store` this is not checked, and a note says so. | + +With `lease_store`, the nodes held by another run or island are left out, and the island +must fit on the healthy rest (one fabric group in a grouped inventory, else any). When it +does not, the refusal names each node left out and why. The launch picks by leases only, +under a holder of its own (after a move, the nodes the island's earlier incarnation holds +are not its own): it takes the free nodes in the inventory's order (the free and the +earlier incarnation's ones when too few are free), and the rest when those are taken +meanwhile. So: + +- any unhealthy candidate refuses, as a pick may come to it: take that node out of the + trainer nodes (`roles`) or clear its fault; +- a node of an island on no or another `lease_store`, or the same machine under another + name, looks free to the launch: a pick that would take it refuses (`launch would take + ...`): give both islands the same `lease_store` and one name per machine, or use + inventories without shared nodes. + +Limits: + +- Two adds on one `lease_store` that run before either island launches see no lease of + the other, so both may list the same nodes. Their launches then take the leases one + after the other: the later one waits for free nodes, up to `--rl-node-lease-wait-s` + (3600 s by default), and fails after that. Add the next island once the previous one + runs, or give the islands inventories without shared nodes. +- On GB200 / GB300 NVL72 racks the NVLink fabric is managed outside the compute tray (on + the NVSwitch trays), so `nvidia-fabricmanager` is not active on the node. The health + check refuses such a node; set `node_health: off` on it and rely on `yeto preflight`. + +A refusal exits 2, names every problem, and writes nothing. No learner id is claimed: + +```text +fleet island: refused: island north's nodes cannot join: node b300-4 is leased to run other-run; node b300-5 is not healthy: GPU 5 XID 79 (a hardware Xid in the kernel log of this boot: fix the GPU and reboot the node, a new boot starts a new log, then add the island again); 0 of 2 trainer node(s) are free and healthy, 2 needed +``` + +The checks run again when the island is written, on the desired state then: another +island added since the dry run, or one that took the learner id this add checked under, +refuses the write (exit 3), naming its nodes. + +`yeto fleet island move --gpu ssh:...` runs the same checks on the nodes the island moves +onto (`--inventory` replaces the island's inventory; without it the island keeps its own), +with the same `--force`. + +Once the island is written, the trainer worker starts its launch. The island joins the +running syncer session, catches up to the newest merged weights, and then answers rounds +like the other islands. The other islands' processes keep running; they are not restarted. + +### Removing an island + +```bash +yeto fleet island remove --config run.json --name north --dry-run +yeto fleet island remove --config run.json --name north +``` + +The trainer worker writes the island's STOP. The island's controller drains it, stops the +trainer on every node (and checks that each container is gone), and records the island +`done`. Its incarnation is closed in the run's resource ledger. The syncer sees the island's +connection drop. The round it was asked for waits one island lease and then merges over the +islands left. The island's nodes are free for another island afterwards. + +In a fleet launched as one launch (`fleet.launch: synced_group`), islands cannot be added +while it trains. One island can be stopped and started again by its learner id, for example +island 1 with `yeto island stop 1 --config run.json` and `yeto island start 1 --config run.json`. diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py new file mode 100644 index 000000000..480b85549 --- /dev/null +++ b/tests/test_dashboard_island_straggler.py @@ -0,0 +1,149 @@ +"""A trainer island the syncer has merged no push of for N merge cycles (``island_straggler`` +in fleet.jsonl, ``straggler`` in its record) on the dashboard: the event stream shows the +straggler events, the trainer card carries a straggler badge until it is cleared, and the +events leave the island's lifecycle state alone.""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +from test_dashboard_diloco import SMOKE +from test_dashboard_fleet_islands import T0, fleet_reducer + +from yeto.dashboard.export import export_html +from yeto.launch import island_straggler as st + +# the topology page's smoke, also printing the event stream +LEGEND = 'legend: mk("topoLg").innerHTML' +EV_SMOKE = SMOKE.replace(LEGEND, LEGEND + ', events: mk("evs").innerHTML') +assert EV_SMOKE != SMOKE + + +def _flagged(k: int = 1, at: float = T0 + 50) -> dict: + return {"event": st.EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "action": st.WAIT, "missed_cycles": 3, "merges": 12, "fragments": 4, "newest_step": 40, + "last_merged_step": 28, "absent": True} + + +def _cleared(k: int = 1, at: float = T0 + 60) -> dict: + return {"event": st.CLEARED_EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "missed_cycles": 0, "reason": "a push of it is merged again"} + + +def _reducer(*extra: dict): + r = fleet_reducer() + for rec in extra: + r.feed(rec) + return r + + +def _smoke(tmp: Path, r) -> dict: + node = shutil.which("node") + if node is None: + pytest.skip("node not installed") + tmp.mkdir(parents=True, exist_ok=True) + page = export_html(r, tmp / "p.html", generated_at=r.max_ts) + (tmp / "smoke.js").write_text(EV_SMOKE) + res = subprocess.run([node, str(tmp / "smoke.js"), str(page), "1200"], capture_output=True, text=True, + timeout=60, check=False) + assert res.returncode == 0, res.stderr + return json.loads(res.stdout) + + +def _cards(r) -> dict: + return {c["id"]: c for c in r.overview(now=r.max_ts)["islands"]} + + +def test_a_straggler_event_marks_the_card_and_keeps_its_lifecycle_state(): + plain = _cards(_reducer()) + flagged = _cards(_reducer(_flagged())) + assert flagged["1"]["straggler"] == {"action": "wait", "missed_cycles": 3, "newest_step": 40, + "last_merged_step": 28, "at": T0 + 50} + assert flagged["0"]["straggler"] is None and plain["1"]["straggler"] is None + assert flagged["1"]["status"] == plain["1"]["status"] # not a lifecycle state + assert _cards(_reducer(_flagged(), _cleared()))["1"]["straggler"] is None + + +def test_an_unavailable_watch_is_no_mark(): + rec = {"event": st.UNAVAILABLE_EVENT, "time_unix": T0 + 50, "island": "fleet-qa-l1-modal", "island_id": 1, + "reason": "the run store is not an object store"} + cards = _cards(_reducer(_flagged(), rec)) + assert cards["1"]["straggler"]["missed_cycles"] == 3 # still flagged: unavailable says nothing of it + + +def test_the_trainer_card_draws_a_straggler_badge_until_cleared(tmp_path): + flagged = _smoke(tmp_path / "a", _reducer(_flagged())) + assert "straggler" in flagged["texts"] # the topology's trainer card + # Islands now: trainer 1's row says straggler in warn colour in place of "ok", once + assert flagged["nodes"].count('straggler') == 1 + shown = re.sub(r"<[^>]+>", "", flagged["nodes"]) # the row's visible text + assert "H100 × 2 · straggler" in shown and "ok · straggler" not in shown + assert "straggler" not in flagged["matrix"] # not in the Fragments rows + for r in (_reducer(), _reducer(_flagged(), _cleared())): + out = _smoke(tmp_path / str(len(r.fleet_records)), r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_island_record_s_mark_wins_over_the_events(tmp_path): + """A per-island fleet: the island's record says what the controller holds now.""" + from test_dashboard_trainer_islands import _state + + from yeto.dashboard import fleet_islands + + r = _reducer(_flagged()) + state = _state(tmp_path) + rec = {**state["trainers"][1]["record"], "launch_state": "running", "life_state": "running", + "straggler": None} + state["trainers"][1].update(record=rec, now=fleet_islands.island_state(rec, state["trainers"][1])) + r.load_fleet_state(state) + assert _cards(r)["1"]["island_now"]["straggler"] is None + out = _smoke(tmp_path / "rec", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_controller_s_mark_reaches_the_card_through_the_island_records(tmp_path): + """The production path: the controller writes the mark to the island's record in the run + store, ``read_fleet_state`` reads it back (``_trainer_records``) and the card shows it.""" + from test_island_straggler import _controller, _join, _step + + from yeto.dashboard import fleet_islands + from yeto.rl.engine.object_store import DirectoryObjectStore + + ctl, _ops, _store, tape, _log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() # island 1 missed one cycle: reported, its record carries the mark + + def card_of(): # a fresh read of the run store, as the dashboard's poll does + r = _reducer() # no island_straggler event: only the record can tell + assert r.load_fleet_state(fleet_islands.read_fleet_state(DirectoryObjectStore(str(tmp_path / "store")))) + return r, _cards(r)["1"] + + r, card = card_of() + mark = card["island_now"]["straggler"] + assert mark["action"] == st.WAIT and mark["missed_cycles"] == 1 and mark["last_merged_step"] == 1 + assert mark["newest_step"] == 2 and mark["absent"] is True and isinstance(mark["at"], float) + assert (_cards(r)["0"]["island_now"] or {}).get("straggler") is None # island 0: no mark + out = _smoke(tmp_path / "flagged", r) + assert out["nodes"].count('straggler') == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() # a push of it is merged again: cleared in its record + r, card = card_of() + assert card["island_now"]["straggler"] is None + out = _smoke(tmp_path / "cleared", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_event_stream_shows_the_straggler_events(tmp_path): + end = fleet_reducer().max_ts # the newest events: the stream shows the latest 15 + events = _smoke(tmp_path, _reducer(_flagged(at=end + 10), _cleared(at=end + 20)))["events"] + assert "island_straggler" in events and "missed_cycles=3" in events and "action=wait" in events + assert "island_straggler_cleared" in events and "reason=a push of it is merged again" in events + cleared = events.split("island_straggler_cleared", 1)[1].split("", 1)[0] + assert "missed_cycles" not in cleared # its reason only + assert 'title="lag"' in events and 'title="back"' in events + assert "island_straggler trainer 1 action=wait missed_cycles=3" in events diff --git a/tests/test_island_join.py b/tests/test_island_join.py new file mode 100644 index 000000000..3de9e411d --- /dev/null +++ b/tests/test_island_join.py @@ -0,0 +1,780 @@ +"""The join checks of an ssh: trainer island added (or moved) at run time +(own-cluster-fleet-stability 9.3): its inventory's trainer nodes must be free in this fleet, +healthy (node health, absolute rules: a node's first check), in one fabric group and not +leased to another run; any one of them failing refuses ``yeto fleet island add`` / ``move`` +with its reason, writing nothing. + +The checks run on the real modules: the real :class:`~yeto.hw.node_health.CudaChecker` over +the recorded tool outputs of the node health tests (``node_text``: what its script prints on +an 8 x B300 IB node), the real :class:`~yeto.hw.node_health.NullChecker`, the real +``fabric_groups`` placement and real :class:`~yeto.launch.node_lease.NodeLeases` on a directory +lease store. Only SSH is a stand-in (it answers each node with its recorded output).""" + +from __future__ import annotations + +import dataclasses +import json +import subprocess + +import pytest +from test_cluster_preflight import ibstat_text # tests/ is on sys.path +from test_fleet_island_changes import fleet_store # noqa: F401 - fixture +from test_node_health import FABRIC_OK, gpus_text, node_text, xid_line, xid_text + +from yeto.hw import node_health +from yeto.launch import island_join as ij +from yeto.launch.learner_ids import claim_key +from yeto.launch.node_inventory import load_inventory +from yeto.launch.node_lease import NodeLeases +from yeto.rl import fleet_islands + +GPU = "ssh:2x8xb300@bm" +HCA = "=mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7" +XID_79 = node_text(xid=(0, xid_text(xid_line(812.5, 5, 79)))) # in the kernel log of this boot already +ECC_5 = node_text(gpus=(0, gpus_text(ecc={2: 5}))) +FM_DOWN = node_text(fabricmanager=(3, "inactive")) # NVSwitch GPUs (fabric Completed), its fabric manager down +PCIE = node_text(fabricmanager=(3, "inactive"), fabric=(0, " Fabric\n State : N/A\n Status : N/A\n" * 8)) +SLOW = node_text(ibstat=(0, ibstat_text(rate=100))) +PORT_DOWN = node_text(ibstat=(0, ibstat_text(down=(3,)))) +NVSMI_TIMEOUT = node_text(gpus=(124, "")) +BUSY = f"{node_health.BUSY_MARK} 4242\n" +CUT = node_text()[:node_text().index("@@yeto-section ibstat")] +IB_UNREAD = node_text(ibstat=(1, "ibstat: not found"), ibv_devinfo=(1, "ibv_devinfo: not found")) + + +class Ssh: + """Answers each node's check with its recorded output (default: a healthy node).""" + + def __init__(self, out=None, unreachable=()): + self.out, self.unreachable = dict(out or {}), set(unreachable) + self.calls: list[str] = [] + self.timeouts: list[float | None] = [] + + def run(self, node, script, *, timeout=None): + self.calls.append(node.name) + self.timeouts.append(timeout) + if node.name in self.unreachable: + return subprocess.CompletedProcess([], 255, stdout="", stderr="ssh: connect to host: timed out\n") + return subprocess.CompletedProcess([], 0, stdout=self.out.get(node.name, node_text()), stderr="") + + +def _entry(name, i, *, env=None, group=None, host=None, address=None, min_ib=None, family="cuda"): + number = int(name.rsplit("-", 1)[1]) if name.rsplit("-", 1)[-1].isdigit() else 100 + i + return (f" - {{name: {name}, host: {host or f'ops@{name}.example'}, " # one machine: one address + f"address: {address or f'198.51.100.{10 + number}'}, interface: bond0, " + f"device_family: {family}, cpu_arch: x86_64, card: B300, cards_per_node: 8, hbm_gib: 288, " + "host_memory_gib: 2048, fabric: ib, runtime: docker, docker_args: [--gpus, all]" + + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") + + (f", fabric_group: {group}" if group else "") + + (f", min_ib_gbps: {min_ib}" if min_ib else "") + "}\n") + + +def _inventory(path, names, *, env=HCA, groups=None, lease_store=None, hosts=None, addresses=None, min_ib=None): + path.write_text((f"lease_store: {lease_store}\n" if lease_store else "") + "nodes:\n" + "".join( + _entry(name, i, env=env, group=(groups or {}).get(name), host=(hosts or {}).get(name), + address=(addresses or {}).get(name), min_ib=min_ib) + for i, name in enumerate(names))) + return path + + +def _nodes(tmp_path, names=("b300-4", "b300-5"), **kw): + return load_inventory(_inventory(tmp_path / "inv.yaml", names, **kw)) + + +def _check(nodes, ssh, need=2, **kw): + return ij.check(nodes, need=need, run_id="r-i2", ssh=ssh, inventory=nodes, **kw) + + +# -- health: the real checker, absolute rules ------------------------------------------------------ + +def test_healthy_nodes_join_with_one_bounded_check_each(tmp_path): + ssh = Ssh() + out = _check(_nodes(tmp_path), ssh) + assert out.ok and out.nodes == ["b300-4", "b300-5"] and out.warnings == [] + assert ssh.calls == ["b300-4", "b300-5"] + assert all(t is not None and 0 < t <= ij.HEALTH_TIMEOUT_S for t in ssh.timeouts) # never unbounded + + +@pytest.mark.parametrize(("text", "why"), [ + (XID_79, "GPU 5 XID 79" + ij.XID_HINT), + (ECC_5, "GPU 2 uncorrectable ECC 5 (volatile)"), + (FM_DOWN, "nvidia-fabricmanager inactive on an NVSwitch node"), + (node_text(gpus=(0, gpus_text(n=7))), "7 of 8 GPUs visible"), +]) +def test_a_fault_a_first_check_cannot_see_as_a_change_refuses(tmp_path, text, why): + """The checker's rules compare with the previous check; a joining node has none: a + hardware XID of this boot, a volatile uncorrectable ECC count, a stopped fabric manager + on NVSwitch GPUs refuse it.""" + out = _check(_nodes(tmp_path), Ssh({"b300-5": text})) + assert out.refusals == [f"node b300-5 is not healthy: {why}"] and out.nodes == [] + + +def test_a_pcie_node_without_nvswitch_joins_with_its_fabric_manager_inactive(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-4": PCIE, "b300-5": PCIE})).ok + + +def test_a_port_down_refuses_a_multi_node_island_only(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-4": PORT_DOWN})).refusals == [ + "node b300-4 is not healthy: mlx5_3 port DOWN"] + (one,) = _nodes(tmp_path, names=("b300-4",)) + assert _check([one], Ssh({"b300-4": PORT_DOWN}), need=1).ok + + +def test_a_slow_port_is_refused_against_the_island_s_fastest_or_min_ib_gbps(tmp_path): + out = _check(_nodes(tmp_path), Ssh({"b300-5": SLOW})) + assert len(out.refusals) == 1 and out.refusals[0].startswith( + "node b300-5 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of the island's nodes, " + "400 Gb/s)") + assert _check(_nodes(tmp_path), Ssh({"b300-4": SLOW, "b300-5": SLOW})).ok # all alike: no slower one + declared = _nodes(tmp_path, min_ib=400) # the inventory's min_ib_gbps: every node held to it + out = _check(declared, Ssh({"b300-4": SLOW, "b300-5": SLOW})) + assert [r.split(":")[0] for r in out.refusals] == ["node b300-4 is not healthy", "node b300-5 is not healthy"] + assert "mlx5_0 rate 100 < 400 Gb/s" in out.refusals[0] + + +@pytest.mark.parametrize(("text", "why"), [ + (NVSMI_TIMEOUT, f"nvidia-smi: timed out after {node_health.SECTION_TIMEOUT_S}s"), + (BUSY, "node health check skipped: the previous one still runs (a tool stuck on the node)"), + (CUT, "node health output incomplete (no ibstat, ibv_devinfo)"), +]) +def test_a_check_that_does_not_read_refuses_unless_forced(tmp_path, text, why): + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-4": text})) + assert out.refusals == [f"node b300-4: its health check did not read ({why})"] + forced = _check(nodes, Ssh({"b300-4": text}), force=True) + assert forced.ok and forced.warnings == [f"node b300-4: its health check did not read ({why}); --force: it " + "joins unchecked"] + + +def test_ib_tools_unread_refuse_a_multi_node_island_unless_forced(tmp_path): + """ok(multi) None: the GPUs pass, the job's ports did not read.""" + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-5": IB_UNREAD})) + assert out.refusals == [f"node b300-5: its health check did not read ({node_health.IB_UNREAD})"] + assert _check(nodes, Ssh({"b300-5": IB_UNREAD}), force=True).warnings + (one,) = _nodes(tmp_path, names=("b300-5",)) + assert _check([one], Ssh({"b300-5": IB_UNREAD}), need=1).ok # alone: its GPUs only + + +def test_force_never_lets_an_unhealthy_node_join(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-5": XID_79}), force=True).refusals == [ + "node b300-5 is not healthy: GPU 5 XID 79" + ij.XID_HINT] + + +def test_a_node_that_does_not_answer_is_refused(tmp_path): + out = _check(_nodes(tmp_path), Ssh(unreachable={"b300-4"})) + assert out.refusals == ["node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " + "timed out)"] + + +def test_the_real_null_checker_is_a_note_with_no_ssh_call(tmp_path): + nodes = [dataclasses.replace(n, device_family="no-such-family") for n in _nodes(tmp_path)] + assert isinstance(ij._checker_for(nodes[0]), node_health.NullChecker) + ssh = Ssh() + out = _check(nodes, ssh) + assert out.ok and ssh.calls == [] + assert out.notes[:2] == [f"node {n}: no health check for device family no-such-family" for n in ("b300-4", "b300-5")] + + +def test_a_node_with_its_health_check_off_is_noted_and_not_called(tmp_path): + first, second = _nodes(tmp_path) + ssh = Ssh({"b300-4": XID_79}) + out = _check([dataclasses.replace(first, node_health="off"), second], ssh) + assert out.ok and ssh.calls == ["b300-5"] + assert "node b300-4: node_health off in the inventory: its health is not checked" in out.notes + + +def test_the_island_s_own_nccl_ib_hca_wins_over_the_node_s(tmp_path): + """The job's HCAs are {**node.env, **island env}, as the island's launch exports them.""" + nodes = _nodes(tmp_path, env="=mlx5_0,mlx5_1") + assert _check(nodes, Ssh({"b300-4": PORT_DOWN})).ok # mlx5_3 is not the node's job port + out = _check(nodes, Ssh({"b300-4": PORT_DOWN}), env={"NCCL_IB_HCA": "=mlx5_2,mlx5_3"}) + assert out.refusals == ["node b300-4 is not healthy: mlx5_3 port DOWN"] + assert ij.island_env_of(["--island-env", "A=1", "--island-env=NCCL_IB_HCA==mlx5_3"]) == { + "A": "1", "NCCL_IB_HCA": "=mlx5_3"} + # the member's launch argv: the fleet's --island-env, then the island's own + inventory = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"], env="=mlx5_0,mlx5_1") + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(inventory), + "--island-env", "NCCL_IB_HCA==mlx5_2,mlx5_3"]} + out = ij.check_member(member, {"members": []}, fleet_argv=["--island-env", "NCCL_IB_HCA==mlx5_0"], + run_id="r-i2", ssh=Ssh({"b300-4": PORT_DOWN}), log=lambda m: None) + assert out.refusals == ["node b300-4 is not healthy: mlx5_3 port DOWN"] + + +# -- this fleet, without lease_store: exact count, overlap by machine ------------------------------- + +def test_the_wrong_count_and_a_node_of_another_island_are_refused(tmp_path): + nodes = _nodes(tmp_path) + assert _check(nodes, Ssh(), need=3).refusals == [ + "the island needs 3 trainer node(s); its inventory lists 2 ['b300-4', 'b300-5']"] + other = load_inventory(_inventory(tmp_path / "other.yaml", ["b300-5"], addresses={"b300-5": "203.0.113.5"})) + taken = {k: "sglang" for k in ij.node_keys(other[0])} # its name + assert _check(nodes, Ssh(), taken=taken).refusals == ["node b300-5 is island sglang's"] + + +@pytest.mark.parametrize(("host", "address"), [("root@B300-5.Example", "203.0.113.9"), # the same SSH target + ("b300-5-alias", "198.51.100.15")]) # the same address +def test_the_same_machine_under_another_name_or_user_is_another_island_s(tmp_path, host, address): + (theirs,) = load_inventory(_inventory(tmp_path / "theirs.yaml", ["their-node"], hosts={"their-node": host}, + addresses={"their-node": address})) + taken = {k: "south" for k in ij.node_keys(theirs)} + out = _check(_nodes(tmp_path), Ssh(), taken=taken) # b300-5: ops@b300-5.example, 198.51.100.15 + assert out.refusals == ["node b300-5 is island south's"] + + +# -- fabric groups ---------------------------------------------------------------------------------- + +def test_the_real_placement_refuses_nodes_of_two_fabric_groups(tmp_path): + def run(groups, names=("b300-4", "b300-5")): + inventory = load_inventory(_inventory(tmp_path / "g.yaml", ["b300-3", *names], groups=groups)) + nodes = [n for n in inventory if n.name in names] + return ij.check(nodes, need=2, run_id="r", ssh=Ssh(), inventory=inventory) + + split = run({"b300-3": "a", "b300-4": "a", "b300-5": "b"}) + assert len(split.refusals) == 1 and split.refusals[0].startswith("fabric: ") + assert run({"b300-3": "a", "b300-4": "b", "b300-5": "b"}).ok + plain = run(None) # no group anywhere: placed as before, with the hint as a note + assert plain.ok and any(n.startswith("fabric: ") and "fabric_group" in n for n in plain.notes) + other = run({"b300-3": "a"}) # groups in the inventory, none on the island's nodes + assert not other.ok and other.refusals[0].startswith("fabric: ") + + +# -- leases: the real NodeLeases on a directory store ---------------------------------------------- + +def _hold(store, node, run, identity="x"): + assert NodeLeases(store, run, identity=identity).acquire(node).ok + + +def test_a_node_another_run_holds_is_refused_naming_that_run(tmp_path): + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh(), lease_store=store) + assert out.refusals == ["node b300-4 is leased to run other-run", + "1 of 2 trainer node(s) are free and healthy, 2 needed"] + + +@pytest.mark.parametrize(("holder", "own"), [ + ("r-i2/trainer", True), ("r-i2-m1/trainer", True), ("r-i2-m12/trainer", True), + ("r-i2-mtest/trainer", False), ("r-i2-m/pool", False), ("r-i2-m/trainer", False), ("r-i2/pool", False), + ("r-i20/trainer", False), ("xr-i2/trainer", False), ("r-i2-m1-m2/trainer", False)]) +def test_only_the_island_s_own_launch_owns_its_lease(tmp_path, holder, own): + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], holder) + out = _check(nodes, Ssh(), lease_store=store) + assert out.ok is own, out.refusals + assert ij.own_lease(f"{holder}@x", "r-i2") is own + + +def test_a_lease_that_does_not_read_refuses(tmp_path, monkeypatch): + class Broken: + def holder(self, node): + raise OSError("store unreachable") + + monkeypatch.setattr(ij, "_node_leases", lambda uri, run: Broken()) + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store="s3://b/l")) + out = _check(nodes, Ssh(), lease_store="s3://b/l") + assert out.refusals == [f"node {n}: its lease does not read (OSError: store unreachable)" for n in ("b300-4", "b300-5")] + monkeypatch.setattr(ij, "_node_leases", lambda uri, run: (_ for _ in ()).throw(RuntimeError("no such bucket"))) + assert _check(nodes, Ssh(), lease_store="s3://b/l").refusals == ["lease store s3://b/l: RuntimeError: no such bucket"] + + +# -- a shared inventory with lease_store: the island takes need of more nodes ----------------------- + +FOUR = ("b300-0", "b300-1", "b300-2", "b300-3") + + +def _shared(tmp_path, **kw): + store = str(tmp_path / "leases") + return store, load_inventory(_inventory(tmp_path / "shared.yaml", FOUR, lease_store=store, **kw)) + + +def test_two_free_nodes_of_a_shared_inventory_make_the_island(tmp_path): + """The spec's scenario: the fleet's island north holds two nodes of the inventory; the + new island takes the other two free ones.""" + store, nodes = _shared(tmp_path) + for node in nodes[:2]: + _hold(store, node, "r-i0/trainer") + ssh = Ssh() + out = _check(nodes, ssh, lease_store=store, islands={"r-i0": "north"}) + assert out.ok and out.nodes == ["b300-2", "b300-3"] and ssh.calls == ["b300-2", "b300-3"] + assert "left out: node b300-0 is island north's (its launch holds the lease)" in out.notes + + +def test_a_shared_inventory_with_one_node_leased_and_one_unhealthy_is_refused(tmp_path): + store, nodes = _shared(tmp_path) + for node in nodes[:2]: + _hold(store, node, "r-i0/trainer") + _hold(store, nodes[2], "other-run/trainer") + out = _check(nodes, Ssh({"b300-3": XID_79}), lease_store=store, islands={"r-i0": "north"}) + assert out.refusals == ["node b300-0 is island north's (its launch holds the lease)", + "node b300-1 is island north's (its launch holds the lease)", + "node b300-2 is leased to run other-run", + "node b300-3 is not healthy: GPU 5 XID 79" + ij.XID_HINT, + "0 of 4 trainer node(s) are free and healthy, 2 needed"] + + +def test_the_group_placement_picks_from_the_free_healthy_nodes(tmp_path): + store, nodes = _shared(tmp_path, groups={"b300-0": "a", "b300-1": "a", "b300-2": "b", "b300-3": "b"}) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh(), lease_store=store) + assert out.ok and out.nodes == ["b300-2", "b300-3"] # group a has one free node + out = _check(nodes, Ssh({"b300-3": ECC_5}), lease_store=store) + assert not out.ok and out.refusals[-1].startswith("fabric: the island needs 2 healthy nodes of one fabric group") + assert "node b300-3 is not healthy: GPU 2 uncorrectable ECC 5 (volatile)" in out.refusals + + +MAY_TAKE = "the island's launch picks its nodes by their leases and may take {}; take such a node out of the " \ + "inventory's trainer nodes (roles) or clear its fault" + + +def test_an_unhealthy_node_the_launch_would_pick_by_its_leases_is_refused(tmp_path): + """The island's launch picks by leases only (in order): any unhealthy candidate refuses, + rather than pass nodes the launch does not take.""" + store, nodes = _shared(tmp_path) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh({"b300-1": XID_79}), lease_store=store) + assert out.refusals == ["node b300-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT, MAY_TAKE.format("b300-1")] + + +def test_the_launch_s_pick_after_a_move_takes_no_node_as_its_own(tmp_path): + """Scenario A. After a move the launch runs as ``r-i2-m1/trainer@``: the + nodes the earlier incarnation (``r-i2``) holds are not its own, so it takes the free ones + in the inventory's order, as the real ``pick_nodes`` does.""" + from yeto.launch.node_lease import pick_nodes + + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["c-1", "d-2", "a-3", "b-4"], lease_store=store)) + for node in nodes[2:]: + _hold(store, node, "r-i2/trainer") + launch = NodeLeases(store, "r-i2-m1/trainer", identity="new") + picked = pick_nodes(list(nodes), 2, launch, wait_s=0, sleep=lambda s: None) + assert [n.name for n in picked] == ["c-1", "d-2"] + for node in picked: + launch.release(node) + out = _check(nodes, Ssh({"c-1": XID_79}), lease_store=store) + assert out.refusals == ["node c-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT, MAY_TAKE.format("c-1")] + fine = _check(nodes, Ssh(), lease_store=store) + assert fine.ok and fine.nodes == ["c-1", "d-2"] + _hold(store, nodes[1], "other-run/trainer") # one free node: the free and the earlier incarnation's + assert _check(nodes, Ssh(), lease_store=store).nodes == ["c-1", "a-3"] + + +def test_scenario_b_the_free_nodes_after_the_earlier_incarnation_s(tmp_path): + """[a-1, b-2 (the earlier incarnation's), c-3, d-4 (free)]: the launch takes c-3, d-4; an + unhealthy c-3 refuses although a-1 and b-2 are fine.""" + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["a-1", "b-2", "c-3", "d-4"], lease_store=store)) + for node in nodes[:2]: + _hold(store, node, "r-i2/trainer") + assert _check(nodes, Ssh({"c-3": XID_79}), lease_store=store).refusals[-1] == MAY_TAKE.format("c-3") + ok = _check(nodes, Ssh(), lease_store=store) + assert ok.nodes == ["c-3", "d-4"] and not any("meanwhile" in n for n in ok.notes) + + +def test_scenario_d_an_unhealthy_candidate_no_predicted_pick_takes_still_refuses(tmp_path): + """[c-1, d-2 free; a-3, b-4 the earlier incarnation's; e-5 free and unhealthy]: the picks + take c-1, d-2, then a-3, b-4; e-5 still refuses (a pick may come to any candidate).""" + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["c-1", "d-2", "a-3", "b-4", "e-5"], lease_store=store)) + for node in nodes[2:4]: + _hold(store, node, "r-i2/trainer") + assert _check(nodes, Ssh({"e-5": XID_79}), lease_store=store).refusals[-1] == MAY_TAKE.format("e-5") + assert _check(nodes, Ssh(), lease_store=store).nodes == ["c-1", "d-2"] + + +def test_a_launch_that_would_take_another_island_s_nodes_is_refused(tmp_path): + """North (no lease_store) runs on b300-0 and b300-1 of south's shared inventory: south's + launch sees them free in its store and takes them first: refused.""" + store, nodes = _shared(tmp_path) + taken = {k: "north" for n in nodes[:2] for k in ij.node_keys(n)} + out = _check(nodes, Ssh(), lease_store=store, taken=taken) + assert out.refusals == ["launch would take b300-0, b300-1, island north's: give both islands the same " + "lease_store, or use inventories without shared nodes"] + late = {k: "north" for n in nodes[2:] for k in ij.node_keys(n)} # after the free nodes: the second pick + assert _check(nodes, Ssh(), lease_store=store, taken=late).refusals == [ + "launch would take b300-2, b300-3, island north's: give both islands the same lease_store, or use " + "inventories without shared nodes"] + three = load_inventory(_inventory(tmp_path / "three.yaml", FOUR[:3], lease_store=store)) + one = {k: "north" for k in ij.node_keys(three[2])} # no pick comes to b300-2: it may join + out = _check(three, Ssh(), lease_store=store, taken=one) + assert out.ok and out.nodes == ["b300-0", "b300-1"] and "left out: node b300-2 is island north's" in out.notes + + +def test_the_same_machine_under_another_name_on_one_lease_store_is_another_island_s(tmp_path): + store, nodes = _shared(tmp_path) + (theirs,) = load_inventory(_inventory(tmp_path / "theirs.yaml", ["north-a"], lease_store=store, + hosts={"north-a": "root@B300-0.example"}, + addresses={"north-a": "203.0.113.50"})) + aliases = {k: ("north", "north-a") for k in ij.node_keys(theirs) - {"name:north-a"}} + out = _check(nodes, Ssh(), lease_store=store, aliases=aliases) + assert out.refusals == ["launch would take b300-0, island north's (its node north-a, the same machine): give " + "the machine one name in both inventories, or use inventories without shared nodes"] + same = {k: ("north", "b300-0") for k in ij.node_keys(nodes[0]) - {"name:b300-0"}} # one name: the lease decides + assert _check(nodes, Ssh(), lease_store=store, aliases=same).ok + + +def test_lease_stores_compare_in_one_spelling(): + assert ij.store_key("file:///srv/leases/") == ij.store_key("/srv/leases") == "/srv/leases" + assert ij.store_key("s3://b/l/") == "s3://b/l" and ij.store_key(None) is None + + +def test_min_ib_gbps_without_nccl_ib_hca_holds_the_fabric_s_ports(tmp_path): + """No NCCL_IB_HCA on an ib fabric: NCCL takes the InfiniBand ports; min_ib_gbps holds each + active one (the checker's rule, the same on a running island).""" + nodes = _nodes(tmp_path, env=None, min_ib=400) + out = _check(nodes, Ssh({"b300-4": SLOW, "b300-5": SLOW})) + assert [r.split(": ", 1)[0] for r in out.refusals] == ["node b300-4 is not healthy", "node b300-5 is not healthy"] + assert "mlx5_0 rate 100 < 400 Gb/s" in out.refusals[0] + assert _check(nodes, Ssh()).ok + checker = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=400, fabric="ib") + assert "mlx5_7 rate 100 < 400 Gb/s" in checker.parse(SLOW, [], None).reasons + assert checker.parse(SLOW, [], None).ok_single is True # a single-node job: its GPUs only + + +def test_a_rate_of_exactly_half_the_fastest_passes(tmp_path): + half = node_text(ibstat=(0, ibstat_text(rate=200))) + assert _check(_nodes(tmp_path), Ssh({"b300-5": half})).ok + below = node_text(ibstat=(0, ibstat_text(rate=199))) + assert not _check(_nodes(tmp_path), Ssh({"b300-5": below})).ok + + +def test_the_relative_rate_compares_nodes_of_one_fabric_group_only(tmp_path): + store, nodes = _shared(tmp_path, groups={"b300-0": "a", "b300-1": "a", "b300-2": "b", "b300-3": "b"}) + slow_b = {"b300-2": SLOW, "b300-3": SLOW} # group b runs at 100 Gb/s, group a at 400: not compared + out = _check(nodes, Ssh(slow_b), lease_store=store) + assert out.ok and out.nodes == ["b300-0", "b300-1"] + out = _check(nodes, Ssh({"b300-3": SLOW}), lease_store=store) + assert out.refusals[0] == ("node b300-3 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of " + "the island's candidate nodes in fabric group b, 400 Gb/s)" + + "".join(f"; mlx5_{i} rate 100 < 200 Gb/s (half the fastest job port of the island's " + "candidate nodes in fabric group b, 400 Gb/s)" for i in range(1, 8))) + + +def test_one_uncorrectable_ecc_error_refuses(tmp_path): + out = _check(_nodes(tmp_path), Ssh({"b300-4": node_text(gpus=(0, gpus_text(ecc={0: 1})))})) + assert out.refusals == ["node b300-4 is not healthy: GPU 0 uncorrectable ECC 1 (volatile)"] + + +@pytest.mark.parametrize(("over", "why"), [ + ({"xid": (0, xid_text(source="none"))}, ij.XID_UNREAD), + ({"fabric": (124, "")}, "nvidia-smi -q (NVLink fabric) timed out"), + ({"fabric": (137, "")}, "nvidia-smi -q (NVLink fabric) timed out"), # killed after its timeout + ({"xid": (124, "boot=" + "0" * 8)}, ij.XID_TIMED_OUT), # timed out: not "restricted" + ({"fabricmanager": (124, "")}, "systemctl is-active nvidia-fabricmanager timed out"), +]) +def test_a_kernel_log_or_fabric_that_does_not_read_refuses_unless_forced(tmp_path, over, why): + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-4": node_text(**over)})) + assert out.refusals == [f"node b300-4: its health check did not read ({why})"] + assert _check(nodes, Ssh({"b300-4": node_text(**over)}), force=True).ok + + +def test_the_island_s_inventory_wins_over_the_fleet_s(tmp_path): + fleet_inv = _inventory(tmp_path / "fleet.yaml", ["b300-0", "b300-1"]) + island_inv = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"]) + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(island_inv)]} + ssh = Ssh() + out = ij.check_member(member, {"members": []}, fleet_argv=["--rl-node-inventory", str(fleet_inv)], + run_id="r-i2", ssh=ssh, log=lambda m: None) + assert out.ok and out.nodes == ["b300-4", "b300-5"] and ssh.calls == ["b300-4", "b300-5"] + + +def test_a_recheck_prints_only_what_the_first_check_did_not(tmp_path): + inventory = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"]) + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(inventory)]} + lines: list[str] = [] + first = ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh({"b300-4": BUSY}), + force=True, log=lines.append) + assert any("WARNING" in line for line in lines) and any("note:" in line for line in lines) + lines.clear() + ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh(), force=True, + log=lines.append, health=first.health, seen=[*first.notes, *first.warnings]) + assert lines == [] + ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh({"b300-5": BUSY}), force=True, + log=lines.append, seen=[*first.notes, *first.warnings]) + assert lines == ["fleet island: WARNING: island north: node b300-5: its health check did not read (node health " + "check skipped: the previous one still runs (a tool stuck on the node)); --force: it joins " + "unchecked"] + + +# -- yeto fleet island add / move ----------------------------------------------------------------- + +def _add(run_cli, samplers, inventory, *extra, name="north"): + return run_cli("add", "--name", name, "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(samplers), + "--inventory", str(inventory), *extra) + + +@pytest.fixture +def wired(monkeypatch): + """SSH answers healthy (``ssh.out``: per node); the launch dry run and session check pass.""" + ssh = Ssh() + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + return ssh + + +@pytest.mark.parametrize("problem", ["health", "fabric", "lease", "unread"]) +def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_store, tmp_path, # noqa: F811 + monkeypatch, capsys, problem): + _cfg, objects, store, run_cli, samplers = fleet_store + ssh = Ssh() + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + if problem == "health": + ssh.out["b300-4"] = node_text(gpus=(0, gpus_text(n=7))) + why = "node b300-4 is not healthy: 7 of 8 GPUs visible" + elif problem == "fabric": + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], groups={"b300-4": "a", "b300-5": "b"}) + why = "fabric: the island needs 2 healthy nodes of one fabric group" + elif problem == "lease": + leases = str(tmp_path / "leases") + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], lease_store=leases) + _hold(leases, load_inventory(inventory)[1], "another-run/trainer") + why = "node b300-5 is leased to run another-run" + else: + ssh.out["b300-5"] = NVSMI_TIMEOUT + why = "node b300-5: its health check did not read (nvidia-smi: timed out after" + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda *a, **kw: pytest.fail("checked before the dry run")) + for dry in ((), ("--dry-run",)): + assert _add(run_cli, samplers, inventory, *dry) == 2 + assert "refused: island north's nodes cannot join: " + why in capsys.readouterr().err + assert store.read()["generation"] == 1 and objects.read(claim_key(2)) is None + + +def test_add_with_force_takes_an_island_whose_check_does_not_read_with_a_warning(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, store, run_cli, samplers = fleet_store + wired.out["b300-5"] = BUSY + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + assert _add(run_cli, samplers, inventory, "--force") == 0 + assert "WARNING: island north: node b300-5: its health check did not read" in capsys.readouterr().err + assert store.read()["generation"] == 2 + wired.out["b300-6"] = XID_79 + south = _inventory(tmp_path / "south.yaml", ["b300-6", "b300-7"]) + assert _add(run_cli, samplers, south, "--force", name="south") == 2 # unhealthy: never forced + + +def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, wired, tmp_path, monkeypatch, capsys): # noqa: F811 + _cfg, objects, store, run_cli, samplers = fleet_store + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + dry_runs = [] + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: dry_runs.append(member)) + assert _add(run_cli, samplers, inventory) == 0 + out = capsys.readouterr() + assert "island north takes nodes b300-4, b300-5; its nodes pass the join checks" in out.out + assert "note: island north: no lease_store" in out.err + (member,) = dry_runs + assert member["argv"][-2:] == ["--rl-node-inventory", str(inventory.resolve())] and member["gpu"] == GPU + assert store.read()["generation"] == 2 and objects.read(claim_key(2)) is not None + + +def test_the_write_s_recheck_does_not_print_the_first_check_s_notes_again(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, _store, run_cli, samplers = fleet_store + wired.out["b300-5"] = BUSY + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]), "--force") == 0 + err = capsys.readouterr().err + assert err.count("note: island north: no lease_store") == 1 + assert err.count("WARNING: island north: node b300-5") == 1 + + +def test_the_dry_run_of_a_shared_inventory_prints_the_nodes_the_island_takes(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + inventory = _inventory(tmp_path / "shared.yaml", FOUR, lease_store=leases) + _hold(leases, load_inventory(inventory)[0], "r-i0/trainer") # island mixed's launch (prefix r-i0) + _hold(leases, load_inventory(inventory)[1], "other-run/trainer") + assert _add(run_cli, samplers, inventory, "--dry-run") == 0 + captured = capsys.readouterr() + assert "island north takes nodes b300-2, b300-3" in captured.out + assert "left out: node b300-0 is island mixed's (its launch holds the lease)" in captured.err + assert store.read()["generation"] == 1 + + +def test_an_inventory_path_is_kept_absolute_whatever_the_cwd(fleet_store, wired, tmp_path, monkeypatch, # noqa: F811 + capsys): + """A relative --inventory is resolved when the island is written: a later add from + another directory still reads the first island's nodes.""" + cfg, _objects, store, run_cli, samplers = fleet_store + (here := tmp_path / "a").mkdir() + (there := tmp_path / "b").mkdir() + _inventory(here / "north.yaml", ["b300-4", "b300-5"]) + _inventory(there / "south.yaml", ["b300-5", "b300-6"]) + monkeypatch.chdir(here) + assert _add(run_cli, samplers, "north.yaml") == 0 + north = next(m for m in store.read()["members"] if m.get("name") == "north") + assert ij.inventory_of(north["argv"]) == str((here / "north.yaml").resolve()) + monkeypatch.chdir(there) + other = samplers.parent / "south.samplers.json" + other.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + capsys.readouterr() + assert _add(run_cli, other, "south.yaml", name="south") == 2 + assert "node b300-5 is island north's" in capsys.readouterr().err + + +def test_two_adds_at_once_on_overlapping_inventories_one_is_refused_at_its_write(fleet_store, wired, tmp_path, # noqa: F811 + monkeypatch, capsys): + """South checks against the desired state without north; north is written meanwhile and + takes south's learner id: south's write checks again on the new state (north's nodes) and + under its new prefix (north's lease, no longer south's own), and is refused.""" + cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + north_inv = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + south_inv = _inventory(tmp_path / "south.yaml", ["b300-5", "b300-6"]) + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + from yeto.launch import learner_ids + + real = learner_ids.allocate_learner_id + meanwhile = [] + + def allocate(objects, **kw): + if kw.get("island") == "south" and not meanwhile: + meanwhile.append(_add(run_cli, samplers, north_inv)) # north's add runs between south's check and write + return real(objects, **kw) + + monkeypatch.setattr(learner_ids, "allocate_learner_id", allocate) + assert _add(run_cli, south_samplers, south_inv, name="south") == 3 and meanwhile == [0] + err = capsys.readouterr().err + assert "island south's nodes cannot join (checked again on the desired state now): node b300-5 is island north's" in err + trainers = {m["name"]: m for m in store.read()["members"] if m.get("kind") == "trainer"} + assert "south" not in trainers and trainers["north"]["learner_id"] == 2 # north took the id south checked under + + +def test_an_id_claimed_meanwhile_checks_the_leases_again_under_the_new_prefix(fleet_store, wired, tmp_path, # noqa: F811 + monkeypatch, capsys): + """South's check runs under prefix r-i2 (a lease of r-i2 is its own); north takes id 2 + meanwhile, so south is written as r-i3: that lease is north's now, and south is refused.""" + cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + shared = _inventory(tmp_path / "shared.yaml", ["b300-7", "b300-8"], lease_store=leases) + _hold(leases, load_inventory(shared)[0], "r-i2/trainer") + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + north = _inventory(tmp_path / "north.yaml", ["b300-9", "b300-10"]) + from yeto.launch import learner_ids + + real, meanwhile = learner_ids.allocate_learner_id, [] + + def allocate(objects, **kw): + if kw.get("island") == "south" and not meanwhile: + meanwhile.append(_add(run_cli, samplers, north)) + return real(objects, **kw) + + monkeypatch.setattr(learner_ids, "allocate_learner_id", allocate) + assert _add(run_cli, south_samplers, shared, name="south") == 3 and meanwhile == [0] + err = capsys.readouterr().err + assert ("island south's nodes cannot join (checked again on the desired state now): node b300-7 is island " + "north's (its launch holds the lease)") in err + assert "south" not in {m["name"] for m in store.read()["members"]} + + +@pytest.mark.parametrize("north_store", [None, "l1"]) +def test_an_island_on_another_lease_store_or_none_keeps_its_nodes(fleet_store, wired, tmp_path, capsys, # noqa: F811 + north_store): + """North's inventory has no lease_store (or another one): its nodes are not in south's + lease store, so south's shared inventory leaves them out by the inventory, not by leases.""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + north = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], + lease_store=north_store and str(tmp_path / north_store)) + assert _add(run_cli, samplers, north) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-4", "b300-5", "b300-6"], lease_store=str(tmp_path / "l2")) + capsys.readouterr() + assert _add(run_cli, south_samplers, south, name="south") == 2 + assert "node b300-4 is island north's; node b300-5 is island north's" in capsys.readouterr().err + + +def test_islands_on_one_lease_store_are_judged_by_their_leases(fleet_store, wired, tmp_path): # noqa: F811 + """North (not launched yet) holds no lease: south may list its nodes; the launches then + wait for each other's leases (docs/OWN_CLUSTERS.md: the window of two adds).""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + store = str(tmp_path / "l2") + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], lease_store=store)) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-4", "b300-5", "b300-6"], lease_store=store) + assert _add(run_cli, south_samplers, south, name="south") == 0 + + +def test_an_island_on_one_lease_store_naming_the_machines_otherwise_is_refused(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + """North and south share one lease store (written ``/x`` and ``file:///x``); north's + inventory names b300-4 and b300-5 ``n-a`` and ``n-b``: their leases do not keep south off.""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + store = str(tmp_path / "l") + north = _inventory(tmp_path / "north.yaml", ["n-a", "n-b"], lease_store=store, + hosts={"n-a": "root@b300-4.example", "n-b": "root@b300-5.example"}, + addresses={"n-a": "198.51.100.14", "n-b": "198.51.100.15"}) + assert _add(run_cli, samplers, north) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-6", "b300-7", "b300-4", "b300-5"], lease_store="file://" + store) + capsys.readouterr() + assert _add(run_cli, south_samplers, south, name="south") == 2 + err = capsys.readouterr().err + assert "launch would take b300-4, island north's (its node n-a, the same machine): give the machine one name" in err + + +def test_move_to_ssh_runs_the_same_join_checks(fleet_store, wired, tmp_path, capsys): # noqa: F811 + _cfg, _objects, store, run_cli, samplers = fleet_store + + def move(inventory, *extra): + return run_cli("move", "--name", "sglang", "--gpu", GPU, "--usd-per-h", "0", "--inventory", str(inventory), + *extra) + + three = _inventory(tmp_path / "three.yaml", ["b300-1", "b300-2", "b300-3"]) + assert move(three) == 2 and "the island needs 2 trainer node(s); its inventory lists 3" in capsys.readouterr().err + wired.out["b300-2"] = XID_79 + two = _inventory(tmp_path / "two.yaml", ["b300-1", "b300-2"]) + assert move(two) == 2 and "node b300-2 is not healthy: GPU 5 XID 79" in capsys.readouterr().err + split = _inventory(tmp_path / "split.yaml", ["b300-3", "b300-4"], groups={"b300-3": "a", "b300-4": "b"}) + assert move(split) == 2 and "fabric: the island needs 2 healthy nodes" in capsys.readouterr().err + leases = str(tmp_path / "leases") + held = _inventory(tmp_path / "held.yaml", ["b300-5", "b300-6"], lease_store=leases) + _hold(leases, load_inventory(held)[0], "other-run/trainer") + assert move(held) == 2 and "node b300-5 is leased to run other-run" in capsys.readouterr().err + assert store.read()["generation"] == 1 + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-7", "b300-8"])) == 0 + onto = _inventory(tmp_path / "onto.yaml", ["b300-8", "b300-9"]) + assert move(onto) == 2 and "node b300-8 is island north's" in capsys.readouterr().err + ok = _inventory(tmp_path / "ok.yaml", ["b300-10", "b300-11"]) + assert move(ok, "--dry-run") == 0 and "island sglang takes nodes b300-10, b300-11" in capsys.readouterr().out + assert move(ok) == 0 + sglang = next(m for m in store.read()["members"] if m.get("name") == "sglang") + assert sglang["gpu"] == GPU and ij.inventory_of(sglang["argv"]) == str(ok.resolve()) + assert ij.without_inventory(sglang["argv"]) == [a for a in sglang["argv"][:-2]] + # its own nodes (its inventory now) are not another island's: a move onto them again passes + assert move(ok) == 0 + + +def test_an_inventory_is_for_an_ssh_island_only(fleet_store, tmp_path, capsys): # noqa: F811 + _cfg, _objects, _store, run_cli, samplers = fleet_store + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + assert run_cli("add", "--name", "north", "--gpu", "modal:1x2xh100", "--usd-per-h", "8", "--samplers", + str(samplers), "--inventory", str(inventory)) == 2 + assert "--inventory is the node inventory of an ssh: island" in capsys.readouterr().err + assert run_cli("move", "--name", "sglang", "--gpu", "modal:1x2xh100", "--inventory", str(inventory)) == 2 + assert "--inventory is the node inventory of an ssh: island" in capsys.readouterr().err + + +def test_min_ib_gbps_is_a_positive_number_of_the_inventory(tmp_path): + from yeto.launch.node_inventory import InventoryError + + assert {n.min_ib_gbps for n in _nodes(tmp_path, min_ib=400)} == {400.0} + assert {n.min_ib_gbps for n in _nodes(tmp_path)} == {None} + with pytest.raises(InventoryError, match="min_ib_gbps must be a positive number"): + _nodes(tmp_path, min_ib="fast") + + +def test_join_prev_counts_every_xid_of_this_boot(tmp_path): + """The previous check a joining node lacks: a cursor of no boot (every XID of this boot is new).""" + checker = node_health.checker_for("cuda", expect_gpus=8) + assert checker.parse(XID_79, [], None).ok_single is True # the checker alone: history + assert checker.parse(XID_79, [], dict(ij.JOIN_PREV)).ok_single is False + assert FABRIC_OK in node_text() diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py new file mode 100644 index 000000000..a4f33c6b6 --- /dev/null +++ b/tests/test_island_straggler.py @@ -0,0 +1,682 @@ +"""Island stragglers (own-cluster-fleet-stability 9.1): an island none of whose pushes the +syncer merged in N merge cycles is written as ``island_straggler`` by the fleet controller, +once per stretch, and cleared once a push of it is merged again. The tracker reads the +syncer's tape (a local file or its copy in the run store); the controller asks its policy +whether to wait (default) or replace, and the other islands are not touched.""" + +from __future__ import annotations + +import json +import types + +import pytest +from test_controller import RUNNING, SYNCER, FakeOps, ImmediateThread + +from yeto.launch import island_lifecycle as lc +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.rl.engine.object_store import DirectoryObjectStore + + +def _step(step, merged, *, fragments=2, absent=()): + return {"kind": "outer_step", "step": step, "fragment": (step - 1) % fragments, + "weights": [[k, step - 1, 1.0 / len(merged)] for k in merged], + "raw_weights": [[k, step - 1, 1.0] for k in merged], "absent": list(absent)} + + +def _join(k): + return {"kind": "pool_join", "island_id": k, "generation": 0, "catch_up": False, "base_version": 0} + + +RUN2 = {0: (0, 1), 1: (0, 1)} + + +def test_an_island_merged_in_no_round_for_n_cycles_is_a_straggler_once_then_cleared(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(4): # both islands merged: nothing + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + signals = [] + for _ in range(6): # island 1 silent: 3 cycles of 2 fragments + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + signals += tracker.check(RUN2) + (signal,) = signals + assert signal.island == 1 and not signal.cleared and signal.missed_cycles == 3 and signal.merges == 6 + assert signal.fragments == 2 and signal.cycles == 3 and signal.absent and signal.newest_step == step + assert signal.last_merged_step == 4 and "3 merge cycle(s)" in signal.reason + for _ in range(4): # still silent: no second event for the same stretch + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + assert tracker.check(RUN2) == [] + step += 1 + tracker.feed(_step(step, [0, 1])) # a push of it is merged again (a late push carried in) + (cleared,) = tracker.check(RUN2) + assert cleared.island == 1 and cleared.cleared and cleared.last_merged_step == step + + +def test_one_cycle_short_is_not_a_straggler_and_a_merged_push_resets_the_count(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(3): + for _ in range(5): # 5 of the 6 merges without it, then one with it + step += 1 + tracker.feed(_step(step, [0])) + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + + +def test_counting_starts_at_the_join_of_the_launch_and_a_relaunch_starts_it_again(): + tracker = st.StragglerTracker(cycles=1) + for step in range(1, 9): # island 1 not joined yet (its launch still starts): nothing counts + tracker.feed(_step(step, [0], fragments=1)) + assert tracker.check(RUN2) == [] + tracker.feed(_join(1)) + tracker.feed(_step(9, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 1 + # relaunched while flagged (a new incarnation token): cleared, and counted from its next join + (cleared,) = tracker.check({0: (0, 1), 1: (1, 2)}) + assert cleared.cleared and cleared.reason == "relaunched" + tracker.feed(_step(10, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] + tracker.feed(_join(1)) # a re-JOIN of the same incarnation later does not restart it + tracker.feed(_step(11, [0], fragments=1)) + tracker.feed(_join(1)) + assert [s.island for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + +def test_only_the_running_islands_are_reported_and_zero_cycles_is_off(): + tracker = st.StragglerTracker(cycles=1) + for k in (0, 1): + tracker.feed(_join(k)) + tracker.feed(_step(1, [0], fragments=1)) + assert tracker.check({0: (0, 1)}) == [] # island 1 draining or recovering: not watched + (flagged,) = tracker.check(RUN2) # running again (same incarnation): reported + (closed,) = tracker.check({0: (0, 1)}) # then it stops running: its stretch is closed + assert not flagged.cleared and closed.cleared and closed.island == 1 and closed.reason == "not running" + assert tracker.check({0: (0, 1)}) == [] + off = st.StragglerTracker(cycles=0) + for k in (0, 1): + off.feed(_join(k)) + for step in range(1, 20): + off.feed(_step(step, [0], fragments=1)) + assert off.check(RUN2) == [] + + +def test_the_flag_is_a_whole_number_of_cycles(): + assert st.straggler_cycles(types.SimpleNamespace()) == 3 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=5)) == 5 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=0)) == 0 + with pytest.raises(ValueError, match="whole number >= 0"): + st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=-1)) + + +def test_the_flag_is_checked_with_the_island_pool_options(monkeypatch): + from yeto.cli import build_parser + from yeto.launch import rl_args + + base = ["launch", "--training-mode", "rl", "--model", "m", "--data", "d"] + assert build_parser().parse_args([*base, "--rl-island-straggler-cycles", "4"]).rl_island_straggler_cycles == 4 + assert build_parser().parse_args(base).rl_island_straggler_cycles is None + monkeypatch.setattr(rl_args, "rl_needs_critic", lambda args: False) + args = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0, rl_sync_preset="strict-avg", + experimental_rl_sync=False, syncer_shards=None, rl_island_straggler_cycles=-2) + with pytest.raises(ValueError, match="--rl-island-straggler-cycles must be a whole number"): + rl_args._check_island_pool(args, num_islands=2) + + +def _at(record, t): + return dict(record, time_unix=t) + + +def test_records_from_before_the_watch_started_are_not_counted(): + """A relaunched or moved island's new launch reads the syncer's history: the merges its + earlier launch missed, and its earlier join, are stamped before the watch started.""" + tracker = st.StragglerTracker(cycles=1, since=10_000.0) + tracker.feed(_at(_join(1), 9_000.0)) + for step in range(1, 9): + tracker.feed(_at(_step(step, [0], fragments=1, absent=[1]), 9_000.0 + step)) + assert tracker.check(RUN2) == [] # nothing of it counts: island 1 has not joined since + tracker.feed(_at(_join(1), 10_001.0)) + assert tracker.check(RUN2) == [] + tracker.feed(_at(_step(9, [0], fragments=1), 10_002.0)) + (signal,) = tracker.check(RUN2) + assert signal.merges == 1 and signal.last_merged_step is None + + +def test_a_syncer_clock_300_s_behind_is_still_counted(): + """The syncer host's clock may run behind the launcher's: its records of now are stamped up + to CLOCK_SKEW_S before the watch's start and still count.""" + tracker = st.StragglerTracker(cycles=1, since=10_000.0) + tracker.feed(_at(_join(1), 9_700.0)) + tracker.feed(_at(_step(1, [0], fragments=1), 9_701.0)) + assert [s.island for s in tracker.check(RUN2)] == [1] + assert st.CLOCK_SKEW_S >= 300 + + +def test_a_link_that_reconnects_keeps_the_count_and_the_mark(): + """Each reconnect of the same process is a new connection generation, and the syncer + writes a new pool_join for it: none restarts the count or clears the mark. An island that + reconnects every 2 merges and never delivers is reported once, and stays reported.""" + tracker = st.StragglerTracker(cycles=3) + signals = [] + for step in range(1, 41): + if step % 2 == 1: + tracker.feed(dict(_join(1), generation=step)) + signals += tracker.check(RUN2) + tracker.feed(_step(step, [0], fragments=1, absent=[1])) + signals += tracker.check(RUN2) + assert [(s.island, s.cleared, s.merges) for s in signals] == [(1, False, 3)] + + +def test_a_new_syncer_term_keeps_the_count_and_the_mark(): + tracker = st.StragglerTracker(cycles=2) + tracker.feed(_join(1)) + for step in (1, 2): + tracker.feed(_step(step, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert not signal.cleared + tracker.feed(dict(_join(1), syncer_epoch=4, generation=7)) # a syncer that took over + assert tracker.check(RUN2) == [] # still reported: nothing written + tracker.feed(_step(3, [1], fragments=1)) + (cleared,) = tracker.check(RUN2) + assert cleared.cleared and cleared.reason == "a push of it is merged again" + + +def test_an_island_the_syncer_lists_absent_is_counted_without_a_join(): + """A restarted launcher adopts a stuck island: its join came before this watch. The syncer + expects it (absent in its merges), so it is counted from the first such merge.""" + tracker = st.StragglerTracker(cycles=2) + for step in (1, 2): + tracker.feed(_step(step, [0], fragments=1, absent=[] if step == 1 else [1])) + assert tracker.check(RUN2) == [] # one merge listed it absent: 1 of 2 + tracker.feed(_step(3, [0], fragments=1, absent=[1])) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 2 and signal.absent + + +def test_records_of_the_earlier_incarnation_read_late_do_not_count(): + """Relaunched (it left running, then runs as a new token): merges of its earlier + incarnation read late, even ones that list it absent, start nothing; it is counted + from its next join.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] # recovering + tracker.feed(_step(1, [0], fragments=1, absent=[1])) # read late + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running as its next incarnation + tracker.feed(_step(2, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # not joined yet: starting + tracker.feed(_join(1)) + tracker.feed(_step(3, [0], fragments=1)) + assert [s.merges for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + +def test_a_join_recorded_before_the_controller_holds_the_new_incarnation_running_counts(): + """Recovering (the island left running), its new incarnation joins, and only then does + the controller hold it running (a new token): the join is the new incarnation's, so the + island is counted from its return, not left uncounted until a push of it merges.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] # island 1 recovering + tracker.feed(dict(_join(1), catch_up=True)) + assert tracker.check({0: (0, 1)}) == [] # not held running: never reported + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running again + tracker.feed(_step(1, [0], fragments=1)) + (signal,) = tracker.check({0: (0, 1), 1: (1, 2)}) + assert not signal.cleared and signal.island == 1 and signal.merges == 1 + + +def test_an_island_back_running_as_the_same_incarnation_keeps_its_place_in_the_pool(): + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] + tracker.check(RUN2) # the same token back + tracker.feed(_step(1, [0], fragments=1)) + assert [s.island for s in tracker.check(RUN2)] == [1] + again = st.StragglerTracker(cycles=2) # counted from its return: what it missed before is not + again.feed(_join(1)) + again.feed(_step(1, [0], fragments=1)) + again.check(RUN2) + again.check({0: (0, 1)}) + again.check(RUN2) + again.feed(_step(2, [0], fragments=1)) + assert again.check(RUN2) == [] + fresh = st.StragglerTracker(cycles=1) # never joined before it left: still not counted + fresh.check(RUN2) + fresh.check({0: (0, 1)}) + fresh.check(RUN2) + fresh.feed(_step(1, [0], fragments=1)) + assert fresh.check(RUN2) == [] + + +# -- the syncer's tape --------------------------------------------------------------------------- + +def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): + tape = tmp_path / "tape.jsonl" + tape.write_text(json.dumps(_join(9)) + "\n") + source = st.FileTape(tape, offset=tape.stat().st_size) # an earlier syncer job's records + assert source.read() == [] + with tape.open("a") as fh: + fh.write(json.dumps(_join(0)) + "\n" + '{"kind": "outer_st') # the syncer mid-write + assert source.read() == [_join(0)] + with tape.open("a") as fh: + fh.write('ep", "step": 1}\nnot json\n') + assert source.read() == [{"kind": "outer_step", "step": 1}] + assert st.FileTape(tmp_path / "missing.jsonl").read() == [] + + +def _chunk(objects, inc, seq, *records): + objects.write(f"tapes/syncer/{inc}/{seq:08d}.jsonl", "".join(json.dumps(r) + "\n" for r in records).encode()) + + +def test_the_store_tape_starts_at_the_tail_of_the_newest_syncer_and_reads_each_chunk_once(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + old, current = "hostb-20261126T120000Z", "hosta-20261126T130000Z" # by name the newer sorts first + _chunk(objects, old, 0, _join(1), _step(1, [0])) + _chunk(objects, current, 0, _join(1), _step(2, [0])) # the history before this watch + _chunk(objects, current, 1, _step(3, [0])) + objects.write("tapes/syncer-shard1/x/00000000.jsonl", b'{"kind": "outer_step"}\n') # not this tape + objects.write("tapes/l0-host-20261126T120000Z/00000000.jsonl", b'{"event": "rl_local_round"}\n') + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and source.polled # the tail: no history + _chunk(objects, current, 2, _step(4, [0])) + assert source.read() == [] and not source.polled # within the poll interval: no request + clock[0] = 31.0 + assert source.read() == [_step(4, [0])] + clock[0] = 62.0 + assert source.read() == [] + restarted = "hosta-20261126T140000Z" # the syncer restarted: its new tape is read from its start + _chunk(objects, current, 3, _step(5, [0])) + _chunk(objects, restarted, 0, _join(0), _step(6, [0])) + got = [] + for _ in range(st.STORE_DISCOVER_POLLS): # found by the next full listing + clock[0] += 31.0 + got += source.read() + assert got == [_step(5, [0]), _join(0), _step(6, [0])] # the old one drained, then the new one + + +def test_a_watch_started_on_a_history_does_not_count_it(tmp_path): + """The relaunch case through the store: an earlier launch's history (island 1 missing + every merge) in the newest syncer incarnation; a new watch reports nothing until island 1 + joins again, then counts from 0.""" + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _at(_join(0), 10.0), _at(_join(1), 10.0), + *(_at(_step(n, [0], fragments=1), 10.0 + n) for n in range(1, 9))) + clock = [0.0] + watch = st.StragglerWatch(st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]), cycles=2, + since=100.0, log=lambda m: None) + assert watch.poll(RUN2) == [] + _chunk(objects, inc, 1, *(_at(_step(n, [0], fragments=1), 101.0 + n) for n in range(9, 12))) + clock[0] = 31.0 + assert watch.poll(RUN2) == [] # island 1 has not joined since the watch started + _chunk(objects, inc, 2, _at(_join(1), 120.0), _at(_step(12, [0], fragments=1), 121.0)) + clock[0] = 62.0 + assert watch.poll(RUN2) == [] # 1 merge since its join + _chunk(objects, inc, 3, _at(_step(13, [0], fragments=1), 122.0)) + clock[0] = 93.0 + (signal,) = watch.poll(RUN2) + assert signal.island == 1 and signal.merges == 2 + + +def test_the_store_tape_reads_at_most_its_chunks_per_poll_and_keeps_what_it_read(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], gets_per_poll=4) + assert source.read() == [] + for seq in range(1, 11): + _chunk(objects, inc, seq, _step(seq, [0])) + got = [] + for _ in range(3): + clock[0] += 31.0 + batch = source.read() + assert len(batch) <= 4 + got += batch + assert [r["step"] for r in got] == list(range(1, 11)) + + class Flaky: # the 3rd chunk read of a poll fails once + def __init__(self, inner): + self.inner, self.reads, self.failed = inner, 0, False + + def list(self, prefix, *, start_after=""): + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + self.reads += 1 + if self.reads == 4 and not self.failed: # the tail's read is the 1st + self.failed = True + raise OSError("read timed out") + return self.inner.read(key) + + flaky = st.StoreTape(Flaky(objects), interval_s=30, clock=lambda: clock[0]) + assert flaky.read() == [] + for seq in range(11, 16): + _chunk(objects, inc, seq, _step(seq, [0])) + clock[0] += 31.0 + first = flaky.read() + assert [r["step"] for r in first] == [11, 12] and "read timed out" in flaky.error # kept, not lost + clock[0] += 31.0 + second = flaky.read() + assert [r["step"] for r in second] == [13, 14, 15] and flaky.error is None # none twice, none skipped + + +def test_a_failed_first_read_tries_the_tail_again_and_never_reads_the_history(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + for seq in range(5): + _chunk(objects, inc, seq, _step(seq + 1, [0])) # the history + + class Down: + def __init__(self, inner, fail): + self.inner, self.fail = inner, set(fail) + + def list(self, prefix, *, start_after=""): + if ("root" if prefix == "tapes/syncer/" else "inc") in self.fail: + raise OSError("list failed") + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + return self.inner.read(key) + + clock = [0.0] + for fail in ({"root"}, {"inc"}): # the incarnations' listing, then the newest one's chunks + clock[0] = 0.0 + down = Down(objects, fail) + source = st.StoreTape(down, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and "list failed" in source.error and not source.tailed + down.fail = set() + clock[0] = 31.0 + assert source.read() == [] and source.tailed # the tail now: still no history + _chunk(objects, inc, 5 + len(fail) + (fail == {"inc"}), _step(99, [0])) + clock[0] = 62.0 + assert [r["step"] for r in source.read()] == [99] + + +def test_the_newest_incarnation_is_the_furthest_syncer_not_the_newest_name(tmp_path): + """No clock: the syncer that took over (a newer term) is read even when its folder's name + sorts first and its steps are behind.""" + objects = DirectoryObjectStore(tmp_path / "store") + _chunk(objects, "z-20991231T000000Z", 0, dict(_step(50, [0]), syncer_epoch=1)) + _chunk(objects, "a-20000101T000000Z", 0, dict(_step(40, [0]), syncer_epoch=2)) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and source.queue == ["a-20000101T000000Z"] + _chunk(objects, "a-20000101T000000Z", 1, dict(_step(41, [0]), syncer_epoch=2)) + _chunk(objects, "z-20991231T000000Z", 1, dict(_step(51, [0]), syncer_epoch=1)) # the old one, late + clock[0] = 31.0 + assert [r["step"] for r in source.read()] == [41] + + +def test_a_store_poll_starts_no_request_past_its_budget(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + ticks = [0.0] + + def clock(): # every call of the poll's clock: 1 s + ticks[0] += 1.0 + return ticks[0] + + source = st.StoreTape(objects, interval_s=0, clock=clock, budget_s=4.0) + assert source.read() == [] + for seq in range(1, 20): + _chunk(objects, inc, seq, _step(seq, [0])) + before = source.requests + batch = source.read() + assert 0 < len(batch) < 16 and source.requests - before <= 4 + + +def test_a_watch_whose_tape_does_not_read_logs_once_and_goes_on(): + lines = [] + + class Broken: + label = "s3://b/runs/r/tapes/syncer/" + + def read(self): + raise OSError("store down") + + watch = st.StragglerWatch(Broken(), cycles=1, log=lines.append) + assert watch.poll(RUN2) == [] and watch.poll(RUN2) == [] + assert len(lines) == 1 and "store down" in lines[0] + + +def test_the_launcher_watches_an_island_pool_only(tmp_path): + lines = [] + pool = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0) + assert st.watch_for(types.SimpleNamespace(training_mode="rl"), objects=object(), log=lines.append) is None + off = st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), + log=lines.append) + assert isinstance(off, st.UnavailableWatch) + assert off.notices() == [(st.UNAVAILABLE_EVENT, "turned off (--rl-island-straggler-cycles 0)")] + assert off.notices() == [] and off.poll(RUN2) == [] + none = st.watch_for(pool, log=lines.append, no_source="the syncer runs on its own VM") + assert isinstance(none, st.UnavailableWatch) + assert none.notices() == [(st.UNAVAILABLE_EVENT, "the syncer runs on its own VM")] + assert "watch off: the syncer runs on its own VM" in lines[-1] + watch = st.watch_for(pool, local_tape=tmp_path / "tape.jsonl", objects=object(), log=lines.append) + assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 and watch.tracker.since > 0 + watch = st.watch_for(pool, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append) + assert isinstance(watch.source, st.StoreTape) + + +# -- the fleet controller ------------------------------------------------------------------------ + +class ScriptedTape: + label = "test tape" + + def __init__(self): + self.pending: list[dict] = [] + + def read(self): + out, self.pending = self.pending, [] + return out + + +class Recorder: + def __init__(self): + self.events = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def kinds(self, kind): + return [e for e in self.events if e[0] == kind] + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + +def _controller(tmp_path, *, policy=None, cycles=1): + ops = FakeOps() + ops.status_seq.update({SYNCER: [RUNNING], "r-l0": [RUNNING], "r-l1": [RUNNING]}) + store = lc.IslandStateStore(DirectoryObjectStore(tmp_path / "store")) + refs = {f"r-l{k}": lc.IslandRef(k, "ssh") for k in (0, 1)} + tape, log = ScriptedTape(), Recorder() + ctl = FleetController(learners={n: (f"task-{n}", 1) for n in refs}, syncer=(SYNCER, "task-syncer", 1), + sky_ops=ops, poll_interval=30, recover_timeout=600, thread_cls=ImmediateThread, + recorder=lc.FleetRecorder(store, refs), elastic=True, fleet_log=log, + straggler=st.StragglerWatch(tape, cycles=cycles, log=lambda m: None), + straggler_policy=policy) + return ctl, ops, store, tape, log + + +def test_the_controller_writes_the_straggler_once_waits_and_touches_no_other_island(tmp_path): + ctl, ops, store, tape, log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() + (event,) = [e for e in log.events if e[0] == st.EVENT] + assert event[1] == "r-l1" and event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == 1 + record = store.read(1) + assert record["straggler"]["action"] == "wait" and record["straggler"]["last_merged_step"] == 1 + assert "straggler" not in (store.read(0) or {}) + ctl._poll_stragglers() # nothing new: no second event + assert len([e for e in log.events if e[0] == st.EVENT]) == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() + assert [e[:2] for e in log.events if e[0] == st.CLEARED_EVENT] == [(st.CLEARED_EVENT, "r-l1")] + assert store.read(1)["straggler"] is None + assert ops.down_calls == [] and ops.relaunch_calls == [] # waiting stops and relaunches nothing + assert all(rec["state"] == "running" for rec in ctl.learners.values()) + + +def test_a_draining_island_is_not_reported(tmp_path): + ctl, _ops, _store, tape, log = _controller(tmp_path) + ctl.learners["r-l1"]["draining"] = True + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert not [e for e in log.events if e[0] == st.EVENT] + + +def test_the_policy_decides_and_a_replace_is_handed_to_it(tmp_path): + asked, replaced = [], [] + + class Policy: + def __call__(self, name, signal): + asked.append((name, signal.island)) + return st.REPLACE + + def replace(self, name, signal): + replaced.append(name) + + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=Policy()) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert asked == [("r-l1", 1)] and replaced == ["r-l1"] + assert store.read(1)["straggler"]["action"] == "replace" + + +def test_a_policy_that_fails_or_answers_nonsense_waits(tmp_path): + def broken(name, signal): + raise RuntimeError("no spare") + + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=broken) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + ctl, _ops, store, tape, _log = _controller(tmp_path / "b", policy=lambda name, signal: "reboot") + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + + +def test_without_a_watch_the_controller_reads_nothing(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = None + ctl._poll_stragglers() + assert log.events == [] + + +def test_a_slow_start_is_never_said_unavailable(): + """Nothing about this launch's islands read yet (its trainers still load): no notice.""" + lines, tape = [], ScriptedTape() + watch = st.StragglerWatch(tape, cycles=1, log=lines.append) + tape.pending.append(_join(5)) # another launch's island: not this one's first record + for _ in range(st.QUIET_POLLS * 3): + watch.poll(RUN2) + assert lines == [] and watch.notices() == [] + + +def test_a_tape_silent_after_its_first_record_is_said_once_then_taken_back(): + lines, tape = [], ScriptedTape() + watch = st.StragglerWatch(tape, cycles=1, log=lines.append) + tape.pending.append(_join(0)) + watch.poll(RUN2) + for _ in range(st.QUIET_POLLS * 2): + watch.poll(RUN2) + assert len(lines) == 1 and "no syncer record read from test tape in 10 reads" in lines[0] + ((kind, why),) = watch.notices() + assert kind == st.UNAVAILABLE_EVENT and "no syncer record" in why and watch.notices() == [] + tape.pending.append(_step(1, [0, 1])) + watch.poll(RUN2) + assert watch.notices() == [(st.AVAILABLE_EVENT, "syncer records read again from test tape")] + for _ in range(st.QUIET_POLLS - 1): + watch.poll(RUN2) + assert watch.notices() == [] # one read short of a new silent stretch + + +def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, monkeypatch): + from yeto import launcher + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + states = types.SimpleNamespace(objects=DirectoryObjectStore(tmp_path / "s")) + base = {"training_mode": "rl", "rl_sync_island_lease_s": 30.0, "rl_checkpoint_store": "s3://b/runs/r"} + island = types.SimpleNamespace(**base, rl_fleet_role="island") + assert isinstance(launcher._island_straggler_watch(island, states, None).source, st.StoreTape) + group = types.SimpleNamespace(**base, rl_fleet_role=None) # one launch: its syncer's tape is not uploaded + off = launcher._island_straggler_watch(group, states, None) + assert isinstance(off, st.UnavailableWatch) and "a VM of its own" in off.reason + local = types.SimpleNamespace(event_tape=str(tmp_path / "tape.jsonl"), _event_offset=5) + watch = launcher._island_straggler_watch(group, states, local) + assert isinstance(watch.source, st.FileTape) and watch.source.offset == 5 + assert launcher._island_straggler_watch(island, None, None) is None # no island records: nothing written + local_store = types.SimpleNamespace(**dict(base, rl_checkpoint_store=str(tmp_path / "d")), rl_fleet_role="island") + assert "not an object store" in launcher._island_straggler_watch(local_store, states, None).reason + monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") + assert "upload is off" in launcher._island_straggler_watch(island, states, None).reason + with pytest.raises(SystemExit, match="whole number"): + launcher._island_straggler_watch(types.SimpleNamespace(**base, rl_island_straggler_cycles=-1), states, local) + + +def test_a_flagged_island_that_stops_running_is_cleared_naming_why(tmp_path): + from yeto.launch import fleet as lf + + for setup, why in ((lambda rec: rec.update(draining=True), "stopped or removed (island STOP)"), + (lambda rec: rec.update(state=lf.RECOVERING), "relaunched"), + (lambda rec: rec.update(state=lf.DONE), "not running (done)")): + ctl, _ops, store, tape, log = _controller(tmp_path / why.split()[0]) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + setup(ctl.learners["r-l1"]) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == why + assert store.read(1)["straggler"] is None + + +def test_the_watch_s_notices_are_written_once_as_unavailable(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = st.UnavailableWatch("the run store is not an object store") + ctl._poll_stragglers() + ctl._poll_stragglers() + why = {"reason": "the run store is not an object store"} + assert [e[1:] for e in log.kinds(st.UNAVAILABLE_EVENT)] == [("r-l0", why), ("r-l1", why)] # once per island + + +def test_a_watch_read_again_writes_available(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler._notices.append((st.AVAILABLE_EVENT, "syncer records read again")) + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.AVAILABLE_EVENT)] == ["r-l0", "r-l1"] + + +def test_a_mark_an_earlier_launcher_left_is_cleared_once_and_judged_again(tmp_path): + ctl, _ops, store, tape, log = _controller(tmp_path) + store.write(1, "running", straggler={"action": "wait", "missed_cycles": 3, "merges": 3, "fragments": 1, + "newest_step": 9, "last_merged_step": 6, "at": 1.0}) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == "controller restarted" + assert cleared[2]["missed_cycles"] == 3 and store.read(1)["straggler"] is None + assert (store.read(0) or {}).get("straggler") is None and not log.kinds(st.EVENT) + tape.pending += [_join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.EVENT)] == ["r-l1"] # judged again by this watch + assert len(log.kinds(st.CLEARED_EVENT)) == 1 diff --git a/tests/test_node_health_wiring.py b/tests/test_node_health_wiring.py index 20ad66b9b..eb48a8144 100644 --- a/tests/test_node_health_wiring.py +++ b/tests/test_node_health_wiring.py @@ -825,3 +825,29 @@ def ssh(self, node, command, **kw): monkeypatch.setattr(sp.SshSamplerPoolOps, "ssh", ssh) _, _, cmds, _, probe = _cuda_start(tmp_path, monkeypatch) assert any("-m yeto.node run" in c for c in cmds) and sp.HEALTH_MARK in probe + + +def test_a_node_s_min_ib_gbps_holds_its_trainer_island_s_ports(tmp_path): + """The inventory's ``min_ib_gbps`` is the least rate of the job's ports (a running island's + check, as the join check of an added island).""" + nodes = tuple(replace(b300(i, env={"NCCL_IB_HCA": HCA}), min_ib_gbps=400.0 if i == 1 else None) + for i in range(3)) + ops = make_ops(tmp_path, HealthCluster(NAMES), clock=IslandClock(), health_every_s=60.0) + ops.add("isl", SshTrainerSpec(nodes=nodes, run_id="run1", workdir="/opt/yeto", run_script="echo island")) + watches = ops.islands["isl"].health + assert watches[1].checker.min_ib_gbps == 400.0 and watches[0].checker.min_ib_gbps is None + + +def test_a_declared_min_ib_gbps_does_not_hide_a_port_that_slowed_down(): + """The running check holds a port to max(its first-check rate, min_ib_gbps): 400 then 200 + with min_ib_gbps 100 is bad; 400 then 400 with min_ib_gbps 500 is bad too.""" + from test_cluster_preflight import ibstat_text + + low = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=100) + first = low.parse(node_text(), node_health.hcas_of(HCA), None) + slowed = low.parse(node_text(ibstat=(0, ibstat_text(rate=200))), node_health.hcas_of(HCA), first.facts) + assert slowed.ok_multi is False and "mlx5_0 rate 200 < 400 Gb/s" in slowed.reasons + high = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=500) + again = high.parse(node_text(), node_health.hcas_of(HCA), high.parse(node_text(), node_health.hcas_of(HCA), + None).facts) + assert again.ok_multi is False and "mlx5_0 rate 400 < 500 Gb/s" in again.reasons diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py new file mode 100644 index 000000000..1fb133254 --- /dev/null +++ b/tests/test_own_clusters_islands_doc.py @@ -0,0 +1,102 @@ +"""docs/OWN_CLUSTERS.md, "Islands that lag, join or leave": every command of the section +parses, the ``yeto fleet island`` ones run in the doc's order on a seeded per-island fleet +(local store; the join checks run on the real node health checker over recorded tool +outputs, the real placement and real leases on a directory store), each dry run writes +nothing, and the flags, events and refusal the section shows are the code's.""" + +from __future__ import annotations + +import re +import shlex +from pathlib import Path + +from test_fleet_island_changes import fleet_store # noqa: F401 - fixture +from test_island_join import XID_79, Ssh, _hold, _inventory + +from yeto.launch import island_join as ij +from yeto.launch import island_straggler as st +from yeto.rl import fleet_islands + +DOC = Path(__file__).resolve().parents[1] / "docs" / "OWN_CLUSTERS.md" +SECTION = "## Islands that lag, join or leave" + + +def section() -> str: + text = DOC.read_text() + start = text.index(SECTION) + end = text.find("\n## ", start + len(SECTION)) + return text[start:] if end < 0 else text[start:end] + + +def commands() -> list[list[str]]: + out = [] + for block in re.findall(r"```bash\n(.*?)```", section(), flags=re.DOTALL): + out += [shlex.split(line) for line in block.replace("\\\n", " ").splitlines() if line.strip()] + inline = re.findall(r"`(yeto island (?:stop|start) [^`]+)`", section()) + return out + [shlex.split(c) for c in inline] + + +def test_the_section_names_the_code_s_flags_and_events(): + text = section() + assert "--rl-island-straggler-cycles" in text and f"`{st.DEFAULT_CYCLES}` is the default" in text + for name in (st.EVENT, st.CLEARED_EVENT, st.UNAVAILABLE_EVENT, st.AVAILABLE_EVENT, st.WAIT, + st.SYNCER_TAPES.rstrip("/"), "controller restarted"): + assert name in text + assert f"{st.QUIET_POLLS} reads in a row" in text and f"every {st.STORE_POLL_S:g} s" in text + assert f"at most {st.STORE_GETS_PER_POLL} chunks" in text and f"every {st.STORE_DISCOVER_POLLS} reads" in text + assert f"up to {st.CLOCK_SKEW_S / 60:g} minutes before" in text + for field in st.Straggler.__dataclass_fields__: + if field not in ("island", "cleared", "cycles", "reason"): + assert f"`{field}`" in text, field + + +def test_the_section_commands_run_in_order(fleet_store, tmp_path, monkeypatch, capsys): # noqa: F811 + from yeto.cli import build_parser + + _cfg, _objects, store, run_cli, samplers = fleet_store + argvs = commands() + assert {a[1] for a in argvs} == {"fleet", "island"} + for argv in argvs: + build_parser().parse_args(argv[1:]) + ssh = Ssh() # every node answers healthy (the recorded 8 x B300 IB node) + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + inventory = _inventory(tmp_path / "north.inventory.yaml", ["b300-4", "b300-5"]) + for argv in (a for a in argvs if a[:3] == ["yeto", "fleet", "island"]): + rest = [str(samplers) if a == "north.samplers.json" else str(inventory) if a == "north.inventory.yaml" + else a for a in argv[3:]] + config = rest.index("--config") + del rest[config:config + 2] + before = store.read()["generation"] + assert run_cli(*rest) == 0, (argv, capsys.readouterr().err) + out = capsys.readouterr().out + assert store.read()["generation"] == before + (0 if "--dry-run" in argv else 1) + if argv[3] == "add": + assert "nodes pass the join checks" in out + + +def test_the_refusal_the_section_shows_is_the_command_s(tmp_path): + """The real checker reads b300-5's recorded output with an Xid 79 of this boot, and the + real leases show b300-4 held by another run.""" + from yeto.launch.node_inventory import load_inventory + + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], "other-run/trainer") + out = ij.check(nodes, need=2, run_id="r-i2", lease_store=store, ssh=Ssh({"b300-5": XID_79}), + inventory=nodes) + line = "fleet island: refused: island north's nodes cannot join: " + "; ".join(out.refusals) + assert line in section() + + +def test_the_section_states_the_join_rules_of_the_code(): + text = section() + assert "half the fastest" in text and ij.RATE_FRACTION == 0.5 + from yeto.launch.ssh_trainer_island import DEFAULT_NODE_LEASE_WAIT_S + + assert f"({DEFAULT_NODE_LEASE_WAIT_S:.0f} s by default)" in text + for word in ("`min_ib_gbps`", "`--force`", "`--island-env`", "`-m/trainer`", "exit 3", + "yeto fleet island move --gpu ssh:", "`adm` or `systemd-journal`", "NVL72", "same fabric group", + "`--rl-node-lease-wait-s`"): + assert word in text, word diff --git a/tests/test_ssh_island_fleet_e2e.py b/tests/test_ssh_island_fleet_e2e.py new file mode 100644 index 000000000..f00ba8d8d --- /dev/null +++ b/tests/test_ssh_island_fleet_e2e.py @@ -0,0 +1,633 @@ +"""SSH trainer islands that join, leave and lag a training fleet, end to end +(own-cluster-fleet-stability 9.1 and 9.2): the real Rust syncer, the trainer worker +reconciling the desired state on a local store, and for each island launch the launcher's +own fleet controller over the resident ``ssh:`` island ops (``yeto.launch.ssh_resident``) on +a fake SSH cluster. Rank 0 of each island is its trainer: its start on the fake nodes +connects a syncer client under the island's learner id, its kill drops the connection. No +cloud, no Ray, no GPU. + +Two islands (``ssh:2x8xb300@bm``, two nodes each) train. Then, one case each: + +* **add**: ``yeto fleet island add`` (its functions) writes a third island into the desired + state; the worker starts its launch on two more nodes, the island catches up to the newest + outer weights and its pushes are merged from then on. +* **remove**: ``remove`` takes island 1 out; the worker writes its island STOP, its + controller drains it, releases its nodes (the kill on each node), and the rounds merge over + island 0 alone. +* **stuck**: island 1's trainer stops pushing while it stays connected (heartbeats). The + syncer merges island 0 at the quorum deadline and excuses island 1; island 1's controller + writes ``island_straggler`` (action ``wait``) once three merge cycles went by without a push + of it, nothing is stopped or relaunched, and once it pushes again its controller writes + ``island_straggler_cleared``. + +Each case checks that the other islands' processes never restarted (one start per node, no +kill before the end, one launch), that the merged steps run 1..N without a gap or a repeat, +that no push is merged twice, and that the resource ledger holds each SSH incarnation once. + +A fourth test runs the stuck case over the per-island wiring: each launch's watch is the +launcher's own for its argv and reads the syncer's tape from the run store, uploaded in +chunks, past an earlier syncer's history; island 1 is relaunched while it is reported. +""" + +from __future__ import annotations + +import json +import threading +import time +from collections import Counter + +import pytest +from test_fleet_island_launches import example_doc +from test_fleet_trainer_worker import FakeLaunches +from test_rl_full_parameter_async import ( + _f32, + _initial, + _start_async_syncer, + _wait, + needs_cargo, + syncer_binary, # noqa: F401 - fixture +) +from test_rl_full_parameter_dynamic_members import ( + LAUNCHED, + MAX_LEARNERS, + POOL, + P, + _client, + _delta, + _outer_steps, +) +from test_rl_ssh_resident import FakeCluster, b300 + +from yeto.cost.ledger import ResourceLedger +from yeto.hw import card_tools +from yeto.launch import island_lifecycle as lifecycle +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.launch.learner_ids import allocate_learner_id +from yeto.launch.pool import desired as dz +from yeto.launch.ssh_resident import SshIslandOps +from yeto.launch.ssh_trainer_island import SshTrainerSpec +from yeto.launch.ssh_trainer_ledger import KIND as SSH_TRAINER +from yeto.modal_runner import RoutingOps +from yeto.rl import fleet, fleet_islands, island_launches, trainer_worker, up +from yeto.rl.engine.object_store import DirectoryObjectStore + +GPU = "ssh:2x8xb300@bm" +NODES = {k: (b300(2 * k), b300(2 * k + 1)) for k in range(MAX_LEARNERS)} # island k on nodes 2k, 2k+1 +CYCLES = 3 +# the stuck case: a short soft deadline, so a round that waits for the silent island merges +# island 0's push after 2 s (the quorum deadline of an island pool, #865) +STUCK_POOL = tuple({"30": "2"}.get(a, a) for a in POOL) + + +@pytest.fixture(autouse=True) +def _ssh_nodes(monkeypatch, tmp_path): + monkeypatch.setattr(card_tools, "check_cards", lambda family, text, **kw: []) + monkeypatch.setenv("YETO_RESOURCE_LEDGER", str(tmp_path / "ledger.jsonl")) + monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "ssh-island-fleet-test-key") + + +class TrainerCluster(FakeCluster): + """The fake nodes of every island; rank 0's start and kill are its trainer's.""" + + def __init__(self) -> None: + super().__init__([n.name for nodes in NODES.values() for n in nodes]) + self.rank0 = {nodes[0].name: k for k, nodes in NODES.items()} + self.trainer_starts: list[int] = [] + self.trainer_kills: list[int] = [] + self.trainer_events: list[tuple[str, int]] = [] # both, in order (a relaunch: kill, then start) + self.guard = threading.Lock() + + def start(self, node, script): + stream = super().start(node, script) + if "setsid bash -c" in script and node.name in self.rank0: + with self.guard: + self.trainer_starts.append(self.rank0[node.name]) + self.trainer_events.append(("start", self.rank0[node.name])) + return stream + + def run(self, node, script, *, timeout=300.0): + out = super().run(node, script, timeout=timeout) + if "kill -TERM" in script and node.name in self.rank0: + with self.guard: + self.trainer_kills.append(self.rank0[node.name]) + self.trainer_events.append(("kill", self.rank0[node.name])) + return out + + def finish(self, k: int) -> None: + """Island k's trainer ended its run: every rank of its newest incarnation exits 0 (rank 0 last).""" + for node in reversed(NODES[k]): + runs = self.runs[node.name] + if runs and runs[max(runs)].get("state") == "running": + self.exit(node.name, max(runs), 0) + + +class FastClock: + """The island controller's sky side: fake time, 30 s per poll in 10 ms.""" + + def __init__(self) -> None: + self.t = 0.0 + + def now(self): + return self.t + + def sleep(self, seconds): + time.sleep(0.01) + self.t += seconds + + +class FleetLog: + def __init__(self) -> None: + self.events: list[tuple[str, str, dict]] = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + def kinds(self, kind): + return [e for e in list(self.events) if e[0] == kind] + + +class _SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + def join(self, timeout=None): + pass + + +class SshIslandLaunches(FakeLaunches): + """Each island launch is what ``yeto launch --gpu ssh:...`` runs for one island of a + fleet: the resident ssh: island ops on its inventory nodes and the fleet controller + supervising it (its island STOP, its record, the straggler watch), on a thread.""" + + def __init__(self, tmp_path, cluster: TrainerCluster, objects, tape, watch=None) -> None: + super().__init__() + self.tmp_path, self.cluster, self.objects, self.tape = tmp_path, cluster, objects, tape + # the straggler watch of a launch (its argv, its island records); the syncer's tape file by default + self.watch = watch or (lambda argv, states: st.StragglerWatch(st.FileTape(tape), cycles=CYCLES, + log=lambda m: None)) + self.controllers: dict[int, FleetController] = {} + self.logs: dict[int, FleetLog] = {} + self.errors: list[BaseException] = [] + + def start(self, prefix: str, argv: list[str]) -> int: + pid = super().start(prefix, argv) + k = int(argv[argv.index("--rl-fleet-learner-id") + 1]) + assert argv[argv.index("--gpu") + 1] == GPU + name = f"{prefix}-trainer" + ops = SshIslandOps(run_id=prefix, journal_dir=self.tmp_path / "runs" / prefix / "ssh-islands", + events_dir=self.tmp_path / "events" / prefix, ops=self.cluster, log=lambda m: None) + spec = SshTrainerSpec(nodes=NODES[k], run_id=prefix, workdir="/opt/yeto", run_script="echo island", env={}) + ops.add(name, spec) + job = ops.start(name) + log = self.logs[k] = FleetLog() + states = lifecycle.IslandStateStore(self.objects, log=lambda m: None) + recorder = lifecycle.FleetRecorder(states, {name: lifecycle.IslandRef(k, "ssh")}) + ctl = self.controllers[k] = FleetController( + learners={name: (spec, job)}, syncer=None, sky_ops=RoutingOps(FastClock(), None, ssh_ops=ops), + poll_interval=30.0, recover_timeout=600.0, thread_cls=_SyncThread, recorder=recorder, elastic=True, + deterministic_stop=True, fleet_log=log, + straggler=self.watch(argv, states)) + + def supervise(): + code = 0 + try: + ctl.run() + except BaseException as error: # noqa: BLE001 - reported by the test + self.errors.append(error) + code = 1 + self.end(prefix, code) + + threading.Thread(target=supervise, daemon=True).start() + return pid + + +def _config(tmp_path): + doc = example_doc(tmp_path, max_islands=MAX_LEARNERS) + for island in doc["islands"]: + island["trainer"].update(gpu=GPU, usd_per_h=0.0) # own machines + path = tmp_path / "run.json" + path.write_text(json.dumps(doc)) + return up.load_config(str(path)) + + +@needs_cargo +@pytest.mark.parametrize("case", ["add", "remove", "stuck"]) +def test_ssh_islands_join_leave_and_lag_without_touching_the_other_islands(syncer_binary, tmp_path, # noqa: F811 + case): + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + members = island_launches.trainer_members(cfg, plan) + store.apply({"members": [*members, *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, + expect=0) + total_steps, change_at = 12, 3 + process, port, profile_hash = _start_async_syncer( + syncer_binary, tmp_path, *(STUCK_POOL if case == "stuck" else POOL), total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + started = Counter() + gone: list[int] = [] + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(MAX_LEARNERS)} + seen: dict[int, set] = {k: set() for k in range(MAX_LEARNERS)} + held: dict[int, list] = {} + state = {"changed": False, "stuck": False, "flagged": False, "cleared": False, "joined_at": None} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + starts, kills = list(cluster.trainer_starts), list(cluster.trainer_kills) + for k in starts[sum(started.values()):]: + started[k] += 1 + client = _client(k, port, profile_hash) + client.start() + clients[k] = client + if k >= LAUNCHED: + catching[k] = {} + for k in kills: + if k in clients and k not in gone: # its machines torn down: the connection just drops + clients.pop(k).close() + gone.append(k) + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: # a joiner applies its catch-up before it answers a PULL + caught = catching[k] + for update in client.drain_updates(): + caught.setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(caught) < P: + return + versions[k] = [caught[fid] for fid in range(P)] + state["joined_at"] = list(versions[k]) # the outer versions its catch-up brought + del catching[k] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if case == "stuck" and k == 1 and state["stuck"]: + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def change(): + if case == "add": + k = allocate_learner_id(objects, launched=LAUNCHED, max_learners=MAX_LEARNERS, island="north") + entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") + member, pools = fleet_islands.compile_island(cfg, plan, k=k, name="north", gpu=GPU, usd_per_h=0.0, + samplers=[entry]) + store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + elif case == "remove": + store.update(lambda d: fleet_islands.remove(d, "sglang"), note="remove island 1") + else: + state["stuck"] = True + state["changed"] = True + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: # every connected island renews its lease + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(catching) or list(clients): + drain(k) + if catching: + return False # a joiner catches up before the fleet moves on + if not state["changed"] and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + change() + if case == "stuck" and state["stuck"] and launches.logs[1].kinds(st.EVENT): + state["stuck"], state["flagged"] = False, True # reported: it pushes again + if case == "stuck" and state["flagged"] and launches.logs[1].kinds(st.CLEARED_EVENT): + state["cleared"] = True + done = all(c.finalizing.is_set() for c in clients.values()) + if case == "add": + return done and 2 in clients and state["joined_at"] is not None + if case == "remove": + return done and 1 in gone + return done and state["cleared"] + + finals = {} + try: + worker.step() # islands 0 and 1 start on their nodes + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, f"the fleet never finalized ({case})", timeout=240) + for k, client in clients.items(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + finals[k] = manifest + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) # the trainers end their run: every launch ends by its trainer + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in worker_members(store, case)), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the other islands were never touched: one start per node, one launch, no kill before the end. + # Limit: these count the start / kill scripts the control plane sent to the fake nodes (and the + # worker's launches), not OS processes; they prove yeto restarted nothing, not that nothing on + # a real node could restart a rank by itself. + others = {"add": [0, 1], "remove": [0], "stuck": [0, 1]}[case] + for k in others: + assert started[k] == 1 and launches.started(f"r-i{k}") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[k]] == [1, 1] + kills_before_end = [k for k in cluster.trainer_kills if k in gone] + assert kills_before_end == ([1] if case == "remove" else []) + if case == "add": + assert started[2] == 1 and launches.started("r-i2") == 1 + if case == "remove": + assert all(sum(1 for c in cluster.calls if c[:2] == ("kill", n.name)) >= 1 for n in NODES[1]) + worker.step() + assert worker.load(1)["state"] == trainer_worker.REMOVED + + # -- the merges: steps 1..N without a gap or a repeat, no push merged twice. + # Limit: a push is keyed by (island, the step it was pushed for); a delta carried into a later + # round keeps its own step, so this catches a double merge, not a wrong carry-over discount. + steps = _outer_steps(tape.read_text()) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + for record in steps: + assert abs(sum(float(e[2]) for e in record["weights"]) - 1.0) < 1e-9 + contributors = {int(e[0]) for r in steps for e in r["raw_weights"]} + assert contributors == ({0, 1, 2} if case == "add" else {0, 1}) + if case == "add": # the joiner caught up to the merged weights of the add's time, then merged + first = min(r["step"] for r in steps if 2 in [int(e[0]) for e in r["raw_weights"]]) + assert min(state["joined_at"]) >= change_at and first > max(state["joined_at"]) + if case == "remove": + leave = next(r for r in _records(tape) if r.get("kind") == "pool_leave" and int(r["island_id"]) == 1) + # Limit: by wall time, skipping one cycle of rounds per fragment pair (2 x P): the rounds open + # at the leave may still merge a push island 1 sent before it; this does not pin the round + # its last push merged in, only that island 0 merges alone from then on. + after = [r for r in steps if r.get("time_unix", 0) > leave.get("time_unix", 0)][2 * P:] + assert after and all([int(e[0]) for e in r["raw_weights"]] == [0] for r in after) + + # -- the straggler: written once by island 1's controller, waiting; nobody else reported + if case == "stuck": + (event,) = launches.logs[1].kinds(st.EVENT) + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert event[2]["absent"] is True + assert len(launches.logs[1].kinds(st.CLEARED_EVENT)) == 1 + assert states.read(1)["straggler"] is None # cleared in its record too + absent = [r for r in steps if r["absent"] == [1]] + # merged at the quorum deadline without it. Limit: "any", because which of the rounds without + # island 1 waited for the deadline depends on when its PULL was answered before it went silent + assert any(r["timed_out"] for r in absent) + assert launches.controllers[1].learners["r-i1-trainer"]["relaunches"] == 0 + for k, log in launches.logs.items(): + if case != "stuck" or k != 1: + assert not log.kinds(st.EVENT), (k, log.kinds(st.EVENT)) + + # -- the ledger: each ssh incarnation created once, released at most once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + released = Counter(r["id"] for r in rows if r["op"] == "release") + islands = {"add": 3, "remove": 2, "stuck": 2}[case] + assert sorted(created) == sorted(f"r-i{k}/r-i{k}-trainer-i0" for k in range(islands)) + assert set(created.values()) == {1} and all(n == 1 for n in released.values()) + + +def _launch_args(argv): + """The args ``yeto launch`` parses from an island launch's argv.""" + from yeto.cli import build_parser + + return build_parser().parse_args(["launch", *argv]) + + +@needs_cargo +def test_a_stuck_island_relaunched_mid_run_is_watched_over_the_run_store(syncer_binary, tmp_path, # noqa: F811 + monkeypatch): + """The stuck case over the per-island wiring: each island launch's watch is the launcher's + own (``launcher._island_straggler_watch`` of its parsed argv and its island records), so it + reads the syncer's tape from the run store (a ``DirectoryObjectStore`` here), where the + syncer launch's uploaders copy it chunk by chunk (``tapes/syncer//``). The + store also holds an earlier syncer's history in which island 1 missed 40 merges: it is + never counted. Island 1 stops pushing and is reported once; then one of its ranks fails, + its controller relaunches it (cleared: relaunched); the new incarnation joins again + (catch-up) and stays silent: it is reported again only after N merge cycles counted from + that join; then it pushes and the mark is cleared. Island 0 is never touched.""" + from yeto import launcher + from yeto.rl.engine.tape_upload import syncer_incarnation, syncer_uploaders + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + store.apply({"members": [*island_launches.trainer_members(cfg, plan), + *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, expect=0) + old = time.time() - 3600 # an earlier syncer of the run: island 1 missing from its last 40 merges + history = [{"kind": "pool_join", "island_id": k, "generation": 0, "syncer_epoch": 0, "time_unix": old} + for k in (0, 1)] + history += [{"kind": "outer_step", "step": n, "fragment": (n - 1) % P, "weights": [[0, n - 1, 1.0]], + "raw_weights": [[0, n - 1, 1.0]], "absent": [1], "time_unix": old + n} for n in range(1, 41)] + objects.write(f"{st.SYNCER_TAPES}oldhost-20200101T000000Z/00000000.jsonl", + "".join(json.dumps(r) + "\n" for r in history).encode()) + total_steps, change_at = 30, 3 + process, port, profile_hash = _start_async_syncer(syncer_binary, tmp_path, *STUCK_POOL, total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + uploaders = syncer_uploaders(objects, tape, incarnation=syncer_incarnation(), interval_s=0.3, from_end=False, + log=lambda m: None) + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + watches = {} + + def watch(argv, island_states): + w = launcher._island_straggler_watch(_launch_args(argv), island_states, None) + # a store read every 0.5 s, not every 30 s: QUIET_POLLS reads (5 s) stay longer than the + # 2 s quorum deadline between merges, as 10 x 30 s does against a real run's merges + w.source.interval_s = 0.5 + watches[int(argv[argv.index("--rl-fleet-learner-id") + 1])] = w + return w + + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape, watch=watch) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(LAUNCHED)} + seen: dict[int, set] = {k: set() for k in range(LAUNCHED)} + held: dict[int, list] = {} + phase = {"name": "train", "events": 0} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + events = list(cluster.trainer_events) + for what, k in events[phase["events"]:]: + phase["events"] += 1 + if what == "kill" and k in clients: # its incarnation torn down: the connection drops + clients.pop(k).close() + elif what == "start": + if k in clients: + clients.pop(k).close() + clients[k] = _client(k, port, profile_hash) + clients[k].start() + if phase["name"] != "train": # a relaunched trainer catches up before it answers + catching[k] = {} + seen[k].clear() + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: + for update in client.drain_updates(): + catching[k].setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(catching[k]) < P: + return + caught = catching.pop(k) + versions[k] = [caught[fid] for fid in range(P)] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if k == 1 and phase["name"] in ("stuck", "relaunching", "stuck again"): + held.pop(k, None) + client.drain_pulls() + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(clients): + drain(k) + log = launches.logs[1] + if phase["name"] == "train" and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + # the history in the store and the merges so far reported nobody + assert not log.kinds(st.EVENT) and not launches.logs[0].kinds(st.EVENT) + phase["name"] = "stuck" + elif phase["name"] == "stuck" and log.kinds(st.EVENT): + phase["name"] = "relaunching" + node = NODES[1][1].name + cluster.exit(node, max(cluster.runs[node]), 1) # incarnation 0's rank 1 fails + elif phase["name"] == "relaunching" and log.kinds(st.CLEARED_EVENT) and 1 in clients and 1 not in catching: + phase["name"] = "stuck again" + elif phase["name"] == "stuck again" and len(log.kinds(st.EVENT)) == 2: + phase["name"] = "pushing" + return phase["name"] == "pushing" and len(log.kinds(st.CLEARED_EVENT)) == 2 \ + and all(c.finalizing.is_set() for c in clients.values()) + + try: + worker.step() + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, "the fleet never finalized (stuck, relaunched)", timeout=300) + for client in clients.values(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in dz.trainers(store.read()).values()), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + for up_ in uploaders: + up_.stop(5.0) + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the watch read the run store's copy, uploaded chunk by chunk + assert all(isinstance(w.source, st.StoreTape) and w.source.requests > 0 for w in watches.values()) + current = [key for key in objects.list(st.SYNCER_TAPES) if "oldhost-" not in key] + assert len(current) >= 2 and len({key.rsplit("/", 2)[1] for key in current}) == 1 + + # -- island 1: reported, relaunched (cleared), reported again N cycles after its new join, cleared + first, second = launches.logs[1].kinds(st.EVENT) + for event in (first, second): + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert first[2]["last_merged_step"] is not None # its own stretch, not the history's 40 merges + assert first[2]["newest_step"] - first[2]["last_merged_step"] >= CYCLES * P + relaunched, back = launches.logs[1].kinds(st.CLEARED_EVENT) + assert relaunched[2]["reason"] == "relaunched" and back[2]["reason"] == "a push of it is merged again" + steps = _outer_steps(tape.read_text()) + joins = [r for r in _records(tape) if r.get("kind") == "pool_join" and int(r["island_id"]) == 1 + and r.get("catch_up") and r["base_version"] <= second[2]["newest_step"]] + rejoin = max(r["base_version"] for r in joins) # the relaunched incarnation's join + assert rejoin >= first[2]["newest_step"] # after the first report (the relaunch may beat the next merge) + assert second[2]["newest_step"] - rejoin >= CYCLES * P # counted from that join, not before + assert states.read(1)["straggler"] is None + ctl = launches.controllers[1] + assert ctl.learners["r-i1-trainer"]["relaunches"] == 1 and launches.started("r-i1") == 1 + + # -- island 0 untouched; the merges continuous, no push merged twice; nobody else reported + assert launches.started("r-i0") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[0]] == [1, 1] + assert not launches.logs[0].kinds(st.EVENT) and not launches.logs[0].kinds(st.UNAVAILABLE_EVENT) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + + # -- the ledger: island 1's two incarnations, each created once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + assert sorted(created) == ["r-i0/r-i0-trainer-i0", "r-i1/r-i1-trainer-i0", "r-i1/r-i1-trainer-i1"] + assert set(created.values()) == {1} + assert all(n == 1 for n in Counter(r["id"] for r in rows if r["op"] == "release").values()) + + +def worker_members(store, case): + members = list(dz.trainers(store.read()).values()) + if case == "remove": + members.append({"prefix": "r-i1"}) + return members + + +def _records(tape): + return [json.loads(line) for line in tape.read_text().splitlines() if line.strip()] diff --git a/yeto/dashboard/fleet_islands.py b/yeto/dashboard/fleet_islands.py index 81568fe25..278d4ba54 100644 --- a/yeto/dashboard/fleet_islands.py +++ b/yeto/dashboard/fleet_islands.py @@ -323,10 +323,22 @@ def _trainer_records(objects: Any, learners: Any = None) -> dict[int, dict]: "started_at": _f(launch.get("started_at")), "closed_at": _f(launch.get("closed_at")), "down_at": _f(launch.get("down_at")), "name": _str(launch.get("name")), "moving_to": _str(launch.get("moving_to")), - "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None} + "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None, + "straggler": _straggler(life.get("straggler"))} return out +def _straggler(mark: Any) -> dict | None: + """The controller's straggler mark in an island's record (``yeto.launch.island_straggler``, + written by ``FleetController._island_straggler``; None once cleared).""" + if not isinstance(mark, dict): + return None + return {**{k: _int(mark.get(k)) for k in ("missed_cycles", "merges", "fragments", "cycles", "newest_step", + "last_merged_step")}, + "action": _str(mark.get("action")), "reason": _str(mark.get("reason")), + "absent": mark.get("absent") is True, "at": _f(mark.get("at"))} + + def _phase(life: str | None) -> str: """A launch's lifecycle state in words (``yeto.rl.island_launches``).""" return {"ordering": "ordering machines (failing over across zones while none is free)", diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 3d5dfe761..ebe55e9c9 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -41,8 +41,12 @@ from . import topology as topology_mod from .sources import COST_EVENTS_FILE, up_state_stops +# a trainer island the syncer has merged no push of for N merge cycles, and its end (or why +# that cannot be watched): fleet.jsonl events that are not lifecycle states +STRAGGLER_EVENTS = frozenset({"island_straggler", "island_straggler_cleared", "island_straggler_unavailable", + "island_straggler_available"}) FLEET_EVENTS = frozenset({"island_launch", "island_ready", "island_lost", "island_stop", "island_done", - "cost_tick"}) + "cost_tick"}) | STRAGGLER_EVENTS POLICY_SWEEP_LEDGER_EVENT = "policy_sweep_ledger" # the syncer's own records (``kind``, no ``step``): its config, round opens / timeouts and # the island connections it saw; a ``learner_id`` there is not a sign of life of that island @@ -669,6 +673,7 @@ def _trainer_island_now(self, isl: dict) -> dict | None: "gpu": rec.get("gpu") or row.get("gpu"), "usd_per_h": rec.get("usd_per_h") or row.get("usd_per_h"), "incarnation": rec.get("incarnation"), "relaunches": rec.get("relaunches"), "moves": row.get("moves") or [], "name": row.get("name"), + "straggler": rec.get("straggler"), # the controller's straggler mark, None once cleared "prefix": rec.get("prefix") or row.get("prefix")} def _membership_left(self, isl: dict, now: float | None = None) -> dict | None: @@ -1452,6 +1457,13 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: isl[key] = r[key] if r.get("island") is not None: isl["name"] = r["island"] + if event in STRAGGLER_EVENTS: # a mark on the card, not a lifecycle state + if event == "island_straggler": + isl["straggler"] = {**{k: r.get(k) for k in ("action", "missed_cycles", "newest_step", + "last_merged_step")}, "at": ts} + elif event == "island_straggler_cleared": + isl["straggler"] = None + return isl["fleet_state"] = event[len("island_"):] # wall clock accrues over ready -> lost/stop intervals (relaunches re-open one) if event == "island_ready" and ts is not None: @@ -1706,6 +1718,7 @@ def _island_card(self, isl: dict, now: float) -> dict: # a sampler waiting at its backlog cap writes nothing until the trainers read "waiting_backlog": waiting, "waiting_reason": waiting_why or ("backlog full" if waiting else None), "role": role, "left": left, "stale_after_s": _r(warn_s), "island_now": inow, + "straggler": isl.get("straggler"), # a sampler whose pool removed or retired it but that still runs (draining, or its # machine not released): shown running, alerted past alerts.POOL_REMOVED_GRACE_S "pool_removed": ({**pool_removed, "since_s": _r(now - pool_removed["ts"]) diff --git a/yeto/dashboard/static/app.js b/yeto/dashboard/static/app.js index 30337b9ed..82a7aae1a 100644 --- a/yeto/dashboard/static/app.js +++ b/yeto/dashboard/static/app.js @@ -445,14 +445,18 @@ function cost(){ } var EV_KEEP={rl_engine_selected:1,rl_driver_start:1,rl_driver_phase:1,rl_publication:1,rl_round_trained:1,rl_reconfiguration:1,rl_learner_finalized:1, island_ready:1,island_lost:1,island_stop:1,island_done:1,island_leave:1,operator_stop:1,dashboard_source_lost:1,rl_elastic_recommendation:1, - rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1}; + rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1, + island_straggler:1,island_straggler_cleared:1,island_straggler_unavailable:1,island_straggler_available:1}; var POOL_BAD=/evicted|node_lost|crash_loop|failed|breaker|timeout|overdue|orphan|refused|manual_release/; function keepEv(t){return EV_KEEP[t]||/^nc_elastic_/.test(t)} var EVENTS=[],EV_CURSOR=0; function evLevel(t,rec){if(t==="operator_stop")return ["mu","stop"]; + if(t==="island_straggler")return ["wn","lag"];if(t==="island_straggler_cleared")return ["ok","back"];if(t==="island_straggler_unavailable"||t==="island_straggler_available")return ["mu","info"]; if(/^nc_elastic_/.test(t))return POOL_BAD.test(t)?["bd","pool"]:["wn","pool"];if(t==="island_leave")return ["wn","left"];if(t==="island_lost"||(t==="rl_reconfiguration"&&rec.result==="RECOVERY_REQUIRED"))return ["bd","failure"]; if(t==="rl_publication"||t==="rl_round_trained")return ["ok","done"];if(t==="rl_reconfiguration"||t==="dashboard_source_lost")return ["wn","change"];return ["mu","info"]} -function evText(e){var r=e.record||{},keys=["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; +// a straggler report: its count; its end and the watch's notices: their reason only +var EV_STRAGGLER_KEYS={island_straggler:["action","missed_cycles","newest_step","last_merged_step"]}; +function evText(e){var r=e.record||{},keys=/^island_straggler/.test(e.type)?EV_STRAGGLER_KEYS[e.type]||["reason"]:["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; return keys.filter(function(k){return r[k]!=null}).map(function(k){return k+"="+String(r[k]).slice(0,80)}).join(" ")} /* newest first by event time; the tapes are read one after another, so arrival (seq) order is not time order. One total-order key per event: its time (an event without one takes the time of the last timed event that diff --git a/yeto/dashboard/static/sft.js b/yeto/dashboard/static/sft.js index e3595d7d3..115f2b05c 100644 --- a/yeto/dashboard/static/sft.js +++ b/yeto/dashboard/static/sft.js @@ -574,7 +574,10 @@ function rlm(V){ var head='Island'+(dl?'Local step / outer sweep':"Round / policy")+'Rewardtrain-rollout KLlogprob |diff|grad_normStep / round timeTokens/s'+(noHbm?"":'HBM peak')+''+(dl?"Last PUSH / BCAST applied":"Last release / load")+'Shard · incarnation'; var flNa=rlMulti(V); var rowOf=function(c){var ex=X[c.id]||{},s=S[c.id],rr=RR(c),r=rr[rr.length-1]||{},liv=rlLive(c.status),h=hbm(c),lim=ex.hbm_total_gib,mx=Math.max(64,fin(lim)?lim*1.15:0),pc=fin(h)?Math.min(100,100*h/mx):0; - var row='
'+rlDot(c.status)+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+esc(c.status+(c.waiting_reason?": "+c.waiting_reason:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; + // a trainer island the syncer has merged no push of for N merge cycles (its record's mark, else its fleet + // event): "straggler" in warn colour in place of its live status + var sg=liv&&!!(c.island_now&&"straggler" in c.island_now?c.island_now.straggler:c.straggler); + var row='
'+(sg?'':rlDot(c.status))+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+(sg?'straggler':esc(c.status))+esc((c.waiting_reason?": "+c.waiting_reason:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; var hb='
'+(fin(h)?h.toFixed(1)+" GiB"+(fin(lim)?" of "+lim+" GiB":""):"not sampled")+'
'+(fin(lim)?'
':"")+'
'+(fin(h)?"":'
'+(/unavailable/.test(ex.gpu_mem_note||"")?"telemetry library missing":"enable --rl-resource-sample-interval")+'
')+''; if(noHbm)hb=""; if(c.role==="sampler"&&s){var sr=s.rounds||[],l=s.last_round||sr[sr.length-1]||{},ld=(A.releases||[]).map(function(x){return (x.loads||{})[c.id]?[x.policy_version,x.loads[c.id]]:null}).filter(Boolean).pop(); diff --git a/yeto/dashboard/static/topology_diloco.js b/yeto/dashboard/static/topology_diloco.js index cb798a875..9a48f5c34 100644 --- a/yeto/dashboard/static/topology_diloco.js +++ b/yeto/dashboard/static/topology_diloco.js @@ -68,6 +68,8 @@ function islandNow(tr){var n=tr.island_now;if(!n)return null; return {stopped:["stopped: "+(n.reason||""),"mute"],done:["finished","mute"],down:["down (run down)","mute"],removed:["removed from the fleet","mute"], abandoned:["abandoned: "+(n.reason||"given up"),"bad"],failed:["failed: "+(n.reason||"")+(n.detail?" · "+n.detail:""),"bad"], moving:[(n.reason||"moving").replace(/^moving to /,"moving → ")+(n.detail&&/^new launch ordering/.test(n.detail)?" · ordering":""),"warn"],starting:[(n.reason||"starting")+(fin(n.incarnation)?" · incarnation "+n.incarnation:""),"warn"]}[n.state]||null} +// the controller's straggler mark: its record's when the island has one, else its last fleet.jsonl event +function straggler(tr){var n=tr.island_now;return (n&&"straggler" in n?n.straggler:tr.straggler)||null} function trainerState(tr,tn,isl){ var age=fin(tr.phase_since)?tn-tr.phase_since:null,a=age!=null?" · "+dur(age):"",ph=tr.phase_raw,co=isl&&isl.colocated; var inow=islandNow(tr);if(inow)return inow; @@ -355,6 +357,7 @@ function paint(){ tc.step.textContent=(fin(tr.step)?"step "+tr.step:fleet()?"not trained yet":"step —")+(sft()&&fin(tr.steps_total)?" / "+tr.steps_total:"");tc.outer.textContent=fin(tr.outer)?(L.W<640?"sweep ":"outer sweep ")+tr.outer:""; // complete sweeps it applied (hover: the card's tip) fitText(tc.ph,st[0],tc.phw);tc.ph.style.fill=st[1]==="good"?C.ink:c;tc.dot.setAttribute("fill",c); tc.badge.textContent=tr.failure?(/hash/.test(tr.failure.metric)?"hash ✕":/lr/.test(tr.failure.metric)?"lr 0":"failed"):tr.lr_zero&&tr.live?"lr 0":dead?"lost":tr.syncer_link&&tr.syncer_link.state==="disconnected"&&!D.done&&!(tr.island_now&&/^(moving|starting)$/.test(tr.island_now.state))?"link ✕":"";tc.badge.style.fill=C.bad; + if(!tc.badge.textContent&&straggler(tr)&&!D.done){tc.badge.textContent="straggler";tc.badge.style.fill=C.warn} // no push merged for N merge cycles [tc.co?o.merged:tc.box].forEach(function(b){if(b){b.style.stroke=dead||tr.failure?C.bad:"";b.style.strokeDasharray=dead?"5 4":""}}); o.tc.g.setAttribute("opacity",dead?0.6:1); var L0=tc.l,lw=tc.lw; diff --git a/yeto/dashboard/topology_diloco.py b/yeto/dashboard/topology_diloco.py index 4009e4be3..fcd6e6744 100644 --- a/yeto/dashboard/topology_diloco.py +++ b/yeto/dashboard/topology_diloco.py @@ -757,6 +757,7 @@ def _trainer(iid: str, x: _Island, card: dict, st: dict, merges: list[dict], ver "arch": arch_of(card.get("gpu")), "status": st.get("status"), "live": bool(st.get("alive")), "reason": (card.get("left") or {}).get("reason"), "finalized": bool(card.get("finalized")), "island_now": card.get("island_now"), # its trainer island record (a fleet launched island by island) + "straggler": card.get("straggler"), # its last island_straggler event, None once cleared "last_event_ts": st.get("last_event_ts"), "step": step, "outer": _int(full.get("sync/outer_version")) if full else None, "versions": vec, "since": since, "pushed": {str(k): v for k, v in pushed.items()}, diff --git a/yeto/hw/node_health.py b/yeto/hw/node_health.py index f811e7dee..e285453c8 100644 --- a/yeto/hw/node_health.py +++ b/yeto/hw/node_health.py @@ -43,7 +43,9 @@ (:data:`HARDWARE_XIDS`) since the previous check, the NVLink fabric is ``Completed/Success`` on every GPU that has one, the fabric manager did not stop; * ``ok_multi``: also every port the job's ``NCCL_IB_HCA`` names exists, is ``Active`` - and runs at no less than its rate at the first check (or ``min_ib_gbps``). False + and runs at no less than its rate at the first check and ``min_ib_gbps``; without + ``NCCL_IB_HCA``, one of the fabric's ports is active and, with ``min_ib_gbps``, every + active one runs at no less. False whenever ``ok_single`` is; None when the GPUs pass but the job names HCAs and the IB tools did not read (a read failure of the multi-node job: ``IB tools unread``). @@ -543,6 +545,10 @@ def _ports(self, sections: Mapping[str, Any], hcas: Sequence[str], prev: Mapping if not any(p.active for p in picked): down = ", ".join(f"{_port_label(p)} {(p.state or 'unknown').upper()}" for p in picked) or "none found" out.append(f"no active {self.fabric} port ({down})") + elif self.min_ib_gbps is not None: # the inventory's least rate: every active port NCCL may use + out += [f"{_port_label(p)} rate {p.rate_gbps:g} < {self.min_ib_gbps:g} Gb/s" + for p in natural_order(picked) + if p.active and p.rate_gbps is not None and p.rate_gbps < self.min_ib_gbps * 0.999] selected = [] else: selected = [] @@ -551,7 +557,9 @@ def _ports(self, sections: Mapping[str, Any], hcas: Sequence[str], prev: Mapping if not p.active: out.append(f"{label} port {(p.state or 'unknown').upper()}") continue - base = self.min_ib_gbps if self.min_ib_gbps is not None else rates.get(label) + # the first check's rate, and the declared least one: a low min_ib_gbps never hides a slower port + known = [float(b) for b in (self.min_ib_gbps, rates.get(label)) if b is not None] + base = max(known) if known else None if p.rate_gbps is not None and base is not None and p.rate_gbps < float(base) * 0.999: out.append(f"{label} rate {p.rate_gbps:g} < {float(base):g} Gb/s") for p in ports: # every active port's best rate: the baseline of a later job port diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 99eb1d0a4..88adeb7c3 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -287,6 +287,8 @@ def __init__( incarnations=None, stop_probe=None, deterministic_stop: bool = False, + straggler=None, + straggler_policy=None, ): """`learners` maps cluster name -> (task, job_id); `syncer` is (name, task, job_id) for a cluster syncer, or None with @@ -406,6 +408,13 @@ def __init__( # STOP there ends that island only. None (a single-trainer launch by default): # nothing is written or read. self.recorder = recorder + # yeto.launch.island_straggler.StragglerWatch or None: the syncer's merges, read each + # poll; a running island none of whose pushes was merged in N merge cycles is written + # as island_straggler (fleet.jsonl and its record). ``straggler_policy(name, signal)`` + # says what to do (island_straggler.WAIT, the default, or REPLACE with a ``replace`` + # callable of its own); None: wait (the syncer merges without it meanwhile). + self.straggler = straggler + self.straggler_policy = straggler_policy # name -> {"incarnation", "relaunches", "adopted"} from the island's record of an # earlier launcher of this run (yeto.launch.island_adopt): an adopted island keeps # its incarnation; a relaunched one continues the count. @@ -532,6 +541,7 @@ def _run_fleet(self) -> dict: self._poll_local_syncer() for rec in self.learners.values(): self._poll_recorded(rec) + self._poll_stragglers() self._end_followers() if all(r["state"] in (DONE, ABANDONED) for r in self.learners.values()): break @@ -1049,6 +1059,114 @@ def _check_stall(self) -> None: print(f"[launcher] ERROR: run stalled: {message}", file=sys.stderr) raise RunStalled(message, silent_s=silent, timeout_s=self.stall_timeout) + # -- island stragglers (yeto.launch.island_straggler) ------------------------------------- + def _poll_stragglers(self) -> None: + """The straggler watch's signals for the islands running now (not draining): each one + is written once (``island_straggler`` / ``island_straggler_cleared`` in fleet.jsonl, + ``straggler`` in the island's record) and its policy is asked what to do; a flagged + island that stops running (recovering, draining, ended) is cleared, naming why. The + watch's notices (nothing can be watched here, its tape went silent, it is read again) + are written once each (``island_straggler_unavailable`` / ``_available``). At its first + poll, a mark an earlier launcher left in an island's record is cleared (``controller + restarted``): this watch judges the island again. Never raises: a watch that fails is a + missing view, not the end of supervision.""" + if self.straggler is None or self.recorder is None: + return + from . import island_straggler as st + + try: + running, names = {}, {} + for rec in self.learners.values(): + ref = self.recorder.ref(rec["name"]) + if ref is None or ref.role == "sampler": + continue + names[ref.island] = rec + if rec["state"] == RUNNING and not rec.get("draining"): + running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) + if not getattr(self, "_straggler_marks_checked", False): + self._straggler_marks_checked = True + self._clear_left_marks(names) + for signal in self.straggler.poll(running): + rec = names.get(signal.island) + if rec is not None: + self._island_straggler(rec, signal) + # each trainer island of this launch names it (a nameless fleet.jsonl event would be + # priced as an island of its own); kept until the launch knows its islands + if names: + for kind, why in self.straggler.notices(): + print(f"[launcher] island straggler watch: {why}", file=sys.stderr) + for rec in names.values(): + self._fleet(kind, rec["name"], reason=str(why)[:500]) + except Exception as error: # noqa: BLE001 - a watch, never the end of supervision + print(f"[launcher] island straggler watch: {type(error).__name__}: {error}"[:400], file=sys.stderr) + + def _clear_left_marks(self, names) -> None: + """Close the stretch an earlier launcher of this run left open in a record (it was + restarted, or this one adopted the island): written once, then judged again.""" + from . import island_straggler as st + + store = getattr(self.recorder, "store", None) + if store is None: + return + for island, rec in names.items(): + try: + left = (store.read(island) or {}).get("straggler") + except Exception as error: # noqa: BLE001 - its record does not read: nothing to close + print(f"[launcher] {rec['name']}: island record: {type(error).__name__}: {error}"[:300], + file=sys.stderr) + continue + if not left: + continue + fields = {k: left.get(k) for k in ("missed_cycles", "merges", "fragments", "newest_step", + "last_merged_step") if isinstance(left, dict) and k in left} + print(f"[launcher] {rec['name']}: no longer a straggler (controller restarted)", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, rec["name"], **fields, reason="controller restarted") + self._record(rec, straggler=None) + + @staticmethod + def _not_running(rec) -> str: + """Why a flagged island's stretch ends without a merged push: its controller state.""" + if rec.get("draining") or rec.get("stop_request") is not None: + return "stopped or removed (island STOP)" + if rec["state"] == RECOVERING: + return "relaunched" + return f"not running ({rec['state']})" + + def _island_straggler(self, rec, signal) -> None: + from dataclasses import replace + + from . import island_straggler as st + + name = rec["name"] + if signal.cleared: + if signal.reason == "not running": + signal = replace(signal, reason=self._not_running(rec)) + print(f"[launcher] {name}: no longer a straggler ({signal.reason})", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, name, **st.signal_fields(signal, None)) + self._record(rec, straggler=None) + return + action = st.WAIT + if self.straggler_policy is not None: + try: + action = self.straggler_policy(name, signal) or st.WAIT + except Exception as error: # noqa: BLE001 - the default is to wait + print(f"[launcher] {name}: straggler policy failed ({type(error).__name__}: {error}); " + "waiting", file=sys.stderr) + action = st.WAIT + if action not in st.ACTIONS: + print(f"[launcher] {name}: straggler policy answered {action!r}; waiting", file=sys.stderr) + action = st.WAIT + fields = st.signal_fields(signal, action) + print(f"[launcher] WARNING: {name}: island straggler: {signal.reason}; " + + ("waiting (the syncer merges the other islands at each quorum deadline, and catches it up " + "once it delivers again)" if action == st.WAIT else "its provider replaces it"), file=sys.stderr) + self._fleet(st.EVENT, name, **fields) + self._record(rec, straggler=dict(fields, at=self.ops.now())) + if action == st.REPLACE: + replace = getattr(self.straggler_policy, "replace", None) + if callable(replace): + replace(name, signal) + def _all_learners_finalized(self) -> bool: return self.finalized_probe is not None and all( r["state"] == DONE or self._finalized(r) for r in self.learners.values() diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py new file mode 100644 index 000000000..244b3e7bb --- /dev/null +++ b/yeto/launch/island_join.py @@ -0,0 +1,696 @@ +"""The checks a new ``ssh:`` trainer island's nodes pass before ``yeto fleet island add`` +writes it into a running fleet, or ``yeto fleet island move`` moves an island onto them +(own-cluster-fleet-stability 9.3). + +An island's nodes are the trainer nodes of its inventory (the command's inventory option: +its launch's ``--rl-node-inventory``). Before anything is written (and in the dry run): + +* count and this fleet: an inventory without ``lease_store`` lists exactly as many + trainer nodes as ``--gpu`` says, none of them a trainer node of another ``ssh:`` island + of the fleet (same name, or same machine: the SSH target without its ``user@`` or the + ``address``, in any case). An inventory with ``lease_store`` may list more (the launch's + rule): the island takes ``need`` of them, as its launch picks them (below), and a node + is another island's when that island's launch holds its lease; +* health: the node health checker of the device family (``yeto.hw.node_health``, built as + the island's launch builds it), one SSH call per node, judged with absolute rules (a + first check has no previous one to compare with): a hardware XID in this boot, a + volatile uncorrectable ECC count above 0, an NVSwitch node whose fabric manager is not + ``active``, a GPU missing; a multi-node island also needs its ``NCCL_IB_HCA`` ports + active, at ``min_ib_gbps`` of the node when the inventory sets it, else at no less than + half the fastest job port of the island's nodes. A family without a checker, or a node + with ``node_health: off``, is noted. A check that does not read (no answer, a timeout, a + check still stuck on the node, an output cut off) refuses, unless ``--force`` (a WARNING); +* fabric group (``yeto.launch.fabric_groups``): an inventory that declares groups places + a multi-node island in one group; one without any group only notes it; +* leases (``yeto.launch.node_lease.NodeLeases``): a node another run holds, or another + island of this fleet, is left out (without ``lease_store``: a note). A lease of the + island's own launch (```` or ``-m``, part ``trainer``) is its own. A + lease that does not read refuses. + +With ``lease_store`` the island's nodes are the ones its launch will take: the free nodes +(not held by another run) in the inventory's order, those this launch holds first, placed +by ``fabric_groups.pick_placement`` (``ssh_trainer_island.lease_trainer_nodes``). The +check leaves out the nodes held by others and the unhealthy ones, then places ``need`` +nodes; none fit: refused, naming every node left out and why. A placement of the launch's +own rule that would take a node the check found unhealthy is refused too (the launch +picks by leases only). + +:func:`check` returns what was refused, noted and warned, and the nodes the island takes; +``yeto fleet island add`` / ``move`` print the notes and refuse the change (exit 2, +nothing written) on any refusal, naming each. +""" + +from __future__ import annotations + +import re +import sys +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any + +INVENTORY_FLAG = "--rl-node-inventory" +ISLAND_ENV_FLAG = "--island-env" +HEALTH_TIMEOUT_S = 120.0 # the SSH call of one check (the check bounds itself at node_health.HEALTH_LIMIT_S) +# the previous check of a node that has none: an XID cursor of no boot, so every hardware +# XID of this boot is new (``CudaChecker`` counts the XIDs after a reboot the same way) +JOIN_PREV: Mapping[str, Any] = {"xid": {"boot": None}} +RATE_FRACTION = 0.5 # a job port below this fraction of the island's fastest one is refused +XID_UNREAD = ("the kernel log does not read (dmesg restricted, no journalctl -k): add the SSH user to the adm or " + "systemd-journal group, or let it run dmesg with sudo") +XID_TIMED_OUT = "reading the kernel log (dmesg / journalctl -k) timed out" +XID_HINT = (" (a hardware Xid in the kernel log of this boot: fix the GPU and reboot the node, a new boot starts a " + "new log, then add the island again)") +_HARDWARE_XID = re.compile(r"\bXID (\d+)\b") + + +@dataclass +class NodeHealth: + """One node's health for the join: ``state`` ``ok`` / ``bad`` / ``unread`` / + ``unchecked``; ``text``: what to say after ``node ``; ``rates``: its job ports' + rates (Gb/s; a multi-node island).""" + + state: str + text: str = "" + rates: dict[str, float] = field(default_factory=dict) + + +@dataclass +class JoinCheck: + refusals: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + nodes: list[str] = field(default_factory=list) # the nodes the island takes (passed) + health: dict[str, NodeHealth] = field(default_factory=dict) # by node name (a recheck reuses it) + + @property + def ok(self) -> bool: + return not self.refusals + + +def inventory_of(argv: Sequence[str]) -> str | None: + """The last ``--rl-node-inventory`` of a launch argv (the island's own wins over the fleet's).""" + found = None + for i, arg in enumerate(argv): + if arg == INVENTORY_FLAG and i + 1 < len(argv): + found = str(argv[i + 1]) + elif str(arg).startswith(INVENTORY_FLAG + "="): + found = str(arg).split("=", 1)[1] + return found + + +def without_inventory(argv: Sequence[str]) -> list[str]: + """``argv`` without its ``--rl-node-inventory`` flags.""" + out, skip = [], False + for arg in argv: + if skip: + skip = False + continue + if arg == INVENTORY_FLAG: + skip = True + continue + if str(arg).startswith(INVENTORY_FLAG + "="): + continue + out.append(arg) + return out + + +def island_env_of(argv: Sequence[str]) -> dict[str, str]: + """The ``--island-env KEY=VALUE`` items of a launch argv (the last of a key wins): the + island's own environment, which an ``ssh:`` island exports after the node's ``env``.""" + out: dict[str, str] = {} + for i, arg in enumerate(argv): + item = None + if arg == ISLAND_ENV_FLAG and i + 1 < len(argv): + item = str(argv[i + 1]) + elif str(arg).startswith(ISLAND_ENV_FLAG + "="): + item = str(arg).split("=", 1)[1] + if item and "=" in item: + key, value = item.split("=", 1) + out[key.strip()] = value + return out + + +def island_nodes(argv: Sequence[str], gpu: str) -> tuple[Any, int, str | None]: + """``(trainer nodes, nodes the island needs, inventory path)`` of an ``ssh:`` island's + launch argv; raises ValueError naming what is wrong.""" + from ..gpu_spec import parse_gpu_spec # noqa: PLC0415 + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + (spec, *rest) = parse_gpu_spec(gpu) + if rest or spec.cloud != "ssh": + raise ValueError(f"--gpu {gpu}: one ssh: cluster expected") + path = inventory_of(argv) + if path is None: + raise ValueError(f"an ssh: island needs its node inventory ({INVENTORY_FLAG}; the inventory option " + "of yeto fleet island add / move)") + return role_nodes(load_inventory(path), "trainer"), int(spec.num_nodes), path + + +def node_keys(node: Any) -> set[str]: + """What names the node's machine: its name, and its SSH target (without ``user@``) and + ``address`` in lower case.""" + keys = {f"name:{node.name}"} + for value in (str(getattr(node, "host", "") or "").rpartition("@")[2], getattr(node, "address", None)): + value = str(value or "").strip().lower() + if value: + keys.add(f"host:{value}") + return keys + + +def own_lease(holder: str | None, run_id: str) -> bool: + """``holder`` is the island's own launch (```` or ``-m`` after a + move), as a trainer.""" + if not holder: + return False + from .node_lease import run_of # noqa: PLC0415 + + run = run_of(holder) or "" + part = str(holder).split("@", 1)[0].rpartition("/")[2] + return part == "trainer" and re.fullmatch(rf"{re.escape(str(run_id))}(-m\d+)?", run) is not None + + +def island_of_lease(holder: str | None, islands: Mapping[str, str]) -> str | None: + """The fleet island (``islands``: launch prefix -> island) whose launch holds the lease.""" + return next((name for prefix, name in islands.items() if own_lease(holder, prefix)), None) + + +# -- the modules of the checks (yeto.hw.node_health, fabric_groups, node_lease) --------------------- + +def _checker_for(node: Any) -> Any: + """The node's health checker, built as the island's own launch builds it (ssh_resident).""" + from yeto.hw.node_health import checker_for # noqa: PLC0415 + + from .ssh_resident import RDMA_FABRICS # noqa: PLC0415 + + fabric = getattr(node, "fabric", None) + return checker_for(node.device_family, expect_gpus=getattr(node, "cards_per_node", None), + min_ib_gbps=getattr(node, "min_ib_gbps", None), + fabric=fabric if fabric in RDMA_FABRICS else None) + + +def _check_placement(nodes: Sequence[Any], need: int, inventory: Sequence[Any] | None) -> tuple[bool, str, bool]: + from .fabric_groups import check_placement # noqa: PLC0415 + + return check_placement(nodes, need, inventory=inventory) + + +def _pick_placement(nodes: Sequence[Any], need: int, inventory: Sequence[Any] | None) -> list[Any]: + """``need`` of ``nodes`` as the launch's lease pick places them; raises PlacementError.""" + from .fabric_groups import pick_placement # noqa: PLC0415 + + return list(pick_placement(nodes, need, inventory=inventory).nodes) + + +def _grouped(inventory: Sequence[Any]) -> bool: + from .fabric_groups import grouped # noqa: PLC0415 + + return grouped(inventory) + + +def _node_leases(store_uri: str, run_id: str) -> Any: + from .node_lease import NodeLeases # noqa: PLC0415 + + return NodeLeases(store_uri, f"{run_id}/trainer") # read only: who holds each node + + +def _hcas(node: Any, env: Mapping[str, str] | None = None) -> list[str]: + """The job's ``NCCL_IB_HCA`` on the node: the island's environment over the node's (as + the launch exports them, ``ssh_resident``).""" + from yeto.hw.node_health import hcas_of # noqa: PLC0415 + + merged = {**dict(getattr(node, "env", None) or {}), **dict(env or {})} + return list(hcas_of(merged.get("NCCL_IB_HCA"))) + + +# -- health --------------------------------------------------------------------------------------- + +def _absolute(result: Any, *, fm_read: bool = True) -> list[str]: + """What a first check cannot see as a change but a node joining must not have: a + volatile uncorrectable ECC count above 0, an NVSwitch node whose fabric manager is not + active (the checker's facts).""" + facts = result.facts or {} + bus = dict(facts.get("bus") or {}) + out = [f"GPU {bus.get(key, key)} uncorrectable ECC {count} (volatile)" + for key, count in sorted((facts.get("ecc") or {}).items(), key=lambda kv: str(bus.get(kv[0], kv[0]))) + if count is not None and int(count) > 0] + if fm_read and facts.get("fabric") not in (None, "none") and facts.get("fm") != "active": # NVSwitch: the FM runs + out.append(f"nvidia-fabricmanager {facts.get('fm') or 'not running'} on an NVSwitch node") + return out + + +def _unread_parts(text: str, result: Any) -> list[str]: + """The parts of a whole check that the join's absolute rules need and that did not read: + the kernel log (timed out, or no XID source: ``dmesg`` restricted and no ``journalctl + -k``), the NVLink fabric or the fabric manager timed out (a kill, 137, too).""" + from yeto.hw.host_probe import parse_sections # noqa: PLC0415 + + out = [] + sections = parse_sections(text) + xid = sections.get("xid") + if xid is not None and xid.rc in (124, 137): + out.append(XID_TIMED_OUT) + elif (result.facts or {}).get("xid_source") == "none": + out.append(XID_UNREAD) + for name in ("fabric", "fabricmanager"): + sec = sections.get(name) + if sec is not None and sec.rc in (124, 137): + tool = "nvidia-smi -q (NVLink fabric)" if name == "fabric" else "systemctl is-active nvidia-fabricmanager" + out.append(f"{tool} timed out") + return out + + +def _job_rates(text: str, hcas: Sequence[str], fabric: str | None) -> dict[str, float]: + """The rates of the job's active ports (``NCCL_IB_HCA``, else the fabric's link layer), + read by the preflight's parsers (``yeto.hw.host_probe``).""" + from yeto.hw.host_probe import ( # noqa: PLC0415 + hca_filter, + link_layer_ports, + natural_order, + parse_sections, + ports_of, + section_ok, + ) + + sections = parse_sections(text) + if not (section_ok(sections.get("ibstat")) or section_ok(sections.get("ibv_devinfo"))): + return {} + ports = natural_order(ports_of(sections)) + if hcas: + picked, _ = hca_filter(",".join(hcas), ports) + elif fabric: + picked = link_layer_ports(ports, fabric) + else: + picked = [] + return {(p.ca if p.port == 1 else f"{p.ca}:{p.port}"): float(p.rate_gbps) + for p in natural_order(picked) if p.active and p.rate_gbps} + + +def read_health(node: Any, *, multi: bool, ssh: Any, env: Mapping[str, str] | None = None) -> NodeHealth: + """One node's health check (module doc), as :class:`NodeHealth`.""" + if getattr(node, "node_health", None) == "off": + return NodeHealth("unchecked", "node_health off in the inventory: its health is not checked") + try: + checker = _checker_for(node) + if not getattr(checker, "enabled", True): + return NodeHealth("unchecked", f"no health check for device family {node.device_family}") + hcas = _hcas(node, env) if multi else [] + done = ssh.run(node, checker.script(hcas), timeout=HEALTH_TIMEOUT_S) + except Exception as error: # noqa: BLE001 - named in the refusal + return NodeHealth("unread", f"its health check could not run ({type(error).__name__}: {error})"[:300]) + if done.returncode != 0: + last = [line for line in str(done.stderr or "").splitlines() if line.strip()][-1:] + return NodeHealth("unread", f"its health check did not answer (ssh exit {done.returncode}" + + (f": {last[0].strip()}" if last else "") + ")") + text = str(done.stdout or "") + result = checker.parse(text, hcas, dict(JOIN_PREV)) + if not result.checked: + return NodeHealth("unread", "its health check did not read (" + + ("; ".join(result.reasons) or "no reason given") + ")") + ok = result.ok(multi) + unread = _unread_parts(text, result) + reasons = (list(result.job_reasons(multi)) if ok is False else []) + _absolute( + result, fm_read=not any("nvidia-fabricmanager" in part for part in unread)) + if reasons: + hint = XID_HINT if any(_HARDWARE_XID.search(r) for r in reasons) else "" + return NodeHealth("bad", "is not healthy: " + "; ".join(dict.fromkeys(reasons)) + hint) + if ok is None: # the GPUs pass, the job's ports did not read (multi-node) + return NodeHealth("unread", "its health check did not read (" + ("; ".join(result.reasons) or "unknown") + + ")") + if unread: # a part the absolute rules need did not read + return NodeHealth("unread", f"its health check did not read ({'; '.join(unread)})") + rates = _job_rates(text, hcas, getattr(checker, "fabric", None)) if multi else {} + return NodeHealth("ok", rates=rates) + + +def judge_rates(nodes: Sequence[Any], health: dict[str, NodeHealth], *, inventory: Sequence[Any] | None = None, + candidates: bool = False) -> None: + """A multi-node island's job port rates (in place): on a node without ``min_ib_gbps`` + (its checker holds the ports to that one), a port below half the fastest job port of + the nodes of its fabric group (one group: an inventory without ``fabric_group``) makes + the node bad. ``candidates``: ``nodes`` are the island's candidates (a shared inventory).""" + by_group: dict[str, list[Any]] = {} + grouped = _grouped(list(nodes if inventory is None else inventory)) + for node in nodes: + by_group.setdefault(str(node.fabric_group or "") if grouped else "", []).append(node) + whose = "candidate nodes" if candidates else "nodes" + for group, members in by_group.items(): + fastest = max((r for n in members for r in (health.get(n.name) or NodeHealth("")).rates.values()), + default=None) + if fastest is None: + continue + where = f" in fabric group {group}" if grouped and group else " without a fabric group" if grouped else "" + base = float(fastest) * RATE_FRACTION + for node in members: + h = health.get(node.name) + # a node with min_ib_gbps: its checker held its ports to it already (CudaChecker) + if h is None or h.state != "ok" or not h.rates or getattr(node, "min_ib_gbps", None) is not None: + continue + slow = [f"{label} rate {rate:g} < {base:g} Gb/s (half the fastest job port of the island's {whose}{where}, " + f"{fastest:g} Gb/s)" for label, rate in h.rates.items() if rate < base * 0.999] + if slow: + health[node.name] = NodeHealth("bad", "is not healthy: " + "; ".join(slow), h.rates) + + +def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck, + env: Mapping[str, str] | None = None, cache: Mapping[str, NodeHealth] | None = None, + inventory: Sequence[Any] | None = None, candidates: bool = False) -> None: + """The health of ``nodes`` into ``out.health`` (a node in ``cache`` is not checked again).""" + for node in nodes: + if node.name in out.health: + continue + cached = (cache or {}).get(node.name) + out.health[node.name] = cached if cached is not None else read_health(node, multi=multi, ssh=ssh, env=env) + if multi: + judge_rates(nodes, out.health, inventory=inventory, candidates=candidates) + + +def _health_problem(name: str, h: NodeHealth, *, force: bool, out: JoinCheck) -> str | None: + """The problem a node's health makes (None: none); notes and warnings into ``out``.""" + if h.state == "unchecked": + out.notes.append(f"node {name}: {h.text}") + return None + if h.state == "unread" and force: + out.warnings.append(f"node {name}: {h.text}; --force: it joins unchecked") + return None + return None if h.state == "ok" else f"node {name} {h.text}" if h.state == "bad" else f"node {name}: {h.text}" + + +# -- fabric and leases ---------------------------------------------------------------------------- + +def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck, *, inventory: Sequence[Any] | None = None) -> None: + """``inventory``: the whole inventory (whether it declares fabric groups at all).""" + ok, message, hint_only = _check_placement(nodes, need, inventory) + if not ok and not hint_only: + out.refusals.append(f"fabric: {message}") + elif message and (hint_only or not ok): + out.notes.append(f"fabric: {message}") + + +def lease_holders(nodes: Sequence[Any], *, lease_store: str, run_id: str, + out: JoinCheck) -> dict[str, str | None] | None: + """Who holds each node's lease (None: the store did not read: refused into ``out``).""" + try: + leases = _node_leases(lease_store, run_id) + except Exception as error: # noqa: BLE001 + out.refusals.append(f"lease store {lease_store}: {type(error).__name__}: {error}"[:300]) + return None + holders: dict[str, str | None] = {} + for node in nodes: + try: + holders[node.name] = leases.holder(node) + except Exception as error: # noqa: BLE001 - unknown is not free + out.refusals.append(f"node {node.name}: its lease does not read ({type(error).__name__}: {error})"[:300]) + return None if len(holders) < len(nodes) else holders + + +def lease_problem(holder: str | None, *, run_id: str, islands: Mapping[str, str]) -> str | None: + """Why a node held by ``holder`` is not the island's (None: free, or its own).""" + if holder is None or own_lease(holder, run_id): + return None + island = island_of_lease(holder, islands) + if island is not None: + return f"is island {island}'s (its launch holds the lease)" + from .node_lease import run_of # noqa: PLC0415 + + return f"is leased to run {run_of(holder) or holder}" + + +def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, out: JoinCheck, + islands: Mapping[str, str] | None = None) -> None: + """Every one of ``nodes`` free for the island (or its own) in ``lease_store``.""" + if not lease_store: + out.notes.append("no lease_store in the inventory: whether another run uses these nodes is not checked") + return + holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) + for node in nodes if holders is not None else (): + why = lease_problem(holders[node.name], run_id=run_id, islands=islands or {}) + if why: + out.refusals.append(f"node {node.name} {why}") + + +# -- the check ------------------------------------------------------------------------------------ + +def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, + taken: Mapping[str, str] | None = None, islands: Mapping[str, str] | None = None, ssh: Any = None, + inventory: Sequence[Any] | None = None, env: Mapping[str, str] | None = None, force: bool = False, + health: Mapping[str, NodeHealth] | None = None, + aliases: Mapping[str, tuple[str, str]] | None = None) -> JoinCheck: + """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: a node key + (:func:`node_keys`) -> the fleet island whose inventory lists it (an inventory without + ``lease_store``); ``islands``: the fleet's other islands' launch prefix -> island (whose + leases are theirs); ``inventory``: the whole inventory (default ``nodes``); ``env``: the + island's own environment; ``force``: a check that does not read is a warning; + ``health``: node health already read (a recheck). With ``lease_store``, ``taken`` holds the + nodes of the islands whose inventory has no ``lease_store`` or another one (their leases + are not in this store); ``aliases``: a machine key (SSH target / address) -> (island, its + node name) of the islands on the same ``lease_store`` (a lease is taken by node name: the + same machine under another name is not exclusive).""" + out = JoinCheck() + if ssh is None: + from .ssh_trainer_island import SshOps # noqa: PLC0415 + + ssh = SshOps() + every = list(nodes if inventory is None else inventory) + if not lease_store: + _check_listed(nodes, need=need, taken=taken or {}, ssh=ssh, env=env, force=force, health=health, out=out, + inventory=every) + else: + _check_leased(nodes, need=need, run_id=run_id, lease_store=lease_store, islands=islands or {}, ssh=ssh, + env=env, force=force, health=health, out=out, inventory=every, taken=taken or {}, + aliases=aliases or {}) + if out.refusals: + out.nodes = [] + return out + + +def _check_listed(nodes: Sequence[Any], *, need: int, taken: Mapping[str, str], ssh: Any, env: Any, force: bool, + health: Any, out: JoinCheck, inventory: Sequence[Any]) -> None: + """An inventory without ``lease_store``: its trainer nodes are the island's.""" + if len(nodes) != need: + out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " + f"{[n.name for n in nodes]}") + return + for node in nodes: + owner = next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) + if owner: + out.refusals.append(f"node {node.name} is island {owner}'s") + check_health(nodes, multi=need > 1, ssh=ssh, out=out, env=env, cache=health, inventory=inventory) + for node in nodes: + problem = _health_problem(node.name, out.health[node.name], force=force, out=out) + if problem: + out.refusals.append(problem) + try: + check_fabric(nodes, need, out, inventory=inventory) + except Exception as error: # noqa: BLE001 - the check that cannot run refuses + out.refusals.append(f"fabric: the placement check could not run ({type(error).__name__}: {error})"[:300]) + check_leases(nodes, lease_store=None, run_id="", out=out) + out.nodes = [n.name for n in nodes] + + +def _owner(node: Any, taken: Mapping[str, str]) -> str | None: + return next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) + + +SHARED_STORE_FIX = "give both islands the same lease_store, or use inventories without shared nodes" +ALIAS_FIX = "give the machine one name in both inventories, or use inventories without shared nodes" + + +def _foreign(node: Any, taken: Mapping[str, str], + aliases: Mapping[str, tuple[str, str]]) -> tuple[str, str, str] | None: + """``(island, detail, fix)`` when ``node`` is another island's machine that this lease + store does not keep from the launch: an island on no or another lease store, or one on + this store that names the machine otherwise.""" + owner = _owner(node, taken) + if owner: + return owner, "", SHARED_STORE_FIX + for key in sorted(node_keys(node)): + island, other = aliases.get(key, (None, None)) + if island is not None and other != node.name: + return island, f" (its node {other}, the same machine)", ALIAS_FIX + return None + + +def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str, islands: Mapping[str, str], + ssh: Any, env: Any, force: bool, health: Any, out: JoinCheck, inventory: Sequence[Any], + taken: Mapping[str, str], aliases: Mapping[str, tuple[str, str]]) -> None: + """An inventory with ``lease_store``: ``need`` of its trainer nodes, as the launch picks them. + + The launch (``lease_trainer_nodes`` / ``pick_nodes``) runs under a new holder (a new + run dir: a new identity, ``-m`` after a move), so no node is its own yet: it + skips the nodes another holder leases and places the island in the inventory's order on + the free ones (the free and the earlier incarnation's ones when too few are free); were + those taken meanwhile, on the rest. It sees another island's nodes that this store does + not lease (:func:`_foreign`) as free: a pick that takes one refuses. Every candidate node + must be healthy (a pick may come to any of them).""" + if len(nodes) < need: + out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " + f"{[n.name for n in nodes]}") + return + holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) + if holders is None: + return + held = {n.name: why for n in nodes if (why := lease_problem(holders[n.name], run_id=run_id, islands=islands))} + foreign = {n.name: f for n in nodes if n.name not in held and (f := _foreign(n, taken, aliases))} + launch = [n for n in nodes if n.name not in held] # what the launch may take: free or the earlier incarnation's + usable = [n for n in launch if n.name not in foreign] + check_health(usable, multi=need > 1, ssh=ssh, out=out, env=env, cache=health, inventory=inventory, + candidates=True) + sick = {} + for node in usable: + problem = _health_problem(node.name, out.health[node.name], force=force, out=out) + if problem: + sick[node.name] = problem + why = {**held, **{name: f"is island {island}'s{detail}" for name, (island, detail, _) in foreign.items()}} + left_out = [f"node {n.name} {why[n.name]}" if n.name in why else sick[n.name] + for n in nodes if n.name in why or n.name in sick] + grouped = need > 1 and _grouped(inventory) + if need > 1 and not grouped: + from .fabric_groups import HINT # noqa: PLC0415 + + out.notes.append(f"fabric: {HINT}") + try: + _pick_placement([n for n in usable if n.name not in sick], need, inventory) + except Exception as error: # noqa: BLE001 - no fit (PlacementError), or the check that cannot run + fit = type(error).__name__ == "PlacementError" + out.refusals += left_out + [(f"fabric: {error}" if grouped else + f"{len(usable) - len(sick)} of {len(nodes)} trainer node(s) are free and " + f"healthy, {need} needed") if fit else + f"fabric: the placement check could not run ({type(error).__name__}: {error})"] + return + free = [n for n in launch if holders[n.name] is None] + picks: list[list[Any]] = [] + for offered in (free, launch): # the first pick: the free nodes, else with the earlier incarnation's + try: + picks.append(_pick_placement(offered, need, inventory)) + break + except Exception: # noqa: BLE001 - too few: the launch waits for the next ones + continue + try: # were those taken meanwhile: the rest + picks.append(_pick_placement([n for n in launch if n not in picks[0]], need, inventory)) + except Exception: # noqa: BLE001 - too few left: the launch waits + pass + if sick: + out.refusals += list(sick.values()) + [ + f"the island's launch picks its nodes by their leases and may take {', '.join(sick)}; take " + "such a node out of the inventory's trainer nodes (roles) or clear its fault"] + hit: dict[tuple[str, str, str], list[str]] = {} + for name in dict.fromkeys(n.name for pick in picks for n in pick if n.name in foreign): + hit.setdefault(foreign[name], []).append(name) + for (island, detail, fix), taken_names in hit.items(): + out.refusals.append(f"launch would take {', '.join(taken_names)}, island {island}'s{detail}: {fix}") + if out.refusals: + return + out.notes += [f"left out: {w}" for w in left_out] + out.nodes = [n.name for n in picks[0]] + + +def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str], + lease_store: str | None = None) -> dict[str, str]: + """Node key (:func:`node_keys`) -> island, for the ``ssh:`` trainer islands of the desired + state other than ``other_than`` (their inventories' trainer nodes). ``lease_store``: the + new island's; an island whose inventory has the same one is left out (its leases say + which nodes it holds).""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + out: dict[str, str] = {} + for name, member in dz.trainers(dict(doc)).items(): + if name == other_than or not str(member.get("gpu") or "").startswith("ssh:"): + continue + path = inventory_of([*fleet_argv, *(member.get("argv") or ())]) + if path is None: + continue + try: + listed = load_inventory(path) + except Exception as error: # noqa: BLE001 - its nodes unknown: said, not taken as free + raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None + if lease_store is not None and store_key(getattr(listed, "lease_store", None)) == store_key(lease_store): + continue + for node in role_nodes(listed, "trainer"): + for key in node_keys(node): + out.setdefault(key, name) + return out + + +def store_key(uri: str | None) -> str | None: + """A lease store URI in one spelling (``file:///x`` and ``/x`` are one store; no trailing ``/``).""" + if uri is None: + return None + text = str(uri).strip() + if text.startswith("file://"): + text = text[len("file://"):] + return text.rstrip("/") or text + + +def aliases_of(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str], + lease_store: str | None) -> dict[str, tuple[str, str]]: + """Machine key (SSH target / address of :func:`node_keys`) -> (island, node name), for + the ``ssh:`` islands whose inventory has the lease store ``lease_store``.""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + out: dict[str, tuple[str, str]] = {} + if lease_store is None: + return out + for name, member in dz.trainers(dict(doc)).items(): + if name == other_than or not str(member.get("gpu") or "").startswith("ssh:"): + continue + path = inventory_of([*fleet_argv, *(member.get("argv") or ())]) + if path is None: + continue + try: + listed = load_inventory(path) + except Exception as error: # noqa: BLE001 + raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None + if store_key(getattr(listed, "lease_store", None)) != store_key(lease_store): + continue + for node in role_nodes(listed, "trainer"): + for key in node_keys(node) - {f"name:{node.name}"}: + out.setdefault(key, (name, node.name)) + return out + + +def fleet_prefixes(doc: Mapping[str, Any], *, other_than: str) -> dict[str, str]: + """Launch prefix -> island, for the trainer islands of the desired state other than ``other_than``.""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + return {str(m["prefix"]): name for name, m in dz.trainers(dict(doc)).items() + if name != other_than and m.get("prefix")} + + +def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_argv: Sequence[str], run_id: str, + ssh: Any = None, log: Callable[[str], None] | None = None, force: bool = False, + health: Mapping[str, NodeHealth] | None = None, seen: Iterable[str] = ()) -> JoinCheck: + """:func:`check` of an island's trainer member (added, or moved) against the desired + state ``doc`` (its other islands). ``seen``: notes and warnings printed already (a + recheck prints only the new ones).""" + say = log or (lambda m: print(m, file=sys.stderr)) + argv = [*fleet_argv, *(member.get("argv") or ())] + from .node_inventory import lease_store_of, load_inventory # noqa: PLC0415 + + nodes, need, path = island_nodes(argv, str(member["gpu"])) + inventory = load_inventory(path) + store = lease_store_of(inventory) + name = str(member["name"]) + result = check(nodes, need=need, run_id=run_id, lease_store=store, + taken=taken_nodes(doc, other_than=name, fleet_argv=fleet_argv, lease_store=store), + aliases=aliases_of(doc, other_than=name, fleet_argv=fleet_argv, lease_store=store), + islands=fleet_prefixes(doc, other_than=name), ssh=ssh, inventory=inventory, + env=island_env_of(argv), force=force, health=health) + shown = set(seen) + for note in result.notes: + if note not in shown: + say(f"fleet island: note: island {name}: {note}") + for warning in result.warnings: + if warning not in shown: + say(f"fleet island: WARNING: island {name}: {warning}") + return result + + +def names(nodes: Iterable[str]) -> str: + return ", ".join(nodes) or "none" diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py new file mode 100644 index 000000000..cb4bda816 --- /dev/null +++ b/yeto/launch/island_straggler.py @@ -0,0 +1,567 @@ +"""Island stragglers of an island pool: a running island none of whose pushes was merged in +N merge cycles (``island_straggler``). + +The syncer already keeps such an island from holding the others: a pool round whose quorum +deadline passes merges the pushes that arrived, the silent island is recorded absent and +excused from the next rounds, and once it delivers again it is caught up and merged again. +What nobody said so far is that an island has stopped contributing: it heartbeats, its +launch is up, and the fleet controller sees nothing wrong. This module watches the syncer's +merges and tells the controller, which writes the event and decides what to do (wait, the +default, or a replacement the island's provider offers). + +* **What is counted.** The syncer's tape (its ``outer_step`` records; ``pool_join`` for the + start of an island). A merge cycle is one outer step of every fragment: with P fragments + (the distinct ``fragment`` ids merged so far, 1 for a non-fragment pool) an island is a + straggler once ``N x P`` merges in a row went by without a push of it in their weights. + A push the syncer refused, or one still in flight, is not merged and does not count. +* **Only this launch's history.** The watch ignores records stamped (``time_unix``) more than + :data:`CLOCK_SKEW_S` before its own start (the launcher's and the syncer host's clocks may + differ that much), and reads the run store's copy from the tail of the furthest syncer + incarnation it finds at its first read: a relaunched or moved island's new launch never + counts the merges its earlier launches missed. No other decision reads a clock. +* **When counting starts.** At the island's first ``pool_join`` read by this watch, or at the + first merge that lists it ``absent`` (the syncer expects it: an island a restarted launcher + adopted joined before this watch), or at its first merged push. Only its controller resets + the count: when the island leaves running (recovering, draining, stopped) it starts again + once it runs again, from its next join for a new incarnation (a relaunch; a join written + before the controller holds it running counts) or at once for the same one. A ``pool_join`` + of a reconnect (each connection is a new generation) or of a syncer that took over (a new + term) keeps the count and the mark. A merged push of the island resets the count. +* **Who is watched.** The islands the controller holds running (not draining, not + recovering): it passes their learner ids with a token of the incarnation. +* **Signals.** One :class:`Straggler` when an island crosses the threshold, and one + ``cleared`` signal when a push of it is merged again, when it was relaunched, or when it + stopped running (recovering, draining, ended): the controller writes one event per stretch + and closes each one. + +Sources (:func:`tape_source`): the syncer's tape file on this host (a head-mode syncer), or +its copy in the run store (``tapes/syncer//.jsonl``, uploaded every 30 s +by ``yeto.rl.engine.tape_upload``). A store read costs at most :data:`STORE_LISTS_PER_POLL` +listings of one incarnation's prefix after its last chunk read and :data:`STORE_GETS_PER_POLL` +chunk reads, and starts no new request after :data:`STORE_POLL_BUDGET_S`. Finding the syncer's +incarnations costs one listing page per incarnation, at the first read, every +:data:`STORE_DISCOVER_POLLS` reads and while none is known; the first read also lists each +incarnation once and reads its last chunk, for its tail. A source that does not read is skipped +for that poll; nothing here ever stops or slows the fleet. When nothing can be watched (no tape +to read, the watch turned off), or the tape goes silent for :data:`QUIET_POLLS` reads after its +first record about this launch's islands, the controller is given one notice +(``island_straggler_unavailable``), and one more when records are read again +(``island_straggler_available``). +""" + +from __future__ import annotations + +import json +import os +import time +from collections.abc import Callable, Mapping +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + +EVENT = "island_straggler" +CLEARED_EVENT = "island_straggler_cleared" +UNAVAILABLE_EVENT = "island_straggler_unavailable" +AVAILABLE_EVENT = "island_straggler_available" # the syncer's records are read again after a silent stretch +DEFAULT_CYCLES = 3 +SYNCER_TAPES = "tapes/syncer/" +STORE_POLL_S = 30.0 # the syncer's uploads are 30 s apart (tape_upload.DEFAULT_INTERVAL_S) +STORE_GETS_PER_POLL = 16 # chunk reads per poll; the rest waits for the next poll +STORE_LISTS_PER_POLL = 4 # listings of the incarnation being read per poll +STORE_DISCOVER_POLLS = 10 # a full listing of tapes/syncer/ (a restarted syncer) every this many reads +STORE_POLL_BUDGET_S = 5.0 # no new store request after this long in one poll +MAX_READ_BYTES = 8 << 20 # one poll reads at most this much of a local tape +QUIET_POLLS = 10 # reads without a syncer record, after the first one of this launch's islands, before that is said +CLOCK_SKEW_S = 600.0 # the launcher's and the syncer host's clocks may differ by this much + +WAIT = "wait" # the syncer merges without it; it is caught up once it delivers again +REPLACE = "replace" # the island's provider replaces it (its own policy decides) +ACTIONS = (WAIT, REPLACE) + + +def straggler_cycles(args: Any) -> int: + """``--rl-island-straggler-cycles`` (N >= 0; 0 turns the watch off), default + :data:`DEFAULT_CYCLES`.""" + value = getattr(args, "rl_island_straggler_cycles", None) + if value is None: + return DEFAULT_CYCLES + if isinstance(value, bool) or int(value) != value or int(value) < 0: + raise ValueError(f"--rl-island-straggler-cycles must be a whole number >= 0 (got {value!r})") + return int(value) + + +@dataclass(frozen=True) +class Straggler: + """One signal about island ``island`` (its learner id).""" + + island: int + cleared: bool # False: it became a straggler; True: its stretch ended (``reason`` says how) + missed_cycles: int # whole merge cycles since its last merged push (or its join) + merges: int # merges since then + fragments: int # P + cycles: int # N, the threshold + newest_step: int | None # the newest merged step the syncer recorded + last_merged_step: int | None # the newest step a push of the island was merged into + absent: bool # the newest merge listed it absent (expected, not answered) + reason: str = "" + + def fields(self) -> dict[str, Any]: + out = asdict(self) + out.pop("island") + out.pop("cleared") + return out + + +@dataclass +class _Island: + joined: bool = False + misses: int = 0 + last_merged_step: int | None = None + absent: bool = False + flagged: bool = False + token: Any = None + away: bool = False # not running now (recovering, draining, ended): its count restarts + was_joined: bool = False # whether it was in the pool when it left running + joined_away: bool = False # a pool_join read while it was away (its next incarnation's, or a reconnect) + + +def _time(record: Mapping[str, Any]) -> float | None: + value = record.get("time_unix") + if isinstance(value, bool): + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +@dataclass +class StragglerTracker: + """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc). + ``since``: the watch's start (wall time); a record stamped more than + :data:`CLOCK_SKEW_S` before it is an earlier launch's history and is ignored.""" + + cycles: int = DEFAULT_CYCLES + since: float | None = None + clock: Callable[[], float] = time.time + islands: dict[int, _Island] = field(default_factory=dict) + fragments: set[int] = field(default_factory=set) + newest_step: int | None = None + + def _island(self, k: int) -> _Island: + return self.islands.setdefault(int(k), _Island()) + + @property + def per_cycle(self) -> int: + return max(1, len(self.fragments)) + + def _history(self, t: float | None) -> bool: + """Stamped before the watch started, beyond the clock skew allowed between hosts.""" + return t is not None and self.since is not None and t < self.since - CLOCK_SKEW_S + + def feed(self, record: Mapping[str, Any]) -> None: + kind = record.get("kind") + if kind not in ("pool_join", "outer_step") or self._history(_time(record)): + return + if kind == "pool_join": + island = _int(record.get("island_id")) + if island is None: + return + # in the pool; a reconnect (a new connection generation) or a new syncer term keeps + # its count and its mark: only its controller's relaunch or stop restarts them + state = self._island(island) + state.joined = True + state.joined_away = state.joined_away or state.away + return + step, fragment = _int(record.get("step")), _int(record.get("fragment")) + if fragment is not None: + self.fragments.add(fragment) + if step is not None: + self.newest_step = step if self.newest_step is None else max(self.newest_step, step) + merged = {_int(entry[0]) for entry in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + absent = {_int(i) for i in record.get("absent") or () if _int(i) is not None} + for k in (merged | absent) - set(self.islands) - {None}: + self.islands[k] = _Island() + for k, state in self.islands.items(): + if k in merged: + state.misses, state.absent = 0, False + state.last_merged_step = step if step is not None else state.last_merged_step + state.joined = True # a merged push: it is in the pool + elif state.joined or k in absent: + # listed absent: the syncer expects it, so it is in the pool even when its join + # came before this watch (an island adopted by a restarted launcher) + state.joined = True + state.misses += 1 + state.absent = k in absent + + def check(self, running: Mapping[int, Any]) -> list[Straggler]: + """The signals for the islands held running (learner id -> incarnation token), and + the end of the stretch of a flagged island that is not running any more.""" + out: list[Straggler] = [] + threshold = self.cycles * self.per_cycle + for k, state in self.islands.items(): + if k in running or state.token is None or state.away: + continue + # it left running: its count restarts when it is running again + if state.flagged: + out.append(self._signal(k, state, cleared=True, reason="not running")) + was_joined = state.joined + self._restart(state) + state.away, state.was_joined, state.joined_away = True, was_joined, False + for k, token in running.items(): + state = self._island(int(k)) + if state.away: + # back: the same incarnation keeps its place in the pool; a new one (relaunched) + # is in it once it joined, which may come before its controller holds it running + state.joined = state.joined_away or (state.token == token and state.was_joined) + state.misses, state.absent = 0, False + elif state.token is not None and state.token != token: + # relaunched between two checks: its count starts at its next join + if state.flagged: + out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) + self._restart(state) + state.token, state.away, state.joined_away = token, False, False + if self.cycles <= 0 or not state.joined: + continue + if not state.flagged and state.misses >= threshold: + state.flagged = True + out.append(self._signal(int(k), state, cleared=False, + reason=f"no push merged in {state.misses // self.per_cycle} merge cycle(s) " + f"({state.misses} merges over {self.per_cycle} fragment(s))")) + elif state.flagged and state.misses < threshold: + state.flagged = False + out.append(self._signal(int(k), state, cleared=True, reason="a push of it is merged again")) + for k, state in self.islands.items(): + if k not in running and state.flagged: # never held running here + state.flagged = False + out.append(self._signal(k, state, cleared=True, reason="not running")) + return out + + @staticmethod + def _restart(state: _Island) -> None: + state.joined, state.misses, state.absent, state.flagged = False, 0, False, False + + def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: + return Straggler(island=k, cleared=cleared, missed_cycles=state.misses // self.per_cycle, + merges=state.misses, fragments=self.per_cycle, cycles=self.cycles, + newest_step=self.newest_step, last_merged_step=state.last_merged_step, + absent=state.absent, reason=reason) + + +def _int(value: Any) -> int | None: + if isinstance(value, bool): + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _entries(value: Any) -> list: + return [e for e in value or () if isinstance(e, (list, tuple)) and e] + + +# -- the syncer's tape --------------------------------------------------------------------- + +class FileTape: + """The syncer's tape file on this host: the complete lines added since the last read.""" + + def __init__(self, path: str | os.PathLike[str], *, offset: int = 0) -> None: + self.path = Path(os.path.expanduser(str(path))) + self.offset = int(offset) # a reused host's tape: what an earlier syncer job wrote is not read + self.label = str(self.path) + self.error: str | None = None + self.polled = True # every call reads + + def read(self) -> list[dict[str, Any]]: + try: + size = self.path.stat().st_size + except FileNotFoundError: + return [] + if size < self.offset: # rewritten from the start: read it again + self.offset = 0 + if size == self.offset: + return [] + with self.path.open("rb") as handle: + handle.seek(self.offset) + data = handle.read(MAX_READ_BYTES) + end = data.rfind(b"\n") + if end < 0: + return [] + self.offset += end + 1 + return _records(data[: end + 1]) + + +def _progress(records: list[dict[str, Any]]) -> tuple[int, int]: + """How far a syncer got in ``records``: its newest term (``syncer_epoch``) and step. A + restarted syncer resumes at its checkpoint's step or takes over in a new term, so the + newest incarnation is the furthest one; no clock is read.""" + epochs = [e for e in (_int(r.get("syncer_epoch")) for r in records) if e is not None] + steps = [s for s in (_int(r.get("step")) for r in records) if s is not None] + return (max(epochs, default=-1), max(steps, default=-1)) + + +class StoreTape: + """The syncer's tape in the run store (``tapes/syncer//.jsonl``). + + The first read establishes the tail: it lists every syncer incarnation, reads each one's + last chunk, and starts at the tail of the furthest one (the newest term, then the newest + step; :func:`_progress`): what the syncer wrote before this watch is not read. Until that + worked (a listing or a read failed) every read tries it again and reads nothing else. From + then on each read lists the current incarnation's prefix after its last chunk read + (``start_after``) and reads its new chunks in order, at most :data:`STORE_GETS_PER_POLL` + (the rest at the next read). An incarnation found later (a restarted syncer, by a full + listing every :data:`STORE_DISCOVER_POLLS` reads) did not exist at the first read: it is + read from its start once the current one has no chunk left. A chunk read moves the cursor + past it, so a request that fails keeps what was read before it and is tried again at the + next read (``error`` says why); no chunk is read twice or skipped.""" + + def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, + clock: Callable[[], float] | None = None, gets_per_poll: int = STORE_GETS_PER_POLL, + discover_polls: int = STORE_DISCOVER_POLLS, budget_s: float = STORE_POLL_BUDGET_S) -> None: + self.objects = objects + self.interval_s = float(interval_s) + self.clock = clock or time.monotonic + self.gets_per_poll, self.discover_polls, self.budget_s = int(gets_per_poll), int(discover_polls), budget_s + self.queue: list[str] = [] # the incarnations to read, the current one first + self.known: set[str] = set() + self.cursors: dict[str, str] = {} # incarnation -> its last chunk read + self.label = f"{getattr(objects, 'uri', 'store')}/{SYNCER_TAPES}" + self.error: str | None = None + self.polled = False # whether the last read() asked the store (False within the interval) + self.tailed = False # the first read's tail is established + self.reads = 0 + self.requests = 0 # listings and chunk reads so far + self._next: float | None = None + + def _incarnations(self) -> set[str]: + """The syncer incarnations under ``tapes/syncer/``: one listing page per incarnation + (a page that ends inside one jumps past the rest of its chunks).""" + page = getattr(self.objects, "list_page", None) + if not callable(page): + self.requests += 1 + return {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in self.objects.list(SYNCER_TAPES) + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + found: set[str] = set() + cursor = "" + while True: + self.requests += 1 + keys, last = page(SYNCER_TAPES, start_after=cursor, limit=1000) + found |= {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in keys + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + if last is None or not keys: + return found + cursor = f"{SYNCER_TAPES}{str(last)[len(SYNCER_TAPES):].split('/')[0]}/~" # past its chunks + + def _tail(self) -> None: + """The first read: every incarnation's tail, and the furthest one to read from. + Committed only when every request worked (else tried again at the next read).""" + cursors, progress = {}, {} + for inc in sorted(self._incarnations()): + self.requests += 1 + chunks = sorted(str(k) for k in self.objects.list(f"{SYNCER_TAPES}{inc}/") if str(k).endswith(".jsonl")) + cursors[inc] = chunks[-1] if chunks else "" + data = None + if chunks: + self.requests += 1 + data = self.objects.read(chunks[-1]) + records = _records(data if isinstance(data, bytes) else str(data or "").encode()) + progress[inc] = (*_progress(records), inc) + self.cursors.update(cursors) + self.known.update(cursors) + self.queue = [max(progress, key=progress.__getitem__)] if progress else [] + self.tailed = True + + def _discover(self) -> None: + new = sorted(inc for inc in self._incarnations() if inc not in self.known) + self.known.update(new) # not there at the first read: newer than every one that was + self.queue += new + + def read(self) -> list[dict[str, Any]]: + now = self.clock() + self.polled = False + if self._next is not None and now < self._next: + return [] + self._next = now + self.interval_s + self.polled, self.error = True, None + started, out, gets, lists = self.clock(), [], 0, 0 + self.reads += 1 + try: + if not self.tailed: + self._tail() + return [] + if not self.queue or self.reads % self.discover_polls == 0: + self._discover() + while self.queue and gets < self.gets_per_poll and lists < STORE_LISTS_PER_POLL \ + and self.clock() - started < self.budget_s: + inc = self.queue[0] + lists += 1 + self.requests += 1 + keys = sorted(str(k) for k in self.objects.list(f"{SYNCER_TAPES}{inc}/", + start_after=self.cursors.get(inc, "")) + if str(k).endswith(".jsonl") and str(k) > self.cursors.get(inc, "")) + if not keys: + if len(self.queue) > 1: + self.queue.pop(0) # a newer syncer incarnation took over: read it from its start + continue + break + for key in keys: + if gets >= self.gets_per_poll or self.clock() - started >= self.budget_s: + break + gets += 1 + self.requests += 1 + data = self.objects.read(key) + self.cursors[inc] = key + if data: + out += _records(data if isinstance(data, bytes) else str(data).encode()) + else: + continue + break + except Exception as error: # noqa: BLE001 - what was read is kept; the rest at the next read + self.error = f"{type(error).__name__}: {error}"[:300] + return out + + +def _records(data: bytes) -> list[dict[str, Any]]: + out = [] + for line in data.splitlines(): + try: + record = json.loads(line) + except (ValueError, UnicodeDecodeError): + continue + if isinstance(record, dict): + out.append(record) + return out + + +class StragglerWatch: + """A tracker fed from one source: :meth:`poll` reads what the syncer added and returns + the signals for the islands held running. A read that fails is logged once per stretch + of failures and tried again at the next poll. :meth:`notices` hands the controller + ``(event, reason)`` pairs to write: once the syncer recorded something about this launch's + islands (a join, or a merge that merged or expected one), :data:`QUIET_POLLS` reads in a + row without any record are said once (:data:`UNAVAILABLE_EVENT`), and the next record read + takes it back (:data:`AVAILABLE_EVENT`). A fleet whose trainers start slowly is never said + to be unavailable: nothing is counted before that first record.""" + + def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, since: float | None = None, + log: Callable[[str], None] | None = None, clock: Callable[[], float] = time.time) -> None: + import sys + + self.source = source + self.tracker = StragglerTracker(cycles=int(cycles), since=since, clock=clock) + self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self._failing = False + self._seen = False # a record about one of this launch's islands was read + self._quiet = 0 # reads in a row without a record since then + self._said = False # the silence was said (UNAVAILABLE_EVENT) and not taken back yet + self._notices: list[tuple[str, str]] = [] + + @staticmethod + def _about(record: Mapping[str, Any], islands: Any) -> bool: + if record.get("kind") == "pool_join": + return _int(record.get("island_id")) in islands + if record.get("kind") == "outer_step": + named = {_int(e[0]) for e in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + named |= {_int(i) for i in record.get("absent") or ()} + return bool(named & set(islands)) + return False + + def poll(self, running: Mapping[int, Any]) -> list[Straggler]: + try: + records = self.source.read() + error = getattr(self.source, "error", None) + except Exception as raised: # noqa: BLE001 - a watch, never the end of supervision + records, error = [], f"{type(raised).__name__}: {raised}" + if error is not None: + if not self._failing: + self.log(f"[launcher] island straggler watch: the syncer tape {self.source.label} does not read " + f"({error}); tried again next poll"[:400]) + self._failing = True + else: + self._failing = False + for record in records: + self.tracker.feed(record) + islands = {int(k) for k in running} | {k for k, s in self.tracker.islands.items() if s.token is not None} + self._seen = self._seen or any(self._about(r, islands) for r in records) + if records: + self._quiet = 0 + if self._said: + self._said = False + self._notices.append((AVAILABLE_EVENT, f"syncer records read again from {self.source.label}")) + elif self._seen and running and getattr(self.source, "polled", True): + self._quiet += 1 + if self._quiet == QUIET_POLLS and not self._said: + self._said = True + why = (f"no syncer record read from {self.source.label} in {QUIET_POLLS} reads; no straggler is " + "reported until the syncer's tape is read again") + self.log(f"[launcher] WARNING: island straggler watch: {why}") + self._notices.append((UNAVAILABLE_EVENT, why)) + return self.tracker.check(running) + + def notices(self) -> list[tuple[str, str]]: + out, self._notices = self._notices, [] + return out + + +class UnavailableWatch: + """An island pool whose stragglers cannot be watched from here: no signal ever, and one + notice saying why (the controller writes it as ``island_straggler_unavailable``).""" + + def __init__(self, reason: str) -> None: + self.reason = reason + self._notices = [(UNAVAILABLE_EVENT, reason)] + + def poll(self, running: Mapping[int, Any]) -> list[Straggler]: + return [] + + def notices(self) -> list[tuple[str, str]]: + out, self._notices = self._notices, [] + return out + + +def tape_source(*, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None) -> Any: + """The syncer tape this controller can read: the local file of a syncer on this host, + else the run store's copy; None when neither is there.""" + if local_tape: + return FileTape(local_tape, offset=local_offset) + if objects is not None: + return StoreTape(objects) + return None + + +def watch_for(args: Any, *, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None, log: Callable[[str], None] | None = None, + no_source: str | None = None) -> StragglerWatch | UnavailableWatch | None: + """The launcher's watch of an island pool (``--rl-island-straggler-cycles``, default 3; + 0 turns it off): None without an island pool. With the watch off, or with no syncer + tape to read from here (``no_source``: why), an :class:`UnavailableWatch` that says so + once. The watch counts only what the syncer records from now on.""" + import sys + + from .syncer import island_pool + + if getattr(args, "training_mode", "sft") != "rl" or not island_pool(args): + return None + say = log or (lambda m: print(m, file=sys.stderr, flush=True)) + cycles = straggler_cycles(args) + if cycles == 0: + say("[launcher] island straggler watch off (--rl-island-straggler-cycles 0)") + return UnavailableWatch("turned off (--rl-island-straggler-cycles 0)") + source = tape_source(local_tape=local_tape, local_offset=local_offset, objects=objects) + if source is None: + why = no_source or "no syncer tape to read here (a syncer on this host, or the run store's tapes/syncer/)" + say(f"[launcher] island straggler watch off: {why}") + return UnavailableWatch(why) + say(f"[launcher] island straggler watch: an island none of whose pushes is merged in {cycles} merge " + f"cycle(s) is reported ({EVENT}); syncer tape {source.label}") + return StragglerWatch(source, cycles=cycles, since=time.time(), log=log) + + +def signal_fields(signal: Straggler, action: str | None) -> dict[str, Any]: + """The event's and the island record's fields of ``signal``.""" + out = signal.fields() + if action is not None: + out["action"] = action + return out diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index 44f82ffd4..7065421dc 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -79,6 +79,11 @@ share one group; a file without any ``fabric_group`` key places islands as before. ``fabric_group: unavailable`` (reserved) marks a node the probe found without RDMA to the others: it never joins a multi-node island, a single-node one takes it. +``min_ib_gbps`` is the least rate (Gb/s) of each port a multi-node job uses on the node: +the ports its ``NCCL_IB_HCA`` names, else every active port of the node's fabric that NCCL +takes. The node health check of a running trainer island (``yeto.hw.node_health``) holds +them to it and to their rate at its first check, whichever is higher; the join check of an +island added at run time (:mod:`.island_join`), which has no earlier check, to it alone. An NVIDIA (``cuda``) multi-node island over ``ib`` / ``roce``, e.g. 6 x 8 B300 (with ``--model-store local:///data/models --model-store-source s3://...`` the @@ -144,7 +149,7 @@ "host_memory_gib") _KNOWN = _REQUIRED + ("proxy_jump", "fabric", "interface", "address", "mounts", "image", "runtime", "docker_args", "env", "price_per_card_hour", "roles", "scratch", "scratch_min_free_gib", - "store_env_file", "node_health", "fabric_group") + "store_env_file", "node_health", "fabric_group", "min_ib_gbps") NODE_HEALTH_MODES = ("auto", "off") # node profile keys (unified-sampler-pool): parse_profile reads them, parse_node accepts and ignores them _PROFILE_KEYS = ("card_arch", "container", "paths", "model_source", "reach") @@ -240,6 +245,10 @@ class Node: # :mod:`.fabric_groups`); None: no fabric_group key; FABRIC_UNGROUPED (""): the key is # null; FABRIC_UNAVAILABLE: reserved, the node has no RDMA to the others fabric_group: str | None = None + # the least rate (Gb/s) of each port a multi-node job uses on the node (NCCL_IB_HCA's, else the + # fabric's active ports): the running health check also keeps its first-check rate, the join + # check has only this; None: not declared + min_ib_gbps: float | None = None @property def hbm_gib_per_node(self) -> float: @@ -492,6 +501,8 @@ def parse_node(raw: Any, *, index: int, images: Mapping[str, str] | None = None, store_env_file=store_env_file, node_health=parse_node_health(raw["node_health"], f"node {name}") if "node_health" in raw else node_health, fabric_group=fabric_group, + min_ib_gbps=(_require_positive(raw["min_ib_gbps"], name, "min_ib_gbps") + if raw.get("min_ib_gbps") is not None else None), ) try: node.compat_group # noqa: B018 - an unknown HBM variant fails here, not at launch diff --git a/yeto/launch/rl_args.py b/yeto/launch/rl_args.py index f1e6c473e..9601b2cff 100644 --- a/yeto/launch/rl_args.py +++ b/yeto/launch/rl_args.py @@ -842,6 +842,9 @@ def _check_island_pool(args, *, num_islands: int) -> None: if int(getattr(args, "syncer_shards", None) or 1) > 1: raise ValueError("membership options need one syncer (no --syncer-shards > 1)") check_stale_lag(args) + from .island_straggler import straggler_cycles + + straggler_cycles(args) # --rl-island-straggler-cycles: a whole number >= 0 max_learners = getattr(args, "rl_sync_max_learners", None) if max_learners is not None: # full-parameter: the islands bind the roster 0..N-1 into their session diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index 6b70b20b0..2d80e73b6 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -250,6 +250,7 @@ def _health_watches(self, spec: SshTrainerSpec) -> dict[int, Any]: env = {**dict(node.env), **dict(spec.env)} # the job's own order (node_env): the island's wins out[rank] = node_health.HealthWatch(node.device_family, hcas=node_health.hcas_of(env.get("NCCL_IB_HCA")), multi=len(spec.nodes) > 1, expect_gpus=node.cards_per_node, + min_ib_gbps=getattr(node, "min_ib_gbps", None), clock=time.time, every_s=self.health_every_s, fabric=node.fabric if node.fabric in RDMA_FABRICS else None) return out diff --git a/yeto/launcher.py b/yeto/launcher.py index 7b76ee929..3d0a402ac 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -690,6 +690,37 @@ def reader(): resolve_island_syncer_epoch(args, reader(), **({} if timeout_s is None else {"timeout_s": timeout_s})) +def _island_straggler_watch(args, island_states, local_syncer): + """``yeto.launch.island_straggler``'s watch of an island pool's merges: the syncer's tape + of a syncer on this host, else, for an island launch of a fleet launched island by island, + the copy its syncer launch uploads to an object run store (``tapes/syncer/``); None + without an island fleet's records (nothing is written then).""" + if island_states is None: + return None + from .launch.island_straggler import watch_for + from .launch.storage import is_object_store_uri + from .rl.engine.sample_roles import FLEET_ROLE_ISLAND, fleet_role + from .rl.engine.tape_upload import upload_interval_s + + store = str(getattr(args, "rl_checkpoint_store", None) or "") + if fleet_role(args) != FLEET_ROLE_ISLAND: + why = ("the fleet's syncer runs on a VM of its own and a launch of every island does not copy its tape " + "to the run store; run the syncer on this host (--controller head) or launch the fleet island by " + "island (fleet.launch per_island)") + elif upload_interval_s() is None: + why = "the syncer launch's tape upload is off (YETO_RL_TAPE_UPLOAD_S=0)" + elif not is_object_store_uri(store): + why = f"the run store {store or '(none)'} is not an object store: the syncer launch uploads no tape to it" + else: + why = None + try: + return watch_for(args, local_tape=getattr(local_syncer, "event_tape", None), + local_offset=int(getattr(local_syncer, "_event_offset", 0) or 0), + objects=getattr(island_states, "objects", None) if why is None else None, no_source=why) + except ValueError as error: + raise SystemExit(str(error)) from None + + def _island_state_store(args): """The run store's island records (None: no object API for the store, or none).""" from .launch.island_lifecycle import open_state_store @@ -1340,6 +1371,7 @@ def route_container(learner_id: int): "new_machine_retries": _recorded_new_machine_retries(recorder, name)} for name, a in adoption.items()}, deterministic_stop=deterministic_stop(args)[0], + straggler=_island_straggler_watch(args, island_states, local_syncer if head_mode else None), # why an island stopped, from its own tape records (a breaker, a strict check, a # refusal: never relaunched), not from its rank's exit status stop_probe=( diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index f24fbb652..d5be7b59e 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1039,6 +1039,11 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. help="with --rl-fleet-role syncer on a cluster: how long the syncer cluster may stay " "unreadable or not UP in a row before the syncer launch fails (and the fleet ends). " "It includes the time the sky API itself does not answer (default 300)"), + cli_flag("--rl-island-straggler-cycles", type=int, default=None, metavar="N", + help="island pool: the fleet controller reports a running island none of whose pushes " + "the syncer merged in N merge cycles (one outer step of every fragment) as " + "island_straggler, and again once it is merged again; the syncer keeps merging the " + "other islands at each quorum deadline. 0 turns the report off (default 3)"), cli_flag("--rl-sync-max-learners", type=int, default=None, metavar="N", help="membership: the syncer admits island ids 0..N-1, so islands may join " "after the launch (default: the launched islands; with the full-parameter " diff --git a/yeto/rl/fleet_islands.py b/yeto/rl/fleet_islands.py index e54764c4c..fc044a3a6 100644 --- a/yeto/rl/fleet_islands.py +++ b/yeto/rl/fleet_islands.py @@ -23,6 +23,10 @@ cluster); same learner id, same store sub-directory: the next launch continues from ``trainer/``. The syncer sees the island leave and come back (no RETIRE). +An ``ssh:`` island added, or moved onto ``ssh:`` nodes (``--inventory``: its node +inventory), passes the join checks of :mod:`yeto.launch.island_join` first (count, this +fleet, node health, fabric group, leases), and again on the desired state its write reads. + ``--dry-run`` writes nothing: it prints the change and runs the island launch's ``yeto launch --dry-run`` (an island whose layout differs from the fleet's is refused there, before anything is ordered). @@ -106,9 +110,11 @@ def next_learner_id(objects: Any, plan: Any, doc: dict[str, Any], name: str | No def compile_island(cfg: dict[str, Any], plan: Any, *, k: int, name: str, gpu: str, usd_per_h: float | None, - samplers: list[Any], island_argv: list[str] | None = None) -> tuple[dict[str, Any], list[dict]]: + samplers: list[Any], island_argv: list[str] | None = None, + inventory: str | None = None) -> tuple[dict[str, Any], list[dict]]: """The trainer member and the sampler pool members of a new island k, compiled as - :func:`yeto.rl.fleet.compile_fleet` compiles island k of the run config.""" + :func:`yeto.rl.fleet.compile_fleet` compiles island k of the run config. ``inventory``: + the node inventory of an ``ssh:`` island (its launch's ``--rl-node-inventory``).""" if not fleet_mod.NAME.fullmatch(str(name)): raise IslandChangeError(f"island name must be a word of letters, digits, '.', '_' or '-' (got {name!r})") where = f"island {name}" @@ -142,11 +148,23 @@ def compile_island(cfg: dict[str, Any], plan: Any, *, k: int, name: str, gpu: st argv = il.island_argv(trainer_argv, island, plan, learners=len(plan.islands), section_argv=il.island_section_argv(cfg, trainer_argv)) argv += il.member_table_flags(k) + if inventory is not None: + if not str(gpu).startswith("ssh:"): + raise IslandChangeError(f"{where}: --inventory is the node inventory of an ssh: island (--gpu {gpu})") + argv += ["--rl-node-inventory", inventory_path(inventory)] member = il.trainer_member(island, plan, argv, prefix=f"{il.fleet_prefix(trainer_argv)}-i{k}", fleet_shape=il.fleet_shape(trainer_argv)) return member, members +def inventory_path(inventory: str) -> str: + """An island's node inventory as its launch reads it: an absolute path (the trainer + worker and a later ``yeto fleet island`` run in other directories).""" + from pathlib import Path # noqa: PLC0415 + + return str(Path(str(inventory)).expanduser().resolve()) + + def run_budget_usd(cfg: dict[str, Any]) -> float | None: """The run's ``run.budget`` in dollars, wherever the run config sets it (``budget.usd`` or the ``breakers`` section), resolved as ``yeto run up`` resolves it; None when off.""" @@ -195,21 +213,60 @@ def remove(doc: dict[str, Any], name: str) -> list[str]: return gone -def move(doc: dict[str, Any], cfg: dict[str, Any], name: str, *, gpu: str, usd_per_h: float | None = None) -> dict: +def move(doc: dict[str, Any], cfg: dict[str, Any], name: str, *, gpu: str, usd_per_h: float | None = None, + inventory: str | None = None) -> dict: """Move island ``name`` to other machines (in place); returns its member. Its price is ``usd_per_h`` when given, else none of its own: the new machines are billed at the unified price table's price for their ``--gpu`` (``trainer_worker.table_usd_per_h``), - never at the old machines' price.""" + never at the old machines' price. ``inventory``: the node inventory of an ``ssh:`` + ``gpu`` (its launch's ``--rl-node-inventory``, in place of the island's own).""" member = trainer_by_name(doc, name) member["gpu"] = fleet_mod._gpu(gpu, f"island {name} --gpu") # noqa: SLF001 member["usd_per_h"] = (None if usd_per_h is None else fleet_mod._price(usd_per_h, f"island {name} --usd-per-h")) # noqa: SLF001 + if inventory is not None: + from yeto.launch import island_join # noqa: PLC0415 + + if not str(member["gpu"]).startswith("ssh:"): + raise IslandChangeError(f"island {name}: --inventory is the node inventory of an ssh: island " + f"(--gpu {member['gpu']})") + member["argv"] = [*island_join.without_inventory([str(a) for a in member.get("argv") or ()]), + "--rl-node-inventory", inventory_path(inventory)] shape = il.fleet_shape([str(a) for a in cfg["fleet"]["trainer_argv"]]) if shape: member["fleet_shape"] = shape # the moved island's layout is checked against the fleet's return member +def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], *, ssh: Any = None, + force: bool = False, first: Any = None) -> Any: + """An ``ssh:`` island's nodes (added, or moved onto; ``yeto.launch.island_join``): + as many as it needs, free in this fleet, healthy, in one fabric group and not leased to + another run; refused naming each problem. Returns the check (its nodes, its health). + + ``first``: the check before the desired state was read again (the write's retry, + another ``add`` that claimed this island's learner id meanwhile): its node health is + kept, the rest (the other islands' nodes, the leases under the member's prefix now) is + checked again on ``doc``.""" + from yeto.launch import island_join # noqa: PLC0415 + + fleet_argv = [str(a) for a in cfg["fleet"]["trainer_argv"]] + # a node leased by the island's own launch (its member prefix, -m after a move) is its own + result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=str(member["prefix"]), ssh=ssh, + force=force, health=None if first is None else first.health, + seen=() if first is None else [*first.notes, *first.warnings]) + if not result.ok: + again = "" if first is None else " (checked again on the desired state now)" + raise IslandChangeError(f"island {member['name']}'s nodes cannot join{again}: " + "; ".join(result.refusals)) + if first is None: + print(f"fleet island: island {member['name']} takes nodes {island_join.names(result.nodes)}; its nodes pass " + "the join checks (health, fabric group, lease)") + elif result.nodes != first.nodes: + print(f"fleet island: island {member['name']} takes nodes {island_join.names(result.nodes)} now (the " + "desired state changed since its check)") + return result + + # -- the launch's own dry run ------------------------------------------------------------------- def _prepare(args: Any) -> None: @@ -295,6 +352,9 @@ def add_parser(fsub: Any) -> None: a.add_argument("--gpu", required=True, help="its trainer cluster (yeto launch --gpu, one cluster)") a.add_argument("--usd-per-h", type=float, default=None, help="its trainer's price (spend view)") a.add_argument("--samplers", required=True, help="a JSON file: the island's samplers list (pool entries)") + a.add_argument("--inventory", default=None, metavar="PATH", + help="an ssh: island's node inventory (its trainer nodes); they are checked first: free in " + "this fleet, healthy, one fabric group, not leased to another run") a.add_argument("--trainer-arg", action="append", default=None, metavar="ARG", help="its own trainer flag (--rl-release-every / --rl-max-policy-age / --rl-sample-wait-s), " "repeatable: --trainer-arg=--rl-release-every --trainer-arg=2") @@ -304,6 +364,13 @@ def add_parser(fsub: Any) -> None: m.add_argument("--name", required=True) m.add_argument("--gpu", required=True) m.add_argument("--usd-per-h", type=float, default=None) + m.add_argument("--inventory", default=None, metavar="PATH", + help="an ssh: --gpu's node inventory (its trainer nodes), in place of the island's own; they are " + "checked first as for add") + for q in (a, m): + q.add_argument("--force", action="store_true", + help="an ssh: island whose node health check does not read joins anyway (a WARNING); " + "a node found unhealthy is still refused") for q in (a, r, m): q.add_argument("--config", required=True, help="the run config") q.add_argument("--dry-run", action="store_true", help="show the change and dry-run the launch; write nothing") @@ -322,7 +389,7 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: for m in doc.get("members") or (): for key in dz.ONE_SHOT: m.pop(key, None) - launch_member = previous = None + launch_member = previous = joined = None if args.island_command == "add": unpriced_under_budget(run.cfg, args.gpu, args.usd_per_h) with open(args.samplers) as fh: @@ -331,15 +398,20 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: k = next_learner_id(objects, plan, doc, args.name) member, pools = compile_island(run.cfg, plan, k=k, name=args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, samplers=samplers, - island_argv=args.trainer_arg) + island_argv=args.trainer_arg, inventory=args.inventory) add(doc, member, pools) launch_member = member + if str(member["gpu"]).startswith("ssh:"): + joined = join_check(run.cfg, current, member, force=args.force) elif args.island_command == "remove": remove(doc, args.name) else: unpriced_under_budget(run.cfg, args.gpu, args.usd_per_h) previous = copy.deepcopy(trainer_by_name(doc, args.name)) - launch_member = move(doc, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h) + launch_member = move(doc, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, + inventory=args.inventory) + if str(launch_member["gpu"]).startswith("ssh:"): # the machines it moves onto: as for add + joined = join_check(run.cfg, current, launch_member, force=args.force) doc = dz.validate(doc) for line in changes(current, doc): print(f"fleet island: {line}") @@ -368,16 +440,22 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: if claimed != int(launch_member["learner_id"]): # another add claimed it meanwhile: compile again launch_member, pools = compile_island(run.cfg, plan, k=claimed, name=args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, samplers=samplers, - island_argv=args.trainer_arg) + island_argv=args.trainer_arg, inventory=args.inventory) member_now = launch_member def change(fresh: dict[str, Any]) -> None: if args.island_command == "add": + before = copy.deepcopy(fresh) add(fresh, member_now, pools) + moved = member_now elif args.island_command == "remove": remove(fresh, args.name) + return else: - move(fresh, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h) + before = copy.deepcopy(fresh) + moved = move(fresh, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, inventory=args.inventory) + if joined is not None: # the other islands and the leases as they are now (an add may have run meanwhile) + join_check(run.cfg, before, moved, force=args.force, first=joined) try: written = store.update(change, note=f"fleet island {args.island_command} {args.name}", attempts=3)