Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/COST_GUARD.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ How cost is computed:
wire overhead. The ledger entry's `egress_events` lists which of these events count.
- **National Compute**: lease duration × rate. A lease past its `lease_until` keeps billing until it is
deleted, and it is counted that way. Set `YETO_NC_USD_PER_GPU_HOUR` (or `YETO_NC_USD_PER_UCR`) to price it.
- **SSH trainer nodes** (a node inventory): the inventory's `price_per_card_hour` times the cards. When
no node of an incarnation declares `price_per_card_hour`, the nodes are the operator's own machines and
count as $0 (not unpriced, no `cost_unpriced` warning), as for an `ssh:` sampler pool. When only some
of its nodes declare a price, the incarnation is unpriced (a forgotten price is never read as $0).
- A resource without a known rate is reported as **unpriced** (`cost_unpriced` event), never as $0, and
is not counted toward the budget. Configure a rate for it.

Expand Down
66 changes: 66 additions & 0 deletions tests/test_fabric_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,72 @@ def test_three_connected_nodes_form_a_group_and_a_socket_node_is_fabric_unavaila
assert sum("torch.distributed.run" in s for _, s in ops.scripts) == 2 * 6 # every pair ran its own NCCL


def _tcp_inventory(tmp_path, fabrics):
path = tmp_path / "nodes.yaml"
path.write_text(yaml.safe_dump({"nodes": [_entry(i, fabric=f) for i, f in enumerate(fabrics)]}))
return path


def test_a_tcp_node_is_no_group_and_no_probe_failure_with_a_next_step(tmp_path, capsys):
"""Rehearsal: tcp nodes were first said to "get no group", then reported "fabric
unavailable" (with the ib_write_bw noise of their pairs) and the probe exited 1."""
path = _tcp_inventory(tmp_path, ["ib", "ib", "tcp"])
assert cluster_cli.main(_args(path, "--write"), ops=_ops_for(path), log=lambda m: None) == 0
cap = capsys.readouterr()
assert "nodes ['b300-2'] declare no RDMA fabric (ib / roce): they get no group" in cap.err
(tcp,) = [x for x in cap.out.splitlines() if "b300-2" in x]
assert tcp.startswith(f"{fg.NO_RDMA}: b300-2: fabric tcp in the inventory: no group, single-node islands only")
assert f"next: {fg.NO_RDMA_NEXT}" in tcp and fg.UNAVAILABLE not in cap.out
groups = {n.name: n.fabric_group for n in load_inventory(path)}
assert groups["b300-0"] == groups["b300-1"] != FABRIC_UNAVAILABLE and groups["b300-2"] == FABRIC_UNAVAILABLE


def test_a_probe_of_tcp_nodes_only_says_so_for_every_node_and_exits_0(tmp_path, capsys):
path = _tcp_inventory(tmp_path, ["tcp", "tcp"])
assert cluster_cli.main(_args(path, "--json"), ops=_ops_for(path), log=lambda m: None) == 0
record = json.loads(capsys.readouterr().out)
assert record["groups"] == {} and record["unavailable"] == {} and record["bad_edges"] == []
assert record["no_rdma"] == {"b300-0": "tcp", "b300-1": "tcp"}


def test_a_tcp_node_that_fails_its_node_checks_fails_the_probe_with_the_reason(tmp_path, capsys):
"""REV-904b M2: a tcp node whose image pull is refused is a probe failure (main: rc 1 with
the image_pull reason), not "nothing to do"."""
path = _tcp_inventory(tmp_path, ["ib", "ib", "tcp"])
ops = _ops_for(path, behaviors={"b300-2": Behavior(pull=(1, "pull access denied for x"))})
assert cluster_cli.main(_args(path), ops=ops, log=lambda m: None) == 1
(tcp,) = [x for x in capsys.readouterr().out.splitlines() if "b300-2" in x]
assert tcp.startswith(f"{fg.NO_RDMA}: b300-2: fabric tcp") and "node checks FAILED: image_pull:" in tcp
assert "pull access denied" in tcp and f"next: {fg.NO_RDMA_FAILED_NEXT}" in tcp and "nothing to do" not in tcp
path = _tcp_inventory(tmp_path, ["tcp", "tcp"])
ops = _ops_for(path, behaviors={"b300-1": Behavior(pull=(1, "pull access denied for x"))})
assert cluster_cli.main(_args(path, "--json"), ops=ops, log=lambda m: None) == 1
record = json.loads(capsys.readouterr().out)
assert list(record["no_rdma_failed"]) == ["b300-1"] and record["no_rdma"] == {"b300-0": "tcp", "b300-1": "tcp"}
path = _tcp_inventory(tmp_path, ["ib", "ib", "tcp"])
ops = _ops_for(path, behaviors={"b300-2": Behavior(ssh_rc=255)})
assert cluster_cli.main(_args(path, "--force"), ops=ops, log=lambda m: None) == 1 # past the idle check
(tcp,) = [x for x in capsys.readouterr().out.splitlines() if "b300-2" in x]
assert "node checks FAILED: ssh:" in tcp # unreachable: a failure (a clock skew alone is not)


