diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 497208667..a7766513a 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -194,8 +194,23 @@ yeto run up --config run.own-sampler-pool.json --dry-run - **Image.** `provider.container.image` names the sampler image (or `auto`: each node's image from the engine image catalog for what the spec asks); the dry run refuses a node the image does not serve. -- **Weights.** Put the model and the prompts on every node once (the - template's sampler nodes mount `/data/models`); the pool does not pull them. +- **Weights.** Put the model on every node once (the template's sampler + nodes mount `/data/models`); the pool does not pull it. +- **Prompts.** With `prompts_file` the pool copies the file to the host path + behind the spec's `prompts.path` (under the pool's `workdir` or a mount) at + every start and checks its size and sha256 there. Without it, put the file + there before the run; the dry run warns when the sampler cannot read the + path. +- **Nodes.** A node named in `provider.nodes` needs the `sampler` role (or no + roles), the spec's tensor parallel size must fit its cards + (`provider.devices` when set, each an index of the node's cards). `yeto run + up` refuses a pool on a node of the run's `ssh:` trainer islands or their + spares, unless both lease the node in one `lease_store` and the islands + still find the nodes they need (then a warning). Two pools of one run on + the nodes of one `lease_store` skip each other's nodes; they are refused + when both name one node in `provider.nodes` or their targets exceed the + nodes they can take (split a node's cards between pools with + `provider.devices` on an inventory without `lease_store`). - **Spend.** The pool bills nothing (`price_usd_h` 0 unless you state one), so a spend cap (`budget.usd`) counts the other parts only: in the template, the Modal trainer. diff --git a/examples/own-cluster/inventory.own-b300-nodes.yaml b/examples/own-cluster/inventory.own-b300-nodes.yaml index 9ae00ae10..07d4ab056 100644 --- a/examples/own-cluster/inventory.own-b300-nodes.yaml +++ b/examples/own-cluster/inventory.own-b300-nodes.yaml @@ -49,5 +49,5 @@ nodes: fabric: tcp # a sampler node needs no RDMA runtime: docker mounts: - /data/models: /data/models # Qwen3-4B weights and the prompts, put there once + /data/models: /data/models # Qwen3-4B weights, put there once (the pool uploads the prompts) roles: [sampler] diff --git a/examples/own-cluster/run.own-trainer-own-sampler.json b/examples/own-cluster/run.own-trainer-own-sampler.json index d03eac287..7095e326c 100644 --- a/examples/own-cluster/run.own-trainer-own-sampler.json +++ b/examples/own-cluster/run.own-trainer-own-sampler.json @@ -1,5 +1,5 @@ { - "comment": "Own cluster as both the trainer and the sampler pool: async GRPO of Qwen3-4B (full parameters) on a 2-node trainer island of own 8 x B300 nodes (SSH + Docker, inventory.own-b300-nodes.yaml, roles: [trainer]) fed by an own SSH sampler pool of one 8 x B300 node (the inventory's roles: [sampler] node; Qwen3-4B vLLM, TP8) that starts its sampler through the unified node runtime. is the trainer image (as in examples/k31: name it; without --rl-image the launch resolves it from the site image catalog, else the built-in default). must be a vLLM build that runs on B300 (sm103), e.g. the catalog's vllm-cuda-k31 image. Every node is your own: the run spends nothing (trainer.usd_per_h 0, the ssh pool bills nothing). budget.usd is a guard cap only: run up's preflight refuses budget.usd 0 while it prices any part of the run. budget.wall_h is the run.wall_clock breaker (3 h when unset), which every run up restarts. docs/OWN_CLUSTERS.md. yeto run up --config THIS.json --dry-run (add --check-nodes to check over SSH that the three nodes reach the store and the registry), then without --dry-run (it runs that check before it orders anything).", + "comment": "Own cluster as both the trainer and the sampler pool: async GRPO of Qwen3-4B (full parameters) on a 2-node trainer island of own 8 x B300 nodes (SSH + Docker, inventory.own-b300-nodes.yaml, roles: [trainer]) fed by an own SSH sampler pool of one 8 x B300 node (the inventory's roles: [sampler] node; Qwen3-4B vLLM, TP8) that starts its sampler through the unified node runtime; the pool copies prompts_file to the sampler spec's prompts.path (on the node behind the inventory mount) at every start and checks its size and sha256 there. is the trainer image (as in examples/k31: name it; without --rl-image the launch resolves it from the site image catalog, else the built-in default). must be a vLLM build that runs on B300 (sm103), e.g. the catalog's vllm-cuda-k31 image. Every node is your own: the run spends nothing (trainer.usd_per_h 0, the ssh pool bills nothing). budget.usd is a guard cap only: run up's preflight refuses budget.usd 0 while it prices any part of the run. budget.wall_h is the run.wall_clock breaker (3 h when unset), which every run up restarts. docs/OWN_CLUSTERS.md. yeto run up --config THIS.json --dry-run (add --check-nodes to check over SSH that the three nodes reach the store and the registry), then without --dry-run (it runs that check before it orders anything).", "run": "", "store": "s3:///runs/", "samplers": [ @@ -29,6 +29,7 @@ "spec": "", "run_prefix": "", "r2_env_file": "", + "prompts_file": "", "sampler": { "dispense": { "backend": "store", diff --git a/examples/own-cluster/sampler-spec.qwen3-4b-vllm-own-b300.json b/examples/own-cluster/sampler-spec.qwen3-4b-vllm-own-b300.json index 0d8cfca7a..0af75fc19 100644 --- a/examples/own-cluster/sampler-spec.qwen3-4b-vllm-own-b300.json +++ b/examples/own-cluster/sampler-spec.qwen3-4b-vllm-own-b300.json @@ -2,8 +2,9 @@ "_comment": [ "Engine sampler spec of one Qwen3-4B vLLM sampler on an own 8 x B300 node (TP8, bf16, in-place", "reload) of the SSH inventory pool in run.own-trainer-own-sampler.json: the container sees the", - "pool's workdir and the inventory's mounts at their host paths; the weights and the prompts are", - "on the node (/data/models). The pool renders the store, shard and sampler id at start.", + "pool's workdir and the inventory's mounts at their host paths; the weights are on the node", + "(/data/models), the pool uploads its prompts_file to prompts.path at every start. The pool", + "renders the store, shard and sampler id at start.", "docs/OWN_CLUSTERS.md." ], "sampler_id": "qwen3-4b-0", diff --git a/tests/test_own_cluster_templates.py b/tests/test_own_cluster_templates.py index 518d71f8d..891fb6f9b 100644 --- a/tests/test_own_cluster_templates.py +++ b/tests/test_own_cluster_templates.py @@ -346,6 +346,135 @@ def test_an_own_trainer_island_with_an_own_sampler_pool_spends_nothing(kit, caps assert [n["name"] for n in island["ssh_island"]["nodes"]] == ["own-b300-0", "own-b300-1"] +def _own_sampler_variant(kit, *, inventory_edit, pools_edit) -> None: + """run.own-trainer-own-sampler.json with its inventory and its pools edited in place.""" + import yaml + + inv = kit.files["inventory.own-b300-nodes.yaml"] + doc = yaml.safe_load(inv.read_text()) + inventory_edit(doc) + inv.write_text(yaml.safe_dump(doc)) + cfg = _cfg(kit, "run.own-trainer-own-sampler.json") + pools_edit(cfg) + kit.files["run.own-trainer-own-sampler.json"].write_text(json.dumps(cfg)) + + +def _two_pools_on_one_node(cfg: dict) -> None: + (pool,) = cfg["samplers"] + pool["provider"]["devices"] = [0, 1, 2, 3] + second = json.loads(json.dumps(pool)) + second.update(name="own-b300-b", shard_base=pool["shard_base"] + "b") + second["provider"]["devices"] = [4, 5, 6, 7] + cfg["samplers"].append(second) + argv = cfg["trainer"]["argv"] + i = argv.index("--rl-buffer-shards") + 1 + argv[i] += "," + ",".join(f"{second['shard_base']}-{k}" for k in range(int(second["shard_limit"]))) + + +@pytest.mark.parametrize("dry_run", [True, False]) +def test_two_pools_on_one_leased_node_refuse_the_run_up(kit, monkeypatch, capsys, tmp_path, dry_run): + """Two pools of target 1 on the one sampler node of a leased inventory: a pool waits for + the node lease the other holds. The run up (a dry run and the real one) refuses, naming + the pools, the node and the two ways out; nothing starts.""" + monkeypatch.setattr(kit.up.Run, "write_fleet_plan", lambda self: pytest.fail("ordered after a refusal")) + store = tmp_path / "leases" + _own_sampler_variant(kit, inventory_edit=lambda doc: doc.update(lease_store=str(store)), + pools_edit=_two_pools_on_one_node) + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys, dry_run=dry_run) + assert rc == 2, out.why + assert (f"preflight: pools own-b300 and own-b300-b share node(s) own-b300-2 of an inventory with node leases " + f"(lease_store {store}): their targets (1 + 1) are more than the 1 node(s) the two can take") in out + assert "give the pools an inventory without lease_store and split the nodes' cards with provider.devices" in out + assert "or put the pools on different nodes; nothing is started" in out + assert kit.ordered == [] and not [c for c in kit.commands if "pool" in c] # refused before any pool dry run + + +def test_two_pools_split_one_node_without_lease_store(kit, capsys): + spec_file = kit.files["sampler-spec.qwen3-4b-vllm-own-b300.json"] + spec = json.loads(spec_file.read_text()) + spec["engine"]["options"]["tp"], spec["engine"]["server"]["topology"] = 4, "tp4" # 4 cards per pool + spec_file.write_text(json.dumps(spec)) + _own_sampler_variant(kit, inventory_edit=lambda doc: None, pools_edit=_two_pools_on_one_node) + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys) + assert "share node(s)" not in out and "may both take" not in out + assert rc == 0 and "dry run: preflight ok, nothing ordered" in out, out.why + + +def test_a_pool_on_a_trainer_node_refuses_the_run_up(kit, monkeypatch, capsys): + monkeypatch.setattr(kit.up.Run, "write_fleet_plan", lambda self: pytest.fail("ordered after a refusal")) + + def both_roles(doc): + doc["nodes"][0]["roles"] = ["trainer", "sampler"] + + def on_it(cfg): + cfg["samplers"][0]["provider"]["nodes"] = ["own-b300-0"] + + _own_sampler_variant(kit, inventory_edit=both_roles, pools_edit=on_it) + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys) + assert rc == 2, out.why + assert ("preflight: pool own-b300 starts samplers on node own-b300-0, which is a node of this run's trainer " + "island ssh:2x8xb300 (own-b300-0): the trainer takes every card of its nodes") in out + + +def test_a_pool_on_a_leased_trainer_node_is_a_warning_while_the_island_has_enough(kit, capsys, tmp_path): + """A leased inventory whose three nodes are trainer and sampler nodes: the island takes + two, the pool one, each skipping what the other holds: a warning, the run goes on.""" + def leased_three(doc): + doc["lease_store"] = str(tmp_path / "leases") + for node in doc["nodes"]: + node["roles"] = ["trainer", "sampler"] + + def on_node_2(cfg): + cfg["samplers"][0]["provider"]["nodes"] = ["own-b300-2"] + + _own_sampler_variant(kit, inventory_edit=leased_three, pools_edit=on_node_2) + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys, check_nodes=False) + assert ("preflight: WARNING: pool own-b300 on own-b300-2: trainer nodes of this run's trainer island(s) " + "ssh:2x8xb300; the trainer skips a node a pool holds") in out + assert "3 trainer node(s), the pools may hold 1 of them, 2 left for the 2 node(s) the islands need" in out + assert "the trainer takes every card of its nodes" not in out + + +def test_a_fleet_pool_on_its_own_island_trainer_node_refuses_the_run_up(kit, monkeypatch, capsys): + """A fleet: the compile lists every island's cluster in the trainer's --gpu; an ssh pool + of the cloud island on the own island's trainer node is refused before anything starts.""" + import yaml + + monkeypatch.setattr(kit.up.Run, "write_fleet_plan", lambda self: pytest.fail("ordered after a refusal")) + inv = kit.files["inventory.own-nodes.yaml"] + doc = yaml.safe_load(inv.read_text()) + doc["nodes"][0]["roles"] = ["trainer", "sampler"] + inv.write_text(yaml.safe_dump(doc)) + cfg = _cfg(kit, "run.fleet-own-and-cloud.json") + (pool,) = cfg["islands"][1]["samplers"] + pool["provider"] = {"kind": "ssh", "inventory": str(inv), "nodes": ["own-b300-0"], "workdir": "/srv/yeto/ocrun", + "runtime": "container", "container": {"engine": "docker", "image": SAMPLER_IMAGE}} + pool["slots"] = [0] + kit.files["run.fleet-own-and-cloud.json"].write_text(json.dumps(cfg)) + rc, out = _dry_run(kit, "run.fleet-own-and-cloud.json", capsys) + assert rc == 2, out.why + assert ("preflight: pool i1-modal-l40s starts samplers on node own-b300-0, which is a node of this run's trainer island " + "ssh:1x8xb300 (own-b300-0): the trainer takes every card of its nodes") in out + + +def test_a_pool_naming_a_trainer_only_node_fails_its_pool_dry_run(kit, capsys): + _own_sampler_variant(kit, inventory_edit=lambda doc: None, + pools_edit=lambda cfg: cfg["samplers"][0]["provider"].update(nodes=["own-b300-1"])) + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys) + assert rc == 2 + assert ("ssh provider: nodes own-b300-1 (roles: trainer) have no sampler role in the inventory; add sampler to " + "their roles, or name sampler nodes in provider.nodes") in out + + +def test_the_own_sampler_template_uploads_its_prompts_and_bills_nothing(kit, capsys): + rc, out = _dry_run(kit, "run.own-trainer-own-sampler.json", capsys) + assert rc == 0, out.why + assert "prompts_file: uploaded to /data/models/prompts/gsm8k.jsonl on every node of the pool" in out + assert "bill until they are released" not in out + assert "WARNING: Own SSH nodes (ssh, price_usd_h 0) are not billed by this pool" in out + assert "each sampler start fails unless the file is already on the node" not in out + + def test_a_fleet_of_an_own_and_a_cloud_island_counts_the_own_trainer_at_zero(kit, capsys): rc, out = _dry_run(kit, "run.fleet-own-and-cloud.json", capsys) assert rc == 0, out.why diff --git a/tests/test_ssh_pool_checks.py b/tests/test_ssh_pool_checks.py new file mode 100644 index 000000000..55ce4fb74 --- /dev/null +++ b/tests/test_ssh_pool_checks.py @@ -0,0 +1,606 @@ +"""The checks of an ssh pool on own nodes: one machine per inventory address, the sampler +role of a named node, the tensor parallel size against the pool's cards, the release +warning of a pool that bills nothing, where the sampler reads its prompts (and the +``prompts_file`` upload at every start), and the cross-pool / trainer node refusals of +``yeto run up`` (:mod:`yeto.launch.own_node_checks`).""" + +from __future__ import annotations + +import hashlib +import json +import re +import shlex +from types import SimpleNamespace + +import pytest + +from tests.test_ssh_sampler_pool import FakeRun, conf, npu_node, pool_cfg, provider_section +from yeto.launch import own_node_checks as checks +from yeto.launch import ssh_sampler_pool as sp +from yeto.launch.nc import cli, pool_run +from yeto.launch.node_inventory import InventoryError, parse_inventory, parse_node + + +def _raw(name, host, **kw): + return {"name": name, "host": host, "device_family": "cuda", "cpu_arch": "x86_64", "card": "H100", + "cards_per_node": 8, "hbm_gib": 80, "host_memory_gib": 1024, **kw} + + +# -- 6: one address per node -------------------------------------------------------- + + +def test_the_inventory_refuses_one_address_on_two_nodes(): + with pytest.raises(InventoryError, match=r"address '10\.0\.0\.5' twice \(nodes a and b\)"): + parse_inventory({"nodes": [_raw("a", "a", address="10.0.0.5"), _raw("b", "b", address="10.0.0.5")]}) + + +def test_nodes_without_an_address_or_on_loopback_are_no_duplicates(): + assert len(parse_inventory({"nodes": [_raw("a", "a"), _raw("b", "b")]})) == 2 + # each container's own loopback (the stage-1 Modal mini inventory) + assert len(parse_inventory({"nodes": [_raw("a", "a", address="127.0.0.1"), + _raw("b", "b", address="127.0.0.1")]})) == 2 + assert len(parse_inventory({"nodes": [_raw("a", "a", address="10.0.0.5"), + _raw("b", "b", address="10.0.0.6")]})) == 2 + + +# -- 3: a named node must have the sampler role --------------------------------------- + + +@pytest.mark.parametrize("roles", [["trainer"], ["trainer-spare"]]) +def test_a_named_node_without_the_sampler_role_is_refused(roles): + with pytest.raises(ValueError, match=re.escape(f"nodes node-a (roles: {roles[0]}) have no sampler role")): + sp.parse_config({"provider": provider_section()}, inventory=[npu_node(roles=roles)]) + + +@pytest.mark.parametrize("roles", [[], ["sampler"], ["trainer", "sampler"]]) +def test_a_named_node_with_the_sampler_role_or_no_roles_is_taken(roles): + c = sp.parse_config({"provider": provider_section()}, inventory=[npu_node(roles=roles)]) + assert [n.name for n in c.nodes] == ["node-a"] + + +# -- 4: tensor parallel size against the pool's cards --------------------------------- + + +def _spec(**options): + return {"engine": {"adapter": "vllm-server", "options": options}} + + +def test_a_tensor_parallel_size_above_the_pool_devices_is_refused(): + (problem,) = sp.spec_node_problems(conf(devices=[0, 1]), _spec(tp=4)) + assert problem == ("ssh provider: node node-a: the spec's engine tensor parallel size is 4 cards, provider.devices " + "[0, 1] give it 2; lower engine.options.tp or give the pool more cards of the node") + assert sp.spec_node_problems(conf(devices=[0, 1, 2, 3]), _spec(tp=4)) == [] + + +def test_without_devices_the_tensor_parallel_size_is_held_to_the_node_cards(): + (problem,) = sp.spec_node_problems(conf(devices=None), _spec(tp=16)) + assert "tensor parallel size is 16 cards, it has 8;" in problem + assert sp.spec_node_problems(conf(devices=None), _spec(tp=8)) == [] + + +def test_devices_beyond_the_node_cards_are_refused_and_not_counted(): + node = npu_node(cards_per_node=4) + c = sp.parse_config({"provider": provider_section(devices=[0, 1, 2, 3, 4, 5, 6, 7])}, inventory=[node]) + problems = sp.spec_node_problems(c, _spec(tp=8)) + assert problems == ["ssh provider: node node-a has 4 cards (indexes 0-3); provider.devices [4, 5, 6, 7] are " + "not on it", + "ssh provider: node node-a: the spec's engine tensor parallel size is 8 cards, " + "provider.devices [0, 1, 2, 3, 4, 5, 6, 7] give it 4; lower engine.options.tp or give the " + "pool more cards of the node"] + + +def test_the_adapter_default_tensor_parallel_size_is_checked(): + from yeto.rl.adapters.sampler_engines.sglang_server import SGLangOptions + from yeto.rl.adapters.sampler_engines.vllm_server import VllmOptions + + assert sp.ADAPTER_DEFAULT_TP == {"vllm-server": VllmOptions().tp, "sglang-server": SGLangOptions().tp} + assert sp.spec_tp({"engine": {"adapter": "vllm-server"}}) == 4 + assert sp.spec_tp({"engine": {"adapter": "sglang-server"}}) == 8 + assert sp.spec_tp({"engine": {"adapter": "fake"}}) is None + assert sp.spec_tp(_spec(tp="8")) == 8 # the adapters take the decimal string + with pytest.raises(ValueError, match="engine.options.tp must be a whole number of cards >= 1, not 'eight'"): + sp.spec_tp(_spec(tp="eight")) + (problem,) = sp.spec_node_problems(conf(devices=None), _spec(tp="eight")) + assert problem == "ssh provider: engine.options.tp must be a whole number of cards >= 1, not 'eight'" + (problem,) = sp.spec_node_problems(conf(devices=[0, 1]), _spec(tp="4")) + assert "tensor parallel size is 4 cards" in problem + (problem,) = sp.spec_node_problems(conf(devices=[0]), {"engine": {"adapter": "vllm-server"}}) + assert "tensor parallel size is 4 cards" in problem + + +# -- 2: a pool that bills nothing ----------------------------------------------------- + + +def test_an_own_ssh_pool_at_no_price_is_not_warned_as_billing(tmp_path): + text = pool_run.lease_warning(pool_cfg(tmp_path), "pool.json") + assert "bill until" not in text and "not billed" in text + assert text == ("Own SSH nodes (ssh, price_usd_h 0) are not billed by this pool, but its samplers hold their " + "cards until the pool stops: keep this pool running, or stop it with " + "`python -m yeto.launch.nc pool-stop --config pool.json`.") + + +def test_an_own_ssh_pool_with_a_price_keeps_the_billing_warning(tmp_path): + text = pool_run.lease_warning(pool_cfg(tmp_path, price_usd_h=2.5), "pool.json") + assert text == pool_run.CLOUD_WARNING.format(kind="ssh").replace("", "pool.json") + sky = {"provider": {"kind": "sky"}, "shard_base": "x"} + assert "bill until they are released" in pool_run.lease_warning(sky, "pool.json") + + +# -- 7: where an ssh pool's sampler reads its prompts -------------------------------- + + +def _inventory_cfg(tmp_path, *, runtime="container", prompts_path, prompts_file=None, **section): + inv = tmp_path / "inv.yaml" + inv.write_text(json.dumps({"nodes": [_raw("own-0", "ops@own-0", mounts={"/mnt/nvme/models": "/data/models"}, + roles=["sampler"])]})) + spec = tmp_path / "spec.json" + spec.write_text(json.dumps({"prompts": {"path": prompts_path}})) + provider = {"kind": "ssh", "inventory": str(inv), "workdir": "/srv/yeto/run0", "runtime": runtime, **section} + if runtime == "container": + provider["container"] = {"engine": "docker", "image": "img@sha256:" + "0" * 64} + else: + provider["venv"] = {"python": "/opt/venv/bin/python"} + cfg = {"provider": provider, "spec": str(spec), "shard_base": "r", "run_prefix": "r", "target": 1, "slots": [0]} + if prompts_file is not None: + cfg["prompts_file"] = str(prompts_file) + return cfg, json.loads(spec.read_text()) + + +def test_prompts_under_a_mount_are_read_from_the_host_path_behind_it(tmp_path): + cfg, spec = _inventory_cfg(tmp_path, prompts_path="/data/models/prompts/p.jsonl") + lines, problems, (note,) = cli.prompts_file_report(cfg, spec) + assert lines == problems == [] + assert note == ("the sampler spec reads prompts.path /data/models/prompts/p.jsonl from the node (an inventory or " + "pool mount; on the host /mnt/nvme/models/prompts/p.jsonl): put the file there before the run, " + "or set prompts_file (uploaded and checked by size and sha256 at every start)") + assert "fails" not in note + + +def test_prompts_under_the_workdir_are_read_from_the_workdir(tmp_path): + cfg, spec = _inventory_cfg(tmp_path, prompts_path="/srv/yeto/run0/prompts.jsonl") + lines, problems, (note,) = cli.prompts_file_report(cfg, spec) + assert lines == problems == [] + assert ("reads prompts.path /srv/yeto/run0/prompts.jsonl from the node (the pool's workdir /srv/yeto/run0; " + "on the host /srv/yeto/run0/prompts.jsonl)") in note + + +def test_prompts_neither_under_a_mount_nor_the_workdir_are_a_warning(tmp_path): + cfg, spec = _inventory_cfg(tmp_path, prompts_path="/opt/prompts.jsonl") + (line,), problems, notes = cli.prompts_file_report(cfg, spec) + assert problems == notes == [] + assert line.startswith("WARNING: the sampler spec reads prompts.path /opt/prompts.jsonl, which the sampler " + "container on nodes ['own-0'] cannot read (no mount or workdir holds it") + assert "set prompts_file to upload it" in line + + +def test_a_venv_sampler_reads_the_host_itself(tmp_path): + cfg, spec = _inventory_cfg(tmp_path, runtime="venv", prompts_path="/opt/prompts.jsonl") + lines, problems, (note,) = cli.prompts_file_report(cfg, spec) + assert lines == problems == [] and "(the node's own filesystem; on the host /opt/prompts.jsonl)" in note + + +def test_a_prompts_file_goes_to_the_host_path_and_an_unseen_path_is_a_problem(tmp_path): + local = tmp_path / "p.jsonl" + local.write_text('{"q": 1}\n') + cfg, spec = _inventory_cfg(tmp_path, prompts_path="/data/models/p.jsonl", prompts_file=local) + lines, problems, notes = cli.prompts_file_report(cfg, spec) + assert problems == notes == [] and lines[-1] == "prompts_file: uploaded to /mnt/nvme/models/p.jsonl on every " \ + "node of the pool" + cfg, spec = _inventory_cfg(tmp_path, prompts_path="/opt/p.jsonl", prompts_file=local) + _lines, (problem,), _notes = cli.prompts_file_report(cfg, spec) + assert "is under no mount or workdir of nodes ['own-0']" in problem + + +def test_a_rented_pool_keeps_its_prompts_note(tmp_path): + cfg = {"provider": {"kind": "sky"}, "spec": "x"} + _lines, _problems, (note,) = cli.prompts_file_report(cfg, {"prompts": {"path": "/work/p.jsonl"}}) + assert "each sampler start fails unless the file is already on the node" in note + + +# -- 5: the prompts_file upload at every start ---------------------------------------- + + +class Node(FakeRun): + """FakeRun that keeps the bytes streamed to a path and answers the size / sha256 check; + ``write_rc``: the exit of the write; ``corrupt``: the write keeps other bytes.""" + + def __init__(self, *, corrupt=False, write_rc=0): + super().__init__() + self.files: dict[str, bytes] = {} + self.corrupt, self.write_rc = corrupt, write_rc + self.writes: list[str] = [] + + def __call__(self, argv, **kw): + cmd = argv[-1] if argv and argv[0] == "ssh" else "" + if cmd.startswith("umask 077; t=") and kw.get("stdin") is not None: + self.calls.append((argv, kw)) + path = shlex.split(cmd.split("t=", 1)[1].split(".tmp.$$", 1)[0])[0] + self.writes.append(cmd) + if self.write_rc == 0: + self.files[path] = kw["stdin"].read() + (b"x" if self.corrupt else b"") + return SimpleNamespace(returncode=self.write_rc, stdout=b"", stderr=b"disk full" if self.write_rc else b"") + if cmd.startswith("echo YETO_PROMPTS"): + self.calls.append((argv, kw)) + path = shlex.split(cmd.split("wc -c < ", 1)[1].split(")", 1)[0])[0] + if path not in self.files: + return SimpleNamespace(returncode=0, stdout="YETO_PROMPTS\n", stderr="") + data = self.files[path] + digest = hashlib.sha256(data).hexdigest() + return SimpleNamespace(returncode=0, stdout=f"YETO_PROMPTS {len(data)} {digest}\n", stderr="") + return super().__call__(argv, **kw) + + +def _ops(tmp_path, monkeypatch, run, *, prompts_path="/srv/yeto/shared/prompts/p.jsonl"): + class Pop: + stdout = None + + def __init__(self, *a, **k): + pass + + def wait(self): + return 0 + + monkeypatch.setattr(sp.subprocess, "Popen", Pop) + monkeypatch.setattr(cli.tasks, "sampler_spec", lambda spec, sampler_id, shards: dict(spec, sampler_id=sampler_id)) + monkeypatch.setattr(cli.tasks, "apply_sampler_overrides", lambda spec, **kw: spec) + local = tmp_path / "prompts.jsonl" + local.write_bytes(b'{"question": "1+1?", "answer": "2"}\n' * 3) + cfg = pool_cfg(tmp_path, node_runtime=False) + spec = json.loads((tmp_path / "spec.json").read_text()) + spec["prompts"]["path"] = prompts_path + (tmp_path / "spec.json").write_text(json.dumps(spec)) + cfg["prompts_file"] = str(local) + ops = sp.SshSamplerPoolOps(cfg, conf=conf(node_runtime=False), run=run, state_dir=tmp_path) + return ops, local + + +def _member(ops): + return SimpleNamespace(account=0, ticket=ops.order(0), shard="f09-0", data_slot=None, replaces_shard=None, + predecessor_lost=False) + + +def _cmds(run): + return [c[0][-1] for c in run.calls if c[0][0] == "ssh"] + + +def test_a_start_uploads_the_prompts_file_and_checks_it_before_the_sampler(tmp_path, monkeypatch): + run = Node() + ops, local = _ops(tmp_path, monkeypatch, run) + ops.start(_member(ops), ["f09-0"]) + host = "/srv/yeto/shared/prompts/p.jsonl" + assert run.files[host] == local.read_bytes() and len(run.writes) == 1 + # a temp name of this shell (two starts on one path do not collide), then renamed + assert "t='/srv/yeto/shared/prompts/p.jsonl'.tmp.$$" in run.writes[0] or \ + "t=/srv/yeto/shared/prompts/p.jsonl.tmp.$$" in run.writes[0] + assert 'mv -f "$t" /srv/yeto/shared/prompts/p.jsonl' in run.writes[0] + cmds = _cmds(run) + assert "mkdir -p /srv/yeto/shared/prompts" in cmds + checks_at = [i for i, c in enumerate(cmds) if c.startswith("echo YETO_PROMPTS")] + assert len(checks_at) == 2 # before (no copy there yet) and after the upload + assert checks_at[-1] < next(i for i, c in enumerate(cmds) if "run -d" in c) # checked before the start + + +def test_a_restart_checks_the_copy_and_keeps_it_when_it_matches(tmp_path, monkeypatch): + run = Node() + ops, local = _ops(tmp_path, monkeypatch, run) + m = _member(ops) + ops.start(m, ["f09-0"]) + ops.start(m, ["f09-0"]) # a restart: checked again at the start, the matching copy is kept + assert len(run.writes) == 1 + assert sum(c.startswith("echo YETO_PROMPTS") for c in _cmds(run)) == 3 + local.write_bytes(b'{"question": "2+2?", "answer": "4"}\n') # a changed file is copied again + ops.start(m, ["f09-0"]) + assert len(run.writes) == 2 and run.files["/srv/yeto/shared/prompts/p.jsonl"] == local.read_bytes() + + +def test_the_upload_streams_the_file_with_a_timeout_by_its_size(tmp_path, monkeypatch): + run = Node() + ops, _local = _ops(tmp_path, monkeypatch, run) + ops.start(_member(ops), ["f09-0"]) + (write,) = [c for c in run.calls if c[0][0] == "ssh" and c[0][-1].startswith("umask 077; t=")] + assert write[1]["stdin"] is not None and write[1].get("input") is None + assert write[1]["timeout"] == sp.upload_timeout_s(108) + assert sp.upload_timeout_s(0) == 60 and sp.upload_timeout_s(100 * 1024 * 1024) == 70 + assert sp.upload_timeout_s(10 ** 12) == 1800 + + +def test_a_failed_write_stops_the_start_naming_it(tmp_path, monkeypatch): + run = Node(write_rc=1) + ops, _local = _ops(tmp_path, monkeypatch, run) + with pytest.raises(sp.SshSamplerError, match=r"prompts upload /srv/yeto/shared/prompts/p.jsonl to node-a " + r"\(exit 1\): disk full"): + ops.start(_member(ops), ["f09-0"]) + assert not any("run -d" in c for c in _cmds(run)) + + +def test_a_copy_that_does_not_match_stops_the_start(tmp_path, monkeypatch): + run = Node(corrupt=True) + ops, _local = _ops(tmp_path, monkeypatch, run) + with pytest.raises(sp.SshSamplerError, match="does not match .* after the upload") as error: + ops.start(_member(ops), ["f09-0"]) + assert not getattr(error.value, "config_error", False) # the node's, retried + assert not any("run -d" in c for c in _cmds(run)) + + +def test_a_prompts_path_the_sampler_cannot_see_is_a_config_error(tmp_path, monkeypatch): + from yeto.launch.pool.island_pool import is_config_error + + run = Node() + ops, _local = _ops(tmp_path, monkeypatch, run, prompts_path="/opt/p.jsonl") + with pytest.raises(sp.SshSamplerError, match="under no mount or workdir of node-a") as error: + ops.start(_member(ops), ["f09-0"]) + assert is_config_error(error.value) and run.files == {} + + +def test_a_missing_local_prompts_file_is_a_config_error(tmp_path, monkeypatch): + from yeto.launch.pool.island_pool import is_config_error + + run = Node() + ops, local = _ops(tmp_path, monkeypatch, run) + local.unlink() + with pytest.raises(sp.SshSamplerError, match="prompts_file .*prompts.jsonl: No such file") as error: + ops.start(_member(ops), ["f09-0"]) + assert is_config_error(error.value) and run.files == {} + + +def test_without_prompts_file_nothing_is_uploaded(tmp_path, monkeypatch): + run = Node() + ops, _local = _ops(tmp_path, monkeypatch, run) + ops.cfg.pop("prompts_file") + ops.start(_member(ops), ["f09-0"]) + assert run.files == {} and not any("YETO_PROMPTS" in c for c in _cmds(run)) + + +# -- 1: two pools of one run on the nodes of one lease store ---------------------------- + + +def _sampler(name, **kw): + return _raw(name, f"ops@{name}", roles=["sampler"], **kw) + + +def _pool(tmp_path, name, nodes=None, *, lease_store=None, inventory_nodes=None, devices=None, target=1, + slots=None, inventory=None): + if inventory is None: + inventory = tmp_path / f"inv-{name}.yaml" + doc = {"nodes": inventory_nodes or [_sampler("own-2", address="10.0.0.2")]} + if lease_store: + doc["lease_store"] = lease_store + inventory.write_text(json.dumps(doc)) + provider = {"kind": "ssh", "inventory": str(inventory), "workdir": f"/srv/yeto/{name}", + "runtime": "venv", "venv": {"python": "/opt/venv/bin/python"}} + if nodes is not None: + provider["nodes"] = nodes + if devices is not None: + provider["devices"] = devices + cfg = {"provider": provider, "target": target} + if slots is not None: + cfg["slots"] = slots + return name, cfg + + +def _shared_inventory(tmp_path, n, lease_store="file:///srv/leases"): + inv = tmp_path / "shared.yaml" + inv.write_text(json.dumps({"lease_store": lease_store, "nodes": [_sampler(f"own-{i}") for i in range(n)]})) + return inv + + +def _levels(found): + return [f.level for f in found] + + +def test_two_pools_with_enough_free_nodes_of_one_lease_store_are_a_note(tmp_path): + inv = _shared_inventory(tmp_path, 3) + a = _pool(tmp_path, "a", inventory=inv, slots=[0, 1, 2]) + b = _pool(tmp_path, "b", inventory=inv, slots=[0, 1, 2]) + (found,) = checks.findings([a, b]) + assert found.level == checks.NOTE + assert found.text == ("pools a and b may both take node(s) own-0, own-1, own-2 (lease_store /srv/leases): a pool " + "skips a node the other holds; their targets (1 + 1) fit the 3 node(s) they can take") + + +def test_two_pools_short_of_nodes_of_one_lease_store_are_refused(tmp_path): + inv = _shared_inventory(tmp_path, 2) + a = _pool(tmp_path, "a", inventory=inv, slots=[0, 1], target=2) + b = _pool(tmp_path, "b", inventory=inv, slots=[0, 1], target=2) + (found,) = checks.findings([a, b]) + assert found.level == checks.ERROR + assert found.text.startswith("pools a and b share node(s) own-0, own-1 of an inventory with node leases " + "(lease_store /srv/leases): their targets (2 + 2) are more than the 2 node(s) the " + "two can take, so a pool waits for a node the other holds.") + assert "without lease_store and split the nodes' cards with provider.devices" in found.text + assert "or put the pools on different nodes" in found.text + + +def test_two_pools_naming_one_leased_node_are_refused(tmp_path): + inv = _shared_inventory(tmp_path, 3) + a = _pool(tmp_path, "a", ["own-0"], inventory=inv, devices=[0, 1, 2, 3]) + b = _pool(tmp_path, "b", ["own-0", "own-1"], inventory=inv, slots=[0, 1], devices=[4, 5, 6, 7]) + (found,) = checks.findings([a, b]) + assert found.level == checks.ERROR and found.text.startswith( + "pools a and b both name node(s) own-0 in provider.nodes on an inventory with node leases " + "(lease_store /srv/leases)") + + +def test_one_lease_store_written_two_ways_is_one_store(tmp_path): + a = _pool(tmp_path, "a", ["own-2"], lease_store="file:///srv/leases") + b = _pool(tmp_path, "b", ["own-2"], lease_store="/srv/leases/") + assert _levels(checks.findings([a, b])) == [checks.ERROR] + assert checks.store_key("file:///srv/leases/") == checks.store_key("/srv/leases") == "/srv/leases" + + +def test_pools_of_two_lease_stores_or_none_do_not_wait_for_each_other(tmp_path): + a = _pool(tmp_path, "a", ["own-2"], lease_store="file:///srv/leases-a") + b = _pool(tmp_path, "b", ["own-2"], lease_store="file:///srv/leases-b") + assert checks.findings([a, b]) == [] # each lease store leases the node to its own pool + a = _pool(tmp_path, "a", ["own-2"], devices=[0, 1, 2, 3]) + b = _pool(tmp_path, "b", ["own-2"], devices=[4, 5, 6, 7]) + assert checks.findings([a, b]) == [] # no leases: the pools split the node's cards + two = [_sampler("own-2"), _sampler("own-3")] + a = _pool(tmp_path, "a", ["own-2"], lease_store="file:///srv/leases", inventory_nodes=two) + b = _pool(tmp_path, "b", ["own-3"], lease_store="file:///srv/leases", inventory_nodes=two) + assert checks.findings([a, b]) == [] + assert checks.findings([a, ("nc", {"provider": {"kind": "nc"}})]) == [] + + +# -- 3: an ssh pool on the trainer's nodes --------------------------------------------- + + +def _side(nodes, *, store=None, need=1, spares=(), inventory="/i/trainers.yaml", entry="ssh:1x8xh100"): + return checks.TrainerSide(inventory, store, entries=[entry], nodes=[parse_node(n, index=0) for n in nodes], + spares=[parse_node(n, index=0) for n in spares], need=need) + + +@pytest.mark.parametrize("trainer_raw", [ + _raw("t-0", "ops@own-2", roles=["trainer"]), # one SSH target + _raw("t-0", "root@own-2", roles=["trainer"]), # one host, another user + _raw("t-0", "ops@other", address="10.0.0.2", roles=["trainer"]), # one cluster address +]) +def test_a_pool_on_a_trainer_node_without_common_leases_is_refused(tmp_path, trainer_raw): + pool = _pool(tmp_path, "p", ["own-2"]) + (found,) = checks.findings([pool], [_side([trainer_raw])]) + assert found.level == checks.ERROR + assert found.text.startswith("pool p starts samplers on node own-2, which is a node of this run's trainer island " + "ssh:1x8xh100 (t-0): the trainer takes every card of its nodes") + (found,) = checks.findings([pool], [_side([], spares=[trainer_raw])]) + assert found.level == checks.ERROR and "which is a trainer-spare node of this run's trainer island" in found.text + other = _raw("t-1", "ops@t-1", address="10.0.0.9") + assert checks.findings([pool], [_side([other])]) == [] + + +def _leased(tmp_path, nodes, store="/srv/leases"): + inv = tmp_path / "leased.yaml" + inv.write_text(json.dumps({"lease_store": store, "nodes": nodes})) + return inv + + +def test_b_a_trainer_and_sampler_node_picked_by_the_pool_is_a_warning_when_enough_remain(tmp_path): + """Review case B: a [trainer, sampler] node on a leased inventory, taken by the pool only.""" + nodes = [_raw(f"n-{i}", f"ops@n-{i}", roles=["trainer", "sampler"]) for i in range(3)] + inv = _leased(tmp_path, nodes) + pool = _pool(tmp_path, "p", ["n-2"], inventory=inv) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) + assert [n.name for n in side.nodes] == ["n-0", "n-1", "n-2"] and side.need == 2 + (found,) = checks.findings([pool], [side], quarantined=lambda s: set()) + assert found.level == checks.WARN + assert found.text == ("pool p on n-2: trainer nodes of this run's trainer island(s) ssh:2x8xh100; the trainer " + "skips a node a pool holds (lease_store /srv/leases): 3 trainer node(s), the pools may hold " + "1 of them, 2 left for the 2 node(s) the islands need") + + +def test_c_a_leased_inventory_without_roles_refuses_only_when_too_few_trainer_nodes_remain(tmp_path): + """Review case C: nodes without roles on a leased inventory: any node is a trainer and a sampler node.""" + inv = _leased(tmp_path, [_raw(f"n-{i}", f"ops@n-{i}") for i in range(3)]) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) + one = _pool(tmp_path, "p", inventory=inv, slots=[0, 1, 2], target=1) + assert _levels(checks.findings([one], [side], quarantined=lambda s: set())) == [checks.WARN] + two = _pool(tmp_path, "p", inventory=inv, slots=[0, 1, 2], target=2) + (found,) = checks.findings([two], [side], quarantined=lambda s: set()) + assert found.level == checks.ERROR + assert "3 trainer node(s), the pools may hold 2 of them, 1 left for the 2 node(s) the islands need" in found.text + assert "the trainer would wait for a node a pool holds" in found.text + # a quarantined trainer node is no candidate: one pool of target 1 is then too many + (found,) = checks.findings([one], [side], quarantined=lambda s: {"n-0"}) + assert found.level == checks.ERROR and "(1 quarantined not counted)" in found.text + + +def test_c_the_quarantine_is_read_from_the_lease_store(tmp_path): + from yeto.launch import node_quarantine + from yeto.launch.node_lease import open_objects + + store = tmp_path / "leases" + store.mkdir() + inv = _leased(tmp_path, [_raw(f"n-{i}", f"ops@n-{i}") for i in range(3)], store=str(store)) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) + assert checks.lease_quarantines(side) == set() + open_objects(str(store)).write(node_quarantine.shared_key("n-1"), + json.dumps({"run": "r", "reason": "lost"}).encode()) + assert checks.lease_quarantines(side) == {"n-1"} + + +def test_d_without_leases_a_pool_on_any_trainer_node_is_refused(tmp_path): + """Review case D: no lease_store: the launch takes every trainer node (and refuses an + inventory that lists more trainer nodes than the island needs).""" + nodes = [_raw(f"n-{i}", f"ops@n-{i}", roles=["trainer", "sampler"]) for i in range(3)] + inv = tmp_path / "plain.yaml" + inv.write_text(json.dumps({"nodes": nodes})) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) # refused at launch: every trainer node counts + assert [n.name for n in side.nodes] == ["n-0", "n-1", "n-2"] + pool = _pool(tmp_path, "p", ["n-2"], inventory=inv) + (found,) = checks.findings([pool], [side]) + assert found.level == checks.ERROR and "the trainer takes every card of its nodes" in found.text + + +def test_a_pool_of_another_lease_store_on_a_leased_trainer_node_is_refused(tmp_path): + nodes = [_raw(f"n-{i}", f"ops@n-{i}", roles=["trainer", "sampler"]) for i in range(3)] + inv = _leased(tmp_path, nodes) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) + pool = _pool(tmp_path, "p", ["own-2"], lease_store="/srv/other-leases", + inventory_nodes=[_raw("own-2", "ops@n-2", roles=["sampler"])]) + (found,) = checks.findings([pool], [side], quarantined=lambda s: set()) + assert found.level == checks.ERROR # the trainer's leases do not see the pool's + + +def test_one_name_is_one_machine_only_in_one_inventory_file(): + a, b = parse_node(_raw("n", "h1"), index=0), parse_node(_raw("n", "h2"), index=0) + assert checks.same_machine(a, "/i.yaml", b, "/i.yaml") + assert not checks.same_machine(a, "/i.yaml", b, "/j.yaml") + lo = parse_node(_raw("x", "h3", address="127.0.0.1"), index=0) + assert not checks.same_machine(lo, None, parse_node(_raw("y", "h4", address="127.0.0.1"), index=0), None) + assert checks.same_machine(parse_node(_raw("x", "ops@Box-1"), index=0), None, + parse_node(_raw("y", "root@box-1"), index=0), None) + + +def test_the_trainer_side_holds_the_island_nodes_and_its_spares(tmp_path): + inv = tmp_path / "trainers.yaml" + inv.write_text(json.dumps({"nodes": [_raw("t-0", "ops@t-0", roles=["trainer"]), + _raw("t-1", "ops@t-1", roles=["trainer"]), + _raw("s-0", "ops@s-0", roles=["trainer-spare"]), + _raw("p-0", "ops@p-0", roles=["sampler"])]})) + (side,) = checks.trainer_sides([f"ssh:{inv}"], None) + assert [n.name for n in side.nodes] == ["t-0", "t-1"] and [n.name for n in side.spares] == ["s-0"] + assert side.inventory == str(inv.resolve()) and side.entries == [f"ssh:{inv}"] and side.need == 2 + assert side.store is None + assert checks.trainer_sides(["ssh:/nonexistent/inventory.yaml"], None) == [] # its launch dry run says why + pool = _pool(tmp_path, "p", ["s-0"], inventory_nodes=[_sampler("s-0")]) + (found,) = checks.findings([pool], [side]) + assert "which is a trainer-spare node of this run's trainer island" in found.text + + +def test_islands_of_one_inventory_need_their_nodes_together(tmp_path): + inv = tmp_path / "trainers.yaml" + inv.write_text(json.dumps({"nodes": [_raw(f"t-{i}", f"ops@t-{i}", roles=["trainer"]) for i in range(2)]})) + (side,) = checks.trainer_sides(["ssh:2x8xh100"], str(inv)) + assert [n.name for n in side.nodes] == ["t-0", "t-1"] and side.need == 2 + (side,) = checks.trainer_sides(["ssh:1x8xh100", "ssh:1x8xh100"], str(inv)) # two islands + assert [n.name for n in side.nodes] == ["t-0", "t-1"] and side.need == 2 and len(side.entries) == 2 + + +def test_a_leased_trainer_inventory_counts_every_node_the_launch_may_take(tmp_path): + inv = _leased(tmp_path, [_raw(f"t-{i}", f"ops@t-{i}", roles=["trainer"]) for i in range(3)], + store=str(tmp_path / "leases")) + (side,) = checks.trainer_sides(["ssh:1x8xh100"], str(inv)) + assert [n.name for n in side.nodes] == ["t-0", "t-1", "t-2"] and side.need == 1 + + +def test_a_fleet_counts_each_island_once_from_the_trainer_gpu_and_the_islands(): + assert checks.island_entries("ssh:1x8xb300,modal:1x8xb300", ["ssh:1x8xb300", "modal:1x8xb300"]) == \ + ["ssh:1x8xb300"] + assert checks.island_entries("ssh:1x8xb300,ssh:1x8xb300", []) == ["ssh:1x8xb300"] * 2 + assert checks.island_entries(None, ["ssh:2x8xb300", "ssh:1x8xb300"]) == ["ssh:2x8xb300", "ssh:1x8xb300"] + + +def test_one_node_more_than_the_two_pools_can_take_is_refused(tmp_path): + inv = _shared_inventory(tmp_path, 3) + a = _pool(tmp_path, "a", inventory=inv, slots=[0, 1, 2], target=2) + b = _pool(tmp_path, "b", inventory=inv, slots=[0, 1, 2], target=2) + assert _levels(checks.findings([a, b])) == [checks.ERROR] + b = _pool(tmp_path, "b", inventory=inv, slots=[0, 1, 2], target=1) + assert _levels(checks.findings([a, b])) == [checks.NOTE] # 2 + 1 fit the 3 nodes + + +def test_a_node_one_pool_names_and_the_other_may_take_is_counted(tmp_path): + inv = _shared_inventory(tmp_path, 3) + a = _pool(tmp_path, "a", ["own-0"], inventory=inv) + b = _pool(tmp_path, "b", inventory=inv, slots=[0, 1, 2]) + (found,) = checks.findings([a, b]) + assert found.level == checks.NOTE and found.text.startswith("pools a and b may both take node(s) own-0") diff --git a/tests/test_ssh_sampler_pool.py b/tests/test_ssh_sampler_pool.py index ebd0dabca..523fd15e6 100644 --- a/tests/test_ssh_sampler_pool.py +++ b/tests/test_ssh_sampler_pool.py @@ -810,5 +810,5 @@ def test_a_spec_for_another_platform_or_card_is_refused_per_node(): problems = sp.spec_node_problems(family_conf(b300), spec) assert any("cuda node, the spec's platform is rocm" in p for p in problems) assert any("B300 cards, the spec's engine.server.card_model is MI355X" in p for p in problems) - assert sp.spec_node_problems(family_conf(rocm_node()), spec) == [] + assert sp.spec_node_problems(family_conf(rocm_node(), devices=None), spec) == [] # TP8 on the node's 8 cards assert sp.spec_node_problems(family_conf(b300), {"engine": {"server": {"card_model": ""}}}) == [] diff --git a/yeto/launch/nc/cli.py b/yeto/launch/nc/cli.py index b588f7831..67dc5d168 100644 --- a/yeto/launch/nc/cli.py +++ b/yeto/launch/nc/cli.py @@ -870,10 +870,20 @@ def prompts_file_report(cfg: dict[str, Any], spec: dict[str, Any]) -> tuple[list except OSError as error: return [], [f"prompts_file {local}: {error.strerror or error}"], [] rows = sum(1 for line in data.splitlines() if line.strip()) - return [f"prompts_file: {local} ({rows} rows, {len(data)} bytes, sha256 " - f"{hashlib.sha256(data).hexdigest()[:12]}) -> {remote} on every node, checked there at each start"], [], [] + lines = [f"prompts_file: {local} ({rows} rows, {len(data)} bytes, sha256 " + f"{hashlib.sha256(data).hexdigest()[:12]}) -> {remote} on every node, checked there at each start"] + if _own_ssh_pool(cfg): # own nodes: the host path behind prompts.path (a mount, the workdir) + from yeto.launch.ssh_sampler_pool import prompts_report # noqa: PLC0415 + + more, problems, notes = prompts_report(cfg, str(remote)) + return lines + more, problems, notes + return lines, [], [] if not remote: return [], [], [] + if _own_ssh_pool(cfg): # own nodes: the file the node has, where the sampler reads it + from yeto.launch.ssh_sampler_pool import prompts_report # noqa: PLC0415 + + return prompts_report(cfg, str(remote)) provider = cfg.get("provider") if isinstance(cfg.get("provider"), dict) else {} if provider.get("transport") == "sdk": return [], [f"the sampler spec reads prompts.path {remote}, and these sandboxes are reached through the " @@ -885,6 +895,11 @@ def prompts_file_report(cfg: dict[str, Any], spec: dict[str, Any]) -> tuple[list return [], [], [] +def _own_ssh_pool(cfg: dict[str, Any]) -> bool: + provider = cfg.get("provider") if isinstance(cfg.get("provider"), dict) else {} + return provider.get("kind") == "ssh" + + def pool_has_dispenser(cfg: dict[str, Any]) -> bool: """The pool's samplers take their tasks from a dispenser (no task goes to two of them, so the pool may add or remove samplers): the store dispenser diff --git a/yeto/launch/nc/pool_run.py b/yeto/launch/nc/pool_run.py index 165f22e9b..839fcd0d4 100644 --- a/yeto/launch/nc/pool_run.py +++ b/yeto/launch/nc/pool_run.py @@ -71,11 +71,24 @@ "both would order nodes, fence and continue the same shards of the same store") +OWN_NODES_WARNING = ("Own SSH nodes (ssh, price_usd_h 0) are not billed by this pool, but its samplers hold their " + "cards until the pool stops: keep this pool running, or stop it with " + "`python -m yeto.launch.nc pool-stop --config `.") + + def lease_warning(cfg: dict[str, Any], config_path: str) -> str: - """The billing warning of the pool's provider (a National Compute lease, a sandbox, a cloud island).""" + """The billing warning of the pool's provider (a National Compute lease, a sandbox, a cloud island; + own SSH nodes at no price hold their cards, they bill nothing).""" kind = provider_kind(cfg) - text = LEASE_WARNING if is_national_compute(cfg) else SANDBOX_WARNING if kind == "daytona" else \ - CLOUD_WARNING.format(kind=kind) + try: + free = kind == "ssh" and not cli.pool_price(cfg)[0] + except ValueError: # a price that is not a number: the pool config check refuses it + free = False + if free: + text = OWN_NODES_WARNING + else: + text = LEASE_WARNING if is_national_compute(cfg) else SANDBOX_WARNING if kind == "daytona" else \ + CLOUD_WARNING.format(kind=kind) return text.replace("", config_path) STOP_SIGNALS = ("SIGTERM", "SIGINT", "SIGHUP") diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index 44f82ffd4..761f1d99f 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -536,10 +536,12 @@ def parse_inventory(document: Any) -> NodeList: raise InventoryError("the inventory must contain at least one node under nodes:") nodes = [parse_node(entry, index=index, images=images, node_health=health) for index, entry in enumerate(entries)] - for key, label in (("name", "name"), ("host", "SSH target")): + for key, label in (("name", "name"), ("host", "SSH target"), ("address", "address")): seen: dict[str, str] = {} for node in nodes: value = getattr(node, key) + if value is None or (key == "address" and ipaddress.ip_address(value).is_loopback): + continue # no address, or a loopback one (each node's own: a container's rendezvous) if value in seen: raise InventoryError(f"the inventory lists {label} {value!r} twice " f"(nodes {seen[value]} and {node.name})") diff --git a/yeto/launch/own_node_checks.py b/yeto/launch/own_node_checks.py new file mode 100644 index 000000000..afef8005b --- /dev/null +++ b/yeto/launch/own_node_checks.py @@ -0,0 +1,315 @@ +"""Checks of a run's own (SSH inventory) nodes across its pools and its trainer islands. + +``yeto run up`` (and its dry run) checks, before anything starts: + +* two ``provider.kind: ssh`` pools of the run that may take one node of one lease store + (``lease_store``: a node lease is held per node name). A pool skips a node another + pool holds and takes another free one of its slots, so this is refused only when + there are not enough nodes: both pools name the node (``provider.nodes``), or their + targets together exceed the nodes the two pools can take. Otherwise a note says it. + Two pools may share a node's cards (``provider.devices``) through an inventory + without ``lease_store``; +* an ssh pool on a node of the run's own ``ssh:`` trainer islands (their nodes and their + ``trainer-spare`` nodes). Without node leases common to both (one lease store, one + node name) the trainer takes every card of its nodes: refused. With them, the + trainer picks free nodes and skips one a pool holds: refused only when the trainer + nodes left after the pools' (quarantined nodes not counted) are fewer than the + islands need; otherwise a warning. + +One machine is one SSH host (``host`` after any ``user@``), one cluster address +(``address``, a loopback one excepted: it is each container's own), or one node name of +one inventory file. +""" + +from __future__ import annotations + +import ipaddress +import os +from collections import Counter +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from .node_inventory import Node + +ERROR, WARN, NOTE = "error", "warn", "note" + + +@dataclass(frozen=True) +class Finding: + level: str # ERROR refuses the run; WARN / NOTE are preflight lines + text: str + + +@dataclass(frozen=True) +class OwnPool: + """An ssh pool of the run: the nodes its slots may take, its target, and whether it + names them (``provider.nodes``).""" + + name: str + nodes: tuple[Node, ...] + target: int + named: bool + store: str | None + inventory: str | None + + +@dataclass +class TrainerSide: + """The ``ssh:`` trainer islands of one inventory file: their entries (one per island), + the nodes they may take (``nodes``; every trainer node when they are picked at launch), + the inventory's spares, its lease store and the nodes the islands need.""" + + inventory: str | None + store: str | None + entries: list[str] = field(default_factory=list) + nodes: list[Node] = field(default_factory=list) + spares: list[Node] = field(default_factory=list) + need: int = 0 + quarantined: set[str] = field(default_factory=set) + + +def _path(value: Any) -> str | None: + if not value: + return None + try: + return str(Path(os.path.expanduser(str(value))).resolve()) + except OSError: + return str(value) + + +def store_key(value: Any) -> str | None: + """A lease store as one key (:func:`~.node_inventory.parse_lease_store`; ``file://`` + and the bare directory are one store).""" + from .node_inventory import InventoryError, parse_lease_store # noqa: PLC0415 + + try: + uri = parse_lease_store(value) + except InventoryError: + return None + if uri is not None and uri.startswith("file://"): + uri = uri[len("file://"):] + return uri + + +def _host(node: Node) -> str: + return str(node.host).rsplit("@", 1)[-1].strip().lower() + + +def _address(node: Node) -> str | None: + address = getattr(node, "address", None) + if not address: + return None + try: + return None if ipaddress.ip_address(address).is_loopback else str(address) + except ValueError: + return str(address) + + +def same_machine(a: Node, a_inventory: str | None, b: Node, b_inventory: str | None) -> bool: + """One machine (module doc): one SSH host (any user), one address, or one name of one inventory.""" + if _host(a) == _host(b): + return True + if _address(a) is not None and _address(a) == _address(b): + return True + return a.name == b.name and a_inventory is not None and a_inventory == b_inventory + + +def own_pools(pools: Sequence[tuple[str, Mapping[str, Any]]]) -> list[OwnPool]: + """The run's ssh pools (``(name, pool config)``; another kind, or a config its own + checks refuse, is skipped: its pool dry run says why).""" + from .nc.cli import slot_list # noqa: PLC0415 + from .ssh_sampler_pool import parse_config # noqa: PLC0415 + + out = [] + for name, cfg in pools: + provider = cfg.get("provider") if isinstance(cfg.get("provider"), Mapping) else {} + if provider.get("kind") != "ssh": + continue + try: + conf = parse_config(dict(cfg)) + slots = slot_list(dict(cfg)) if ("slots" in cfg or "accounts" in cfg) else list(range(len(conf.nodes))) + target = int(cfg.get("target", 1)) + except (ValueError, TypeError, KeyError, OSError): + continue + nodes = tuple(conf.nodes[s] for s in dict.fromkeys(slots) if 0 <= int(s) < len(conf.nodes)) + out.append(OwnPool(name, nodes, target, provider.get("nodes") is not None, store_key(conf.lease_store), + _path(provider.get("inventory")))) + return out + + +def _pool_pair(a: OwnPool, b: OwnPool) -> Finding | None: + if a.store is None or a.store != b.store: + return None # a node lease is taken per node in one lease store: no common store, no wait + shared = [n.name for n in a.nodes if any(m.name == n.name for m in b.nodes)] + if not shared: + return None + union = {n.name for n in a.nodes} | {n.name for n in b.nodes} + ways = ("Either give the pools an inventory without lease_store and split the nodes' cards with " + "provider.devices, or put the pools on different nodes") + if a.named and b.named: + return Finding(ERROR, f"pools {a.name} and {b.name} both name node(s) {', '.join(shared)} in provider.nodes " + f"on an inventory with node leases (lease_store {a.store}): a node lease is held per " + f"node, so the pool that does not hold one waits for it while the other runs. {ways}") + if a.target + b.target > len(union): + return Finding(ERROR, f"pools {a.name} and {b.name} share node(s) {', '.join(shared)} of an inventory with " + f"node leases (lease_store {a.store}): their targets ({a.target} + {b.target}) are " + f"more than the {len(union)} node(s) the two can take, so a pool waits for a node " + f"the other holds. {ways}") + return Finding(NOTE, f"pools {a.name} and {b.name} may both take node(s) {', '.join(shared)} (lease_store " + f"{a.store}): a pool skips a node the other holds; their targets ({a.target} + {b.target}) " + f"fit the {len(union)} node(s) they can take") + + +def _protected(pool: OwnPool, side: TrainerSide, pool_node: Node, trainer_node: Node) -> bool: + """The pool's and the trainer's leases see each other on this node: one lease store, one name.""" + return side.store is not None and pool.store == side.store and pool_node.name == trainer_node.name + + +def _trainer_findings(pools: Sequence[OwnPool], side: TrainerSide, + quarantined: Callable[[TrainerSide], set[str]]) -> list[Finding]: + out: list[Finding] = [] + entries = ", ".join(dict.fromkeys(side.entries)) + overlap: dict[str, list[str]] = {} # pool -> its nodes on the trainer's (leased: may share) + leased_nodes: set[str] = set() + for pool in pools: + for node in pool.nodes: + for t, spare in [(t, False) for t in side.nodes] + [(t, True) for t in side.spares]: + if not same_machine(node, pool.inventory, t, side.inventory): + continue + what = "a trainer-spare node" if spare else "a node" + if not _protected(pool, side, node, t): + out.append(Finding(ERROR, f"pool {pool.name} starts samplers on node {node.name}, which is {what} " + f"of this run's trainer island {entries} ({t.name}): the trainer takes " + "every card of its nodes. Put the pool on nodes with the sampler role " + "only (inventory roles), or name them in provider.nodes")) + elif spare: + out.append(Finding(WARN, f"pool {pool.name} may take node {node.name}, a trainer-spare node of " + f"this run's trainer island {entries}: while the pool holds its lease " + f"(lease_store {side.store}) it cannot replace a lost trainer node")) + else: + overlap.setdefault(pool.name, []).append(node.name) + leased_nodes.add(node.name) + break + if not overlap: + return out + gone = quarantined(side) + candidates = [t.name for t in side.nodes if t.name not in gone] + by_pool = {p.name: p for p in pools} + held = min(len(leased_nodes & set(candidates)), + sum(min(by_pool[name].target, len(set(nodes) & set(candidates))) for name, nodes in overlap.items())) + left = len(candidates) - held + shown = "; ".join(f"pool {name} on {', '.join(nodes)}" for name, nodes in overlap.items()) + counted = (f"{len(candidates)} trainer node(s)" + (f" ({len(gone)} quarantined not counted)" if gone else "") + + f", the pools may hold {held} of them, {left} left for the {side.need} node(s) the islands need") + if left < side.need: + out.append(Finding(ERROR, f"{shown}: trainer nodes of this run's trainer island(s) {entries} (lease_store " + f"{side.store}): {counted}; the trainer would wait for a node a pool holds. Put " + "the pools on nodes with the sampler role only, or lower their targets")) + else: + out.append(Finding(WARN, f"{shown}: trainer nodes of this run's trainer island(s) {entries}; the trainer " + f"skips a node a pool holds (lease_store {side.store}): {counted}")) + return out + + +def findings(pools: Sequence[tuple[str, Mapping[str, Any]]], sides: Sequence[TrainerSide] = (), *, + quarantined: Callable[[TrainerSide], set[str]] | None = None) -> list[Finding]: + """The checks of the module doc for the run's ``(pool name, pool config)`` against + its trainer side ``sides`` (:func:`trainer_sides`). ``quarantined``: the quarantined + nodes of a leased side (default :func:`lease_quarantines`; read only when a pool + may share its nodes).""" + own = own_pools(pools) + out = [] + for i, a in enumerate(own): + for b in own[i + 1:]: + found = _pool_pair(a, b) + if found is not None: + out.append(found) + for side in sides: + out += _trainer_findings(own, side, quarantined or lease_quarantines) + return out + + +def lease_quarantines(side: TrainerSide) -> set[str]: + """The side's trainer nodes quarantined in its lease store (``node_quarantine``: any + run's record); none when the store cannot be opened (the launch reads it again).""" + if side.store is None: + return set() + from .node_lease import open_objects # noqa: PLC0415 + from .node_quarantine import shared_quarantines # noqa: PLC0415 + + try: + return set(shared_quarantines(open_objects(side.store), [n.name for n in side.nodes])) + except Exception: # noqa: BLE001 - not read here: every node counts (the launch reads it) + return set() + + +def _need(entry: str, every: Sequence[Node]) -> int: + from ..gpu_spec import parse_gpu_spec # noqa: PLC0415 + from .node_inventory import island_nodes # noqa: PLC0415 + + try: + (spec,) = parse_gpu_spec(entry) + return int(spec.num_nodes) + except (ValueError, TypeError): # ssh:: every trainer node of it + return len(island_nodes(list(every), "trainer")) + + +def trainer_sides(entries: Sequence[str], inventory: str | None) -> list[TrainerSide]: + """The trainer side of the run's ``ssh:`` island entries (``--gpu``, one per island), + by inventory file: the nodes the islands take and the inventory's ``trainer-spare`` + nodes. Every trainer node of the inventory counts when the islands' nodes are picked + at launch (a leased inventory, or several islands of one inventory) or the entry is + refused there. An entry whose inventory does not load is skipped (the trainer + launch's own dry run says why).""" + from .node_inventory import InventoryError, island_nodes, lease_store_of, load_inventory # noqa: PLC0415 + from .node_quarantine import SPARE_ROLE # noqa: PLC0415 + from .preflight.cluster import resolve_inventory # noqa: PLC0415 + + sides: dict[str | None, TrainerSide] = {} + every_of: dict[str | None, Any] = {} + picked: dict[str | None, list[list[Node]] | None] = {} + for entry in entries: + rest = entry[4:] + own_file = rest.endswith((".yaml", ".yml", ".json")) or Path(rest).expanduser().is_file() + source = rest if own_file else inventory + path = _path(source) + if path not in every_of: + try: + every_of[path] = load_inventory(Path(str(source)).expanduser()) + except (InventoryError, OSError, ValueError, TypeError): + every_of[path] = None + every = every_of[path] + if every is None: + continue + side = sides.setdefault(path, TrainerSide(path, store_key(lease_store_of(every)))) + side.entries.append(entry) + side.need += _need(entry, every) + try: + nodes, _every = resolve_inventory(entry, inventory) + if picked.get(path, []) is not None: + picked.setdefault(path, []).append(list(nodes)) + except (InventoryError, OSError, ValueError): # refused at launch, or picked there + picked[path] = None + for path, side in sides.items(): + every = every_of[path] + rows = picked.get(path) + if side.store is not None or rows is None or len(rows) > 1: # picked at launch: any trainer node + side.nodes = island_nodes(list(every), "trainer") + else: + side.nodes = list(rows[0]) + side.spares = [n for n in every if SPARE_ROLE in n.roles and n.name not in {t.name for t in side.nodes}] + return list(sides.values()) + + +def island_entries(argv_gpu: str | None, island_gpus: Sequence[str] = ()) -> list[str]: + """The ``ssh:`` entries of the run's trainer islands, one per island: the trainer's + ``--gpu`` (a fleet's compile lists every island's cluster there) and the fleet + islands' own (each counted once, however many lists name it).""" + from .preflight.gate import ssh_entries # noqa: PLC0415 + + counts = Counter(ssh_entries(argv_gpu)) + for entry, n in Counter(e for gpu in island_gpus for e in ssh_entries(gpu)).items(): + counts[entry] = max(counts[entry], n) + return [e for e, n in counts.items() for _ in range(n)] diff --git a/yeto/launch/ssh_sampler_pool.py b/yeto/launch/ssh_sampler_pool.py index 01b1dac35..6ccecfc80 100644 --- a/yeto/launch/ssh_sampler_pool.py +++ b/yeto/launch/ssh_sampler_pool.py @@ -177,6 +177,10 @@ class SshSamplerError(RuntimeError): """A start that cannot go on (preflight refused, the launch did not come up).""" +class PromptsConfigError(SshSamplerError): + config_error = True # the pool config's prompts_file / prompts.path: no retry fixes it + + class PreflightError(SshSamplerError): config_error = False # a busy card or a full disk is this node's, not the config's @@ -274,6 +278,10 @@ def parse_config(cfg: Mapping[str, Any], *, inventory: Sequence[Node] | None = N if missing: raise ValueError(f"ssh provider: nodes {missing} are not in the inventory ({sorted(by_name)})") nodes = [by_name[n] for n in names] + other = [f"{n.name} (roles: {', '.join(n.roles)})" for n in nodes if n.roles and "sampler" not in n.roles] + if other: # a node with roles serves those roles only (no roles: any) + raise ValueError(f"ssh provider: nodes {'; '.join(other)} have no sampler role in the inventory; add " + "sampler to their roles, or name sampler nodes in provider.nodes") if not nodes: raise ValueError("ssh provider: no sampler node (nodes, or inventory nodes with role sampler)") unreachable = [f"{n.name} ({n.reach.mode})" for n in nodes if n.reach is not None and n.reach.mode in @@ -1336,6 +1344,56 @@ def put(self, node: Node, text: str, remote: str, *, mode: str = "644") -> None: if out.returncode != 0: raise SshSamplerError(f"upload {remote} to {node.name}: {_text(out.stderr)[-300:]}") + def upload_prompts(self, node: Node, spec: Mapping[str, Any]) -> dict[str, Any]: + """The pool's ``prompts_file`` at the host path behind the spec's ``prompts.path`` + on ``node`` (:func:`prompts_host_path`), checked there by size and sha256 against + the local file: a copy that matches already is kept (``uploaded`` False), else the + file is streamed there (a temp name of this shell, then renamed) and checked again. + :class:`PromptsConfigError` (not retried) when the sampler would not see the path + or the local file is missing; SshSamplerError when the copy fails or does not match.""" + from yeto.node.transport import size_sha256_command # noqa: PLC0415 + + local = Path(os.path.expanduser(str(self.cfg["prompts_file"]))) + prompts = spec.get("prompts") if isinstance(spec.get("prompts"), Mapping) else {} + remote = str(prompts.get("path") or "") + host, _where = prompts_host_path(self.conf, node, remote) + if host is None: + raise PromptsConfigError(f"prompts_file {local}: the sampler spec's prompts.path " + f"{remote or '(unset)'!r} is under no mount or workdir of {node.name}: the " + "sampler would not see it") + try: + size, digest = file_size_sha256(local) + except OSError as error: + raise PromptsConfigError(f"prompts_file {local}: {error.strerror or error}") from None + copy = {"bytes": size, "sha256": digest} + + def matches() -> tuple[bool, str]: + out = self.ssh(node, size_sha256_command(host), timeout=120) + have = next((ln.split()[1:] for ln in _text(out.stdout).splitlines() if ln.startswith("YETO_PROMPTS ")), []) + return have == [str(size), digest], " ".join(have) or "unreadable" + + same, _have = matches() + if same: + _log(f"ssh pool: {node.name}: prompts_file {local} is at {host} already ({size} bytes, sha256 " + f"{digest[:12]}): kept") + return {"path": remote, "host": host, "uploaded": False, **copy} + out = self.ssh(node, f"mkdir -p {shlex.quote(str(Path(host).parent))}", timeout=60) + if out.returncode != 0: + raise SshSamplerError(f"prompts upload to {node.name}: {_text(out.stderr)[-300:]}") + q = shlex.quote(host) + with local.open("rb") as stream: # streamed: a large file is not held in memory + out = self.ssh(node, f"umask 077; t={q}.tmp.$$; cat > \"$t\" && chmod 644 \"$t\" && mv -f \"$t\" {q} " + "|| { rm -f \"$t\"; exit 1; }", stdin=stream, timeout=upload_timeout_s(size)) + if out.returncode != 0: + raise SshSamplerError(f"prompts upload {host} to {node.name} (exit {out.returncode}): " + f"{_text(out.stderr)[-300:]}") + same, have = matches() + if not same: + raise SshSamplerError(f"{node.name}: prompts file {host} does not match {local} after the upload " + f"(node size/sha256 {have}, local {size} {digest[:12]})") + _log(f"ssh pool: {node.name}: prompts_file {local} -> {host} ({size} bytes, sha256 {digest[:12]}) checked") + return {"path": remote, "host": host, "uploaded": True, **copy} + def upload_code(self, node: Node) -> str: """``git archive`` (gzip: a slow launcher link) of ``yeto/`` at ``code_ref`` into ``/yeto/`` (idempotent: a tree already there is kept).""" @@ -1428,6 +1486,8 @@ def start(self, m, shards: list[str]) -> None: self.event("ssh_pool_idle_unchecked", node=node.name, shard=m.shard, detail=facts["idle"]) yeto_dir = self.upload_code(node) spec = self.spec_for(m, shards) + if self.cfg.get("prompts_file"): # at every start, as the rented-node route: copied, then checked there + self.upload_prompts(node, spec) route = self.node_route_for(node) if route is None: self.put(node, json.dumps(spec, indent=1), p["spec"]) @@ -1843,9 +1903,136 @@ def spec_node_problems(conf: SshPoolConf, spec: Mapping[str, Any]) -> list[str]: f"engine.server.card_model is {card}") except UnknownCard: pass + have = int(node.cards_per_node) + beyond = [d for d in conf.devices or () if d >= have] + if beyond: + out.append(f"ssh provider: node {node.name} has {have} cards (indexes 0-{have - 1}); provider.devices " + f"{beyond} are not on it") + try: + tp = spec_tp(spec) + except ValueError as error: + out.append(f"ssh provider: {error}") + continue + cards = min(len(conf.devices), have) if conf.devices else have + if tp is not None and tp > cards: + where = (f"provider.devices {list(conf.devices)} give it {cards}" if conf.devices + else f"it has {cards}") + out.append(f"ssh provider: node {node.name}: the spec's engine tensor parallel size is {tp} cards, " + f"{where}; lower engine.options.tp or give the pool more cards of the node") return out +# the adapters' own ``tp`` defaults (VllmOptions, SGLangOptions; the launch layer imports no +# adapter: tests/test_ssh_pool_checks.py holds the two equal) +ADAPTER_DEFAULT_TP = {"vllm-server": 4, "sglang-server": 8} + + +def spec_tp(spec: Mapping[str, Any]) -> int | None: + """The cards one sampler server spans: ``engine.options.tp`` (a whole number, or its + decimal string), else the adapter's default (vllm-server, sglang-server); None for + another adapter. ValueError when ``tp`` is no whole number >= 1.""" + engine = spec.get("engine") if isinstance(spec.get("engine"), Mapping) else {} + options = engine.get("options") if isinstance(engine.get("options"), Mapping) else {} + tp = options.get("tp") + if tp is None: + tp = ADAPTER_DEFAULT_TP.get(str(engine.get("adapter"))) + if tp is None: + return None + if isinstance(tp, str) and tp.strip().isdigit(): + tp = int(tp.strip()) + if isinstance(tp, bool) or not isinstance(tp, int) or tp < 1: + raise ValueError(f"engine.options.tp must be a whole number of cards >= 1, not {tp!r}") + return tp + + +PROMPTS_WORKDIR, PROMPTS_MOUNT, PROMPTS_HOST = "workdir", "mount", "host" +UPLOAD_BYTES_PER_S = 10 * 1024 * 1024 # the slowest link a prompts upload is given time for +UPLOAD_TIMEOUT_MAX_S = 1800 + + +def upload_timeout_s(size: int) -> float: + """The time a ``size``-byte upload is given: 60 s plus the bytes at 10 MiB/s, at most 30 min.""" + return min(float(UPLOAD_TIMEOUT_MAX_S), 60.0 + size / UPLOAD_BYTES_PER_S) + + +def file_size_sha256(path: Path) -> tuple[int, str]: + """``(bytes, sha256 hex)`` of a local file, read in chunks.""" + import hashlib # noqa: PLC0415 + + digest, size = hashlib.sha256(), 0 + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1 << 20), b""): + digest.update(chunk) + size += len(chunk) + return size, digest.hexdigest() + + +def prompts_host_path(conf: SshPoolConf, node: Node, path: str) -> tuple[str | None, str | None]: + """``(host path, where)`` of the sampler's ``prompts.path`` on ``node``: under the + pool's workdir (``workdir``), under a mount (``mount``: the inventory's or the pool's + ``container.mounts``, the path on the host behind it), or (runtime venv, which reads + the host itself) elsewhere on the host (``host``). ``(None, None)``: the container + sees no such path (no mount or workdir holds it), or the path is not absolute.""" + if not str(path).startswith("/"): + return None, None + path = str(path).rstrip("/") + + def under(path: str, base: str) -> bool: + base = base.rstrip("/") + return path == base or path.startswith(base + "/") + + if under(path, conf.workdir): + return path, PROMPTS_WORKDIR + if conf.runtime == "venv": # the sampler reads the host's own paths + if any(under(path, host) for host in node.mounts): + return path, PROMPTS_MOUNT + return path, PROMPTS_HOST + seen = {**dict(node.mounts), **dict(conf.container.mounts if conf.container else {})} + if conf.store: + seen.setdefault(conf.store, conf.store) + inside = sorted(((str(i).rstrip("/"), str(h).rstrip("/")) for h, i in seen.items() if under(path, str(i))), + key=lambda pair: -len(pair[0])) + if not inside: + return None, None + mount, host = inside[0] + return host + path[len(mount):], PROMPTS_MOUNT + + +def prompts_report(cfg: Mapping[str, Any], remote: str) -> tuple[list[str], list[str], list[str]]: + """``pool --dry-run`` (:func:`yeto.launch.nc.cli.prompts_file_report`) of an ssh pool + whose spec reads ``prompts.path`` ``remote``: ``(lines, problems, notes)``. With + ``prompts_file`` the file goes to the host path behind ``remote`` on every node at each + start (checked there by size and sha256): a path no node's sampler sees is a problem. + Without it the sampler reads the file the node has: a note says where, a ``WARNING`` + line when the container sees no such path (no mount or workdir holds it).""" + try: + conf = parse_config(dict(cfg)) + except (ValueError, TypeError, KeyError, OSError): + return [], [], [] # offline_problems reports it + rows = [(node, *prompts_host_path(conf, node, remote)) for node in conf.nodes] + unseen = [node.name for node, host, _where in rows if host is None] + hosts = sorted({str(host) for _node, host, _where in rows if host is not None}) + seen_text = f"workdir {conf.workdir}, the inventory mounts or provider.container.mounts" + if cfg.get("prompts_file"): + if unseen: + return [], [f"prompts_file: the sampler spec's prompts.path {remote} is under no mount or workdir of " + f"nodes {unseen} ({seen_text}): an upload there is not seen by the sampler; point " + "prompts.path under the pool's workdir or a mount"], [] + return [f"prompts_file: uploaded to {', '.join(hosts)} on every node of the pool"], [], [] + if unseen: + return [f"WARNING: the sampler spec reads prompts.path {remote}, which the sampler container on nodes " + f"{unseen} cannot read (no mount or workdir holds it: {seen_text}); set prompts_file to upload " + "it (checked by size and sha256 at every start), or point prompts.path under the workdir or a " + "mount"], [], [] + wheres = sorted({where for _node, _host, where in rows}) + place = {PROMPTS_WORKDIR: f"the pool's workdir {conf.workdir}", PROMPTS_MOUNT: "an inventory or pool mount", + PROMPTS_HOST: "the node's own filesystem"} + where = " / ".join(place[w] for w in wheres) + return [], [], [f"the sampler spec reads prompts.path {remote} from the node ({where}; on the host " + f"{', '.join(hosts)}): put the file there before the run, or set prompts_file " + "(uploaded and checked by size and sha256 at every start)"] + + def spec_of(cfg: Mapping[str, Any]) -> dict[str, Any]: """The pool's sampler spec file as written (``{}`` when it cannot be read: the pool's own checks report that).""" diff --git a/yeto/rl/up.py b/yeto/rl/up.py index dacbfd513..b8d05c684 100644 --- a/yeto/rl/up.py +++ b/yeto/rl/up.py @@ -1343,7 +1343,7 @@ def preflight(self, *, dry_run: bool = False) -> bool: _log(f"preflight: {problem}") self.mark("preflight", ok=False) return False - problem = self.rules_problem() + problem = self.rules_problem() or self.own_nodes_problem() if problem is not None: _log(f"preflight: {problem}") self.mark("preflight", ok=False) @@ -1504,6 +1504,37 @@ def _cluster_preflight(self, *, dry_run: bool, check_nodes: bool, egress: bool) self.cluster_preflight_passed = True return ok + def own_nodes_problem(self) -> str | None: + """Two ``kind: ssh`` pools of the run short of nodes of one lease store, or an ssh + pool on a node of the run's ``ssh:`` trainer islands (:mod:`yeto.launch.own_node_checks`): + the run is refused before anything starts (its dry run too); a warning or a note + is a preflight line. None otherwise.""" + from yeto.launch import own_node_checks # noqa: PLC0415 + from yeto.launch.preflight.gate import argv_value # noqa: PLC0415 + + pools = [] + for ref in self.pools: + try: + cfg = ref.load() + except (OSError, ValueError): + continue # an unreadable pool config: its pool dry run says so + if isinstance(cfg, dict) and str((cfg.get("provider") or {}).get("kind") or "") == "ssh": + pools.append((ref.name, cfg)) + if not pools: + return None + argv = [str(a) for a in self.cfg["trainer"]["argv"]] + plan = self.fleet_plan() + entries = own_node_checks.island_entries(argv_value(argv, "--gpu"), + [island.gpu for island in (plan.islands if plan is not None else ())]) + sides = own_node_checks.trainer_sides(entries, argv_value(argv, "--rl-node-inventory")) + errors = [] + for found in own_node_checks.findings(pools, sides): + if found.level == own_node_checks.ERROR: + errors.append(found.text) + else: + _log(f"preflight: {'WARNING' if found.level == own_node_checks.WARN else 'note'}: {found.text}") + return "; ".join(errors) + "; nothing is started" if errors else None + def own_node_targets(self) -> list[tuple[Any, tuple[Any, ...]]]: """``(node, endpoints)`` of every own (SSH inventory) node of the run: the nodes of the trainer's ``ssh:`` islands (the run store and the trainer image's registry) and