def test_declared_roce_nodes_are_grouped_and_never_no_rdma():
names = ["r-0", "r-1"]
states = [SimpleNamespace(node=SimpleNamespace(name=n, fabric="roce", env={}, cards_per_node=8), ports=None)
for n in names]
result = fg.group_nodes(names, _pair_checks(names), states=states)
assert result.no_rdma == {} and list(result.groups.values()) == [names] and result.clean
tcp = [SimpleNamespace(node=SimpleNamespace(name=n, fabric="tcp", env={}, cards_per_node=8), ports=None)
for n in names]
assert fg.group_nodes(names, _pair_checks(names), states=tcp).no_rdma == {"r-0": "tcp", "r-1": "tcp"}


def test_a_declared_ib_node_that_runs_over_sockets_stays_fabric_unavailable():
nodes, ops = _cluster(2, socket={"b300-1"})
result = _probe(nodes, ops)
assert result.no_rdma == {} and list(result.unavailable) == ["b300-0", "b300-1"] and not result.clean


def test_a_triangle_with_a_missing_edge_is_no_group_of_three():
names = ["b300-0", "b300-1", "b300-2"]
result = fg.group_nodes(names, _pair_checks(names, socket={("b300-0", "b300-2")}))
Expand Down
16 changes: 16 additions & 0 deletions tests/test_node_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,22 @@ def test_the_probe_finds_trainer_process_groups_and_venv_samplers(tmp_path):
assert os.environ.get("FAKE_STATE_DIR") is None


def test_the_probe_prints_each_finding_once(tmp_path):
"""Rehearsal: one labelled trainer container named ``yeto-<run>-...`` on a docker node
whose ``sudo -n`` works was printed four times (two views x label and name listing)."""
import subprocess

env = _node_bin(tmp_path)
rows = [{"name": "yeto-run-a-fake", "labels": {node_lease.RUN_LABEL: "run-a"}}]
for view in ("docker", "docker-root"): # docker's one daemon: both views list the container
(tmp_path / f"{view}.json").write_text(json.dumps(rows))
out = subprocess.run(["bash", "-c", node_lease.still_runs_script("run-a", sudo=True)], capture_output=True,
text=True, env=env).stdout
lines = [x for x in out.splitlines() if x.startswith(node_lease.PROBE_MARK)]
assert lines == [f"{node_lease.PROBE_MARK} found=container:yeto-run-a-fake", f"{node_lease.PROBE_MARK} done"]
assert node_lease.parse_probe(out) == (True, ["container:yeto-run-a-fake"])


def test_the_node_runtime_labels_its_containers_only_when_asked(tmp_path):
from tests.test_ssh_sampler_pool import conf
from yeto.node import launch as node_launch
Expand Down
52 changes: 49 additions & 3 deletions tests/test_ssh_trainer_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import dataclasses
import functools
import json
import os
import subprocess
from pathlib import Path
Expand Down Expand Up @@ -249,7 +250,7 @@ def run(self, n, script, *, timeout):
assert [r.id for r in ledger.open_resources()] == ["k31/trainer-i4"]


def test_cost_prices_an_incarnation_by_the_declared_price_or_leaves_it_unpriced(tmp_path):
def test_cost_prices_an_incarnation_by_the_declared_price_or_at_zero_on_own_nodes(tmp_path):
ledger = ResourceLedger(tmp_path / "resources.jsonl", clock=lambda: 1000.0)
nodes = [b300(i, price_per_card_hour=1.0) for i in range(6)]
for i, priced in ((1, nodes), (2, [b300(0)])):
Expand All @@ -258,8 +259,53 @@ def test_cost_prices_an_incarnation_by_the_declared_price_or_leaves_it_unpriced(
summary = billing.resource_costs(ledger.resources(), now=1000.0 + 1800)
by_id = {item.key: item for item in summary.items}
assert by_id["ssh_trainer:k31/t-i1"].estimated_usd == pytest.approx(24.0) # 48 cards, $1, 30 min
assert not by_id["ssh_trainer:k31/t-i2"].priced
assert "price_per_card_hour" in by_id["ssh_trainer:k31/t-i2"].note
own = by_id["ssh_trainer:k31/t-i2"] # no price: the operator's own node, $0 and not unpriced
assert own.priced and own.estimated_usd == 0.0 and "price_per_card_hour" in own.note
assert summary.unpriced == []


def test_a_partly_priced_incarnation_stays_unpriced_and_the_guard_warns(tmp_path):
"""REV-904b M1: 5 nodes at $3 per card hour and one without a price is not $0."""
from yeto.cost.guard import CostGuard, GuardConfig

ledger = ResourceLedger(tmp_path / "resources.jsonl", clock=lambda: 1000.0)
nodes = [b300(i, price_per_card_hour=3.0) for i in range(5)] + [b300(5)]
attrs = ssh_trainer_ledger.created_attrs(run_id="k31", island="t", incarnation=0, nodes=nodes, docker=True,
kill_grace_s=30)
assert (attrs["usd_per_hour"], attrs["priced_nodes"], attrs["unpriced_nodes"]) == (None, 5, 1)
ledger.created("ssh_trainer", "k31/t-i0", "t-i0", **attrs)
(item,) = billing.resource_costs(ledger.resources(), now=1000.0 + 1800).items
assert not item.priced and item.rate_usd_per_hour is None and "1 of 6 SSH nodes" in item.note
guard = CostGuard("k31", GuardConfig(), ledger=ledger, events_path=tmp_path / "events.jsonl",
clock=lambda: 1000.0 + 600, log=lambda *_: None)
guard.tick()
events = [json.loads(x) for x in (tmp_path / "events.jsonl").read_text().splitlines()]
assert [e["resource"] for e in events if e.get("event") == "cost_unpriced"] == ["ssh_trainer:k31/t-i0"]


def test_a_row_without_node_counts_stays_unpriced(tmp_path):
"""A ledger written before the rows counted their nodes: no price is not read as $0."""
ledger = ResourceLedger(tmp_path / "resources.jsonl", clock=lambda: 1000.0)
ledger.created("ssh_trainer", "k31/t-i0", "t-i0", run_id="k31", gpus=8, usd_per_hour=None)
(item,) = billing.resource_costs(ledger.resources(), now=1000.0 + 1800).items
assert not item.priced and "price_per_card_hour" in item.note


def test_the_cost_guard_does_not_warn_about_own_ssh_nodes(tmp_path):
"""Rehearsal: every incarnation of a resident ssh trainer on own nodes (no
price_per_card_hour) raised a cost_unpriced warning."""
from yeto.cost.guard import CostGuard, GuardConfig

ledger = ResourceLedger(tmp_path / "resources.jsonl", clock=lambda: 1000.0)
ledger.created("ssh_trainer", "k31/t-i0", "t-i0", **ssh_trainer_ledger.created_attrs(
run_id="k31", island="t", incarnation=0, nodes=[b300(0)], docker=True, kill_grace_s=30))
guard = CostGuard("k31", GuardConfig(), ledger=ledger, events_path=tmp_path / "events.jsonl",
clock=lambda: 1000.0 + 600, log=lambda *_: None)
guard.tick()
events = [json.loads(x) for x in (tmp_path / "events.jsonl").read_text().splitlines()]
assert [e for e in events if e.get("event") == "cost_unpriced"] == []
(tick,) = [e for e in events if e.get("event") == "cost_tick"]
assert tick["unpriced"] == [] and tick["total_usd"] == 0.0


# ---------------------------------------------------------------- multi-node staged releases
Expand Down
23 changes: 20 additions & 3 deletions yeto/cost/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,22 @@ def _nc_rate(r: Resource, rates: Rates) -> float | None:
return None


OWN_SSH_NODES_NOTE = "own SSH nodes (no price_per_card_hour): $0"


def _ssh_nodes_without_price(attrs: Mapping[str, Any]) -> tuple[float | None, str]:
"""``(rate, note)`` of an ssh_trainer row without ``usd_per_hour``: $0 when none of its
nodes declares ``price_per_card_hour`` (the operator's own machines, as an ``ssh:``
sampler pool), unpriced when only some do (a forgotten price is not $0) or when the
row does not count its nodes (a ledger written before it did)."""
priced, unpriced = attrs.get("priced_nodes"), attrs.get("unpriced_nodes")
if priced == 0 and isinstance(unpriced, int) and unpriced > 0:
return 0.0, OWN_SSH_NODES_NOTE
if isinstance(priced, int) and isinstance(unpriced, int) and priced > 0:
return None, f"{unpriced} of {priced + unpriced} SSH nodes without price_per_card_hour"
return None, "SSH nodes without price_per_card_hour"


def _span_cost(r: Resource, start: float, now: float, rate: float | None, note: str = "") -> ItemCost:
end = r.released_at if r.released_at is not None else now
if end < start and r.key not in _SKEW_WARNED:
Expand Down Expand Up @@ -547,9 +563,10 @@ def covered_until(c: Resource) -> float:
elif _provider_cost(r.kind) is not None: # an island provider's machine (nc_lease)
items.append(_provider_cost(r.kind)(r, now, rates))
elif r.kind == "ssh_trainer": # the operator's machines: the inventory's declared price
rate = r.attrs.get("usd_per_hour")
items.append(_span_cost(r, r.created_at, now, None if rate is None else float(rate),
"" if rate is not None else "SSH nodes without price_per_card_hour"))
rate, note = r.attrs.get("usd_per_hour"), ""
if rate is None:
rate, note = _ssh_nodes_without_price(r.attrs)
items.append(_span_cost(r, r.created_at, now, None if rate is None else float(rate), note))
elif r.kind == "sky_cluster":
rate = r.attrs.get("usd_per_hour")
note = ""
Expand Down
45 changes: 39 additions & 6 deletions yeto/launch/fabric_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
HINT = ("the node inventory declares no fabric_group: a multi-node island may land on nodes that do not "
"reach each other over IB / RoCE; `yeto cluster probe` groups them (docs/OWN_CLUSTERS.md)")
UNAVAILABLE = "fabric unavailable"
NO_RDMA = "no RDMA fabric"
NO_RDMA_NEXT = ("if the node has IB / RoCE HCAs, set its fabric to ib or roce in the inventory and probe "
"again; otherwise nothing to do (yeto preflight checks the node itself)")
NO_RDMA_FAILED_NEXT = "fix the node (yeto preflight on it names the fix) and probe again"
_log = logging.getLogger(__name__)


Expand Down Expand Up @@ -225,14 +229,21 @@ class ProbeResult:
pair_problems: dict[str, str] = field(default_factory=dict)
bad_edges: list[tuple[str, str, str]] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
# node -> its declared fabric, for the nodes that declare no RDMA fabric (``tcp``; ``hccs`` is
# Ascend's in-node interconnect, no RDMA fabric between nodes either): no group by their own
# inventory, single-node islands only; not a probe failure by itself
no_rdma: dict[str, str] = field(default_factory=dict)
# such a node -> its failed node checks (image pull, container, ssh, ...): those are failures
no_rdma_failed: dict[str, list[str]] = field(default_factory=dict)

@property
def clean(self) -> bool:
return not self.unavailable and not self.bad_edges
return not self.unavailable and not self.bad_edges and not self.no_rdma_failed

def assignment(self) -> dict[str, str]:
"""Node name -> group name (``unavailable``: no RDMA to the others)."""
out = {n: FABRIC_UNAVAILABLE for n in self.unavailable}
"""Node name -> group name (``unavailable``: no RDMA to the others, a node that
declares no RDMA fabric included)."""
out = {n: FABRIC_UNAVAILABLE for n in [*self.unavailable, *self.no_rdma]}
for g, members in self.groups.items():
out.update({n: g for n in members})
return dict(sorted(out.items()))
Expand All @@ -242,10 +253,17 @@ def lines(self) -> list[str]:
out += [f"missing edge {a}<->{b}: {why}" for a, b, why in self.bad_edges]
for n, why in self.unavailable.items():
out.append(f"{UNAVAILABLE}: {n}: {'; '.join(why) or 'no RDMA edge to another node'}")
for n, fabric in self.no_rdma.items():
head = (f"{NO_RDMA}: {n}: fabric {fabric} in the inventory: no group, single-node islands only "
f"(fabric_group {FABRIC_UNAVAILABLE})")
failed = self.no_rdma_failed.get(n)
out.append(f"{head}; node checks FAILED: {'; '.join(failed)}; next: {NO_RDMA_FAILED_NEXT}" if failed
else f"{head}; next: {NO_RDMA_NEXT}")
return out

def record(self) -> dict[str, Any]:
return {"groups": self.groups, "unavailable": self.unavailable,
return {"groups": self.groups, "unavailable": self.unavailable, "no_rdma": self.no_rdma,
"no_rdma_failed": self.no_rdma_failed,
"edges": [list(e) for e in self.edges], "pair_problems": self.pair_problems,
"bad_edges": [list(e) for e in self.bad_edges], "warnings": self.warnings}

Expand All @@ -255,6 +273,9 @@ def record(self) -> dict[str, Any]:
"dev_infiniband", "dev_infiniband_container", "memlock_container", "tools")
# a FAIL of any of these: the node's HCAs cannot carry the island (no edge at all)
_HCA_CHECKS = ("ib_ports", "ib_hca", "gid", "dev_infiniband")
# the node checks that fail a node declaring no RDMA fabric: what keeps the node from running the
# image (its IB / RoCE checks do not apply; ssh only when the node is unreachable, not a clock skew)
_NO_RDMA_REASONS = tuple(r for r in _NODE_REASONS if r not in (*_HCA_CHECKS, "dev_infiniband_container", "ssh"))


def _over_ib(check: Any) -> bool:
Expand Down Expand Up @@ -545,7 +566,18 @@ def group_nodes(names: Sequence[str], checks: Sequence[Any], *, states: Sequence
previous: Mapping[str, str | None] | None = None, reserved: Iterable[str] = (),
nccl_pairs: str = "all") -> ProbeResult:
"""The fabric groups of ``names`` from a preflight's ``checks`` (and its node
``states``: the declared rails, the fabric keys)."""
``states``: the declared rails, the fabric keys). A node whose state declares no
RDMA fabric (``tcp``) is in ``no_rdma``, not ``unavailable``: the probe does not
group it, and that is no failure of the probe."""
from .ssh_trainer_island import RDMA_FABRICS # noqa: PLC0415 - the island imports this module

declared = {s.node.name: getattr(s.node, "fabric", None) for s in states}
no_rdma = {n: str(declared[n]) for n in names if declared.get(n) not in (None, *RDMA_FABRICS)}
unreachable = {s.node.name for s in states if getattr(s, "reachable", True) is False}
no_rdma_failed = {n: list(dict.fromkeys(
f"{c.name}: {c.detail}" for c in checks if c.scope == n and c.status == "FAIL"
and (c.name in _NO_RDMA_REASONS or (c.name == "ssh" and n in unreachable))))[:4] for n in no_rdma}
names = [n for n in names if n not in no_rdma]
blocked = node_blocks(names, checks, states)
edges, problems, warns = evaluate_pairs(names, checks, nccl_pairs=nccl_pairs, blocked=blocked)
edge = {frozenset(e) for e in edges}
Expand All @@ -560,7 +592,8 @@ def group_nodes(names: Sequence[str], checks: Sequence[Any], *, states: Sequence
keys = {s.node.name: fabric_keys(s) for s in states}
ids = assign_ids(multi, keys=keys, previous=previous, reserved=reserved)
result = ProbeResult(groups=dict(sorted(zip(ids, multi))), edges=edges, pair_problems=problems,
bad_edges=bad, warnings=warns)
bad_edges=bad, warnings=warns, no_rdma=dict(sorted(no_rdma.items())),
no_rdma_failed={n: why for n, why in sorted(no_rdma_failed.items()) if why})
for part in parts:
if len(part) > 1:
continue
Expand Down
Loading
Loading