Download eval/metrics.py from HuggingFaceSwarms/s3-maze: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze/resolve/main/eval/metrics.py
- Command line
-
hf download hf://datasets/HuggingFaceSwarms/s3-maze/eval/metrics.py
-
curl -L -o metrics.py https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze/resolve/main/eval/metrics.py
19.9 kB
| """One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.py | |
| RUN_DIR [RUN_DIR ...] [--out rows.jsonl]`. | |
| s3-aggregation's eval/metrics.py, with s3-maze's move-log metrics added (`maze_moves` in | |
| EXTRAS). A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`, | |
| docs/local.md), or a Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where the | |
| workers copy what a run is graded on into `results/`. Under either, each agent's Trials | |
| (`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the board | |
| export (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (one | |
| JSON line; README.md has every field): | |
| - the task and team size, how the run ended, and `success`: any agent's reward is 1; | |
| - per agent: its reward (its latest Trial with a verifier result), tokens and board posts; | |
| - the message graph: an edge from a sender to each teammate it mentions (`@agent-002`; a group | |
| mention such as `@all` names every member) or messages directly (a DM or a private channel of | |
| the two), with in-degree centralization and reciprocity as in the s³ paper's Appendix M. A | |
| post that mentions no one adds no edge; | |
| - for the maze: each agent's moves, the rooms it visited and the team's room overlap, from the | |
| move logs the grader keeps in each Trial's `verifier/`; | |
| - `missing`: what the run directory lacks (an agent's reward or move log, the board export) or | |
| where its spec and its Trials disagree, so a row never passes for complete when it is not. | |
| A reward and a move log count only from a Trial whose `result.json` holds Harbor's verifier | |
| result: the agent's container can write into `verifier/` while it works, and only the | |
| verifier's run replaces what is there. | |
| A local run's `run.json` gives the spec, the agents, their tokens (summed over models), the | |
| cost and how the run ended. A Slurm run has no such bundle: the task and the roster come from | |
| its `experiment/spec.yaml` as the run resolved it (its `${VAR}`s from `cluster.env` and | |
| `run.env`, else their defaults), each agent's tokens from its Trials' results (no reasoning | |
| split), and the run's span from its Trials. Every agent the spec planned has a row entry, so | |
| one without results shows in `missing`; so do Trials of an unplanned agent or of another task | |
| than the spec selects (e.g. a run directory whose `run.env` is gone, read with the defaults). | |
| The board may hold earlier runs' messages (a reused Space): only those posted within the run's | |
| span count. | |
| """ | |
| import argparse | |
| import fnmatch | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter | |
| from collections.abc import Callable | |
| from datetime import datetime | |
| from pathlib import Path | |
| import yaml | |
| TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning") | |
| def load_json(path: Path): | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def epoch(value) -> float: | |
| return float(value) if isinstance(value, int | float) else datetime.fromisoformat( | |
| value).timestamp() | |
| def bundle(run_dir: Path) -> dict | None: | |
| """A local run's run.json; None for a Slurm run (its controller's run.json, in the bucket, | |
| holds neither the spec nor the agents).""" | |
| path = run_dir / "run.json" | |
| doc = load_json(path) if path.is_file() else {} | |
| return doc if "spec" in doc and "agents" in doc else None | |
| def all_trials(run_dir: Path) -> dict[str, list[Path]]: | |
| """Each agent's Trial directories, oldest first: `<agent>/trials/<swarm>-<agent>-t<N>/` | |
| (a local run's agents/_harbor/, a Slurm run's results/<swarm>/), one per Trial name.""" | |
| found: dict[str, dict[str, tuple[int, Path]]] = {} | |
| for trial in run_dir.rglob("trials/*"): | |
| agent = trial.parent.parent.name | |
| m = re.fullmatch(rf"(?:.+-)?{re.escape(agent)}-t(\d+)", trial.name) | |
| if m and trial.is_dir(): | |
| found.setdefault(agent, {}).setdefault(trial.name, (int(m[1]), trial)) | |
| return {a: [p for _, p in sorted(t.values())] for a, t in sorted(found.items())} | |
| def results(trials: list[Path]) -> list[dict]: | |
| return [load_json(t / "result.json") for t in trials if (t / "result.json").is_file()] | |
| def verified(trial: Path) -> dict | None: | |
| """Harbor's verifier rewards for a Trial, or None when its verifier didn't run.""" | |
| result = trial / "result.json" | |
| if not result.is_file() or result.is_symlink(): | |
| return None | |
| return (load_json(result).get("verifier_result") or {}).get("rewards") or None | |
| def reward(trials: list[Path]) -> float | None: | |
| """The reward of the agent's latest Trial that has one.""" | |
| for trial in reversed(trials): | |
| rewards = verified(trial) | |
| if rewards and "reward" in rewards: | |
| return float(rewards["reward"]) | |
| return None | |
| def bundle_tokens(agent: dict) -> dict[str, int]: | |
| usage = dict.fromkeys(TOKEN_FIELDS, 0) | |
| for by_model in (agent.get("tokens") or {}).values(): | |
| for key in TOKEN_FIELDS: | |
| usage[key] += int(by_model.get(key) or 0) | |
| return usage | |
| def trial_tokens(trials: list[Path]) -> dict[str, int]: | |
| """Harbor's counts: its input includes the cached tokens.""" | |
| usage = dict.fromkeys(TOKEN_FIELDS, 0) | |
| for result in results(trials): | |
| agent = result.get("agent_result") or {} | |
| cached = int(agent.get("n_cache_tokens") or 0) | |
| usage["input"] += int(agent.get("n_input_tokens") or 0) - cached | |
| usage["cache_read"] += cached | |
| usage["output"] += int(agent.get("n_output_tokens") or 0) | |
| return usage | |
| def board(run_dir: Path, start: float, end: float) -> tuple[list[dict], dict[int, dict], bool]: | |
| """(the run's messages, oldest first, channels by id, whether an export was found).""" | |
| messages, channels, found = {}, {}, False | |
| for export in run_dir.rglob("resources/message_board/board.jsonl"): | |
| found = True | |
| listing = export.with_name("channels.json") | |
| for channel in load_json(listing) if listing.is_file() else []: | |
| channels[channel["id"]] = channel | |
| for line in export.read_text(encoding="utf-8").splitlines(): | |
| if line.strip(): | |
| record = json.loads(line) | |
| message = record["message"] | {"channel_id": record["channel_id"]} | |
| if start <= epoch(message["created_at"]) <= end: | |
| messages[message["id"]] = message | |
| return sorted(messages.values(), key=lambda m: m["id"]), channels, found | |
| def sender(message: dict) -> str | None: | |
| return (message.get("sender") or {}).get("external_id") | |
| def edges(messages: list[dict], channels: dict[int, dict], team: list[str]) -> set[tuple]: | |
| """(sender, receiver) for each teammate a message mentions or is sent to directly.""" | |
| members = set(team) | |
| out = set() | |
| for message in messages: | |
| source = sender(message) | |
| if source not in members: | |
| continue | |
| targets = {m.get("external_id") for m in message.get("mentions") or []} | |
| channel = channels.get(message["channel_id"]) or {} | |
| if channel.get("kind") in ("dm", "private"): | |
| inside = {m.get("external_id") for m in channel.get("members") or []} & members | |
| if len(inside) == 2 and source in inside: # a DM, or a private channel of the two | |
| targets |= inside | |
| out |= {(source, target) for target in targets & members if target != source} | |
| return out | |
| def centralization(graph: set[tuple], team: list[str]) -> float | None: | |
| """Appendix M: sum over agents of (k* - k_j) / (N - 1)^2, k_j agent j's in-degree and k* | |
| the largest: 0 when everyone receives from as many teammates, 1 when one agent receives | |
| from everyone and no one else from anyone. None for a team of one.""" | |
| n = len(team) | |
| if n < 2: | |
| return None | |
| degree = Counter(target for _, target in graph) | |
| k = [degree[a] for a in team] | |
| return sum(max(k) - kj for kj in k) / (n - 1) ** 2 | |
| def reciprocity(graph: set[tuple]) -> float | None: | |
| """Appendix M: the fraction of edges whose reverse edge exists. None without edges.""" | |
| return sum((b, a) in graph for a, b in graph) / len(graph) if graph else None | |
| def maze_moves(run_dir: Path, team: list[str], trials: dict[str, list[Path]]) -> dict: | |
| """s3-maze: from each agent's move logs (`verifier/moves.jsonl`, with the export's | |
| `final.json` for its start room), its accepted and refused moves, the rooms it visited | |
| (R_i: the start and every room it moved into, over all its Trials) and whether it reached | |
| the exit; and the team's room overlap, Appendix M's (V - U) / V with V = sum_i (|R_i| - 1) | |
| and U = |union of the R_i| - 1: 0 when no two agents visit the same room, near 1 when all | |
| walk the same path; None when no agent moved. And the first exit: which agent reached it, | |
| how long after the team's Trials started (the earliest `started_at`), with how many moves of | |
| its own, and how many moves the whole team had made by then (`first_exit`, None when no | |
| agent got out). Empty for a run without move logs (not a maze).""" | |
| per_agent, union, missing, any_log = {}, set(), [], False | |
| accepted, exits = [], [] # (time, agent) of every accepted move; (time, agent, its moves) | |
| for name in team: | |
| rooms, moves, refused, reached, logs = set(), 0, 0, False, 0 | |
| for trial in trials.get(name, []): | |
| log, final = trial / "verifier" / "moves.jsonl", trial / "verifier" / "final.json" | |
| if verified(trial) is None or not log.is_file() or log.is_symlink(): | |
| continue | |
| logs += 1 | |
| export = {} | |
| if final.is_file() and not final.is_symlink(): | |
| export = load_json(final) | |
| rooms.add(export.get("start")) | |
| reached |= export.get("reached") is True | |
| last, own = None, 0 | |
| lines = log.read_text(encoding="utf-8").splitlines() | |
| for i, line in enumerate(lines): | |
| try: | |
| record = json.loads(line) if line.strip() else {} | |
| except ValueError: # e.g. cut off when the Trial stopped mid-write: the moves | |
| # (or the exit) after it are unknown, so the run doesn't count | |
| missing.append(f"move log: {name} (line {i + 1} of {len(lines)} unreadable)") | |
| continue | |
| if record.get("ok") is True: | |
| moves += 1 | |
| own += 1 | |
| rooms |= {record["from"], record["to"]} | |
| last = (epoch(record["time"]), record["to"]) | |
| accepted.append((last[0], name)) | |
| elif record: | |
| refused += 1 | |
| if export.get("reached") is True and last and last[1] == export.get("room"): | |
| exits.append((last[0], name, own)) | |
| rooms.discard(None) | |
| any_log |= logs > 0 | |
| if not logs: | |
| missing.append(f"move log: {name}") | |
| per_agent[name] = {"moves": moves, "refused": refused, "rooms": len(rooms), | |
| "reached_exit": reached} | |
| union |= rooms | |
| if not any_log: | |
| return {} | |
| v = sum(max(a["rooms"] - 1, 0) for a in per_agent.values()) | |
| first_exit = None | |
| if exits: | |
| at, who, own = min(exits) | |
| started = [epoch(r["started_at"]) for ts in trials.values() for r in results(ts) | |
| if r.get("started_at")] | |
| first_exit = {"agent": who, "agent_moves": own, | |
| "team_moves": sum(1 for t, _ in accepted if t <= at), | |
| "after_s": round(at - min(started), 1) if started else None} | |
| return {"moves": {n: a["moves"] for n, a in per_agent.items()}, | |
| "first_exit": first_exit, | |
| "refused_moves": {n: a["refused"] for n, a in per_agent.items()}, | |
| "rooms": {n: a["rooms"] for n, a in per_agent.items()}, | |
| "rooms_union": len(union), | |
| "room_overlap": (v - (len(union) - 1)) / v if v else None, | |
| "exit_reached_by": [n for n, a in per_agent.items() if a["reached_exit"]], | |
| "missing_moves": missing} | |
| # Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields. | |
| EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = [maze_moves] | |
| def local_run(run: dict) -> dict: | |
| """What a local bundle says about the run.""" | |
| harbor = next((t.get("harbor") or {} for t in run["spec"]["types"].values()), {}) | |
| task = (harbor.get("config") or {}).get("task") or {} | |
| agents = sorted(run["agents"], key=lambda a: a["name"]) | |
| return {"swarm": run.get("swarm"), "task": task, "team": [a["name"] for a in agents], | |
| "start": epoch(run["started_at"]), "end": epoch(run["ended_at"]), | |
| "stop_reason": run.get("stop_reason"), "duration_s": run.get("duration_s"), | |
| "cost_usd": (run.get("totals") or {}).get("cost_usd"), | |
| "tokens": {a["name"]: bundle_tokens(a) for a in agents}, | |
| "turns": {a["name"]: a.get("turns_completed") for a in agents}} | |
| PLACEHOLDER = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)(?::-([^}]*))?\}") | |
| def env_value(raw: str) -> str: | |
| """A `NAME=value` line's value as Legion reads it (specrender.read_env_file): a quoted value | |
| ends at its closing quote (what follows is a comment), an unquoted one at ` #`.""" | |
| value = raw.strip() | |
| if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0: | |
| return value[1:end] | |
| return re.split(r"\s+#", raw, maxsplit=1)[0].strip() | |
| def run_values(run_dir: Path) -> dict[str, str]: | |
| """The run's `cluster.env` then `run.env` (later wins), as the jobs read them: what fills | |
| the spec's `${VAR}`s. Lines Legion would refuse (no `=`, a bad name) are skipped.""" | |
| values = {} | |
| for name in ("cluster.env", "run.env"): | |
| path = run_dir / name | |
| for line in path.read_text().splitlines() if path.is_file() else []: | |
| line = line.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| key, sep, raw = line.removeprefix("export ").partition("=") | |
| if sep and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key.strip()): | |
| values[key.strip()] = env_value(raw) | |
| return values | |
| def expand(text: str, values: dict[str, str]) -> str: | |
| """`${VAR}` and `${VAR:-default}` in the spec's text, as Legion fills them (empty = unset).""" | |
| return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]), | |
| text) | |
| def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict: | |
| """What a Slurm run's directory says: its spec as the run resolved it (`legion init`'s copy | |
| of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their | |
| defaults) and the Trials the workers kept. The spec gives the task and the roster: every | |
| agent it planned is in the row, so one whose results are missing is flagged, not dropped. | |
| `problems` says where the spec and the Trials disagree (e.g. a `run.env` that is gone, its | |
| values replaced by the defaults).""" | |
| path = run_dir / "experiment" / "spec.yaml" | |
| spec = (yaml.safe_load(expand(path.read_text(), run_values(run_dir))) | |
| if path.is_file() else None) or {} | |
| problems = [] if spec else ["spec: no experiment/spec.yaml"] | |
| agents = spec.get("agents") or {} | |
| count = agents.get("count") if type(agents.get("count")) is int else None | |
| if spec and count is None: | |
| problems.append(f"spec: agents.count is {agents.get('count')!r}, not a number") | |
| if spec.get("naming") == "consecutive-id" and count is not None: | |
| team = [f"agent-{k:03d}" for k in range(1, count + 1)] | |
| else: | |
| team = list(trials) | |
| if count is not None and len(team) < count: | |
| problems.append(f"agents: {len(team)} of the {count} planned have Trials") | |
| if outside := sorted(set(trials) - set(team)): | |
| problems.append(f"agents: Trials of agents the spec didn't plan: {', '.join(outside)}") | |
| times = [(epoch(r["started_at"]), epoch(r["finished_at"])) | |
| for ts in trials.values() for r in results(ts) | |
| if r.get("started_at") and r.get("finished_at")] | |
| start, end = (min(t[0] for t in times), max(t[1] for t in times)) if times else (0, 0) | |
| ran = sorted({r["task_name"].split("/")[-1] for ts in trials.values() for r in results(ts) | |
| if r.get("task_name")}) | |
| task = spec.get("task") or {"selector": ran[0] if len(ran) == 1 else None} | |
| selector = task.get("selector") or "" | |
| if odd := [name for name in ran if not fnmatch.fnmatchcase(name, selector)]: | |
| problems.append(f"task: the spec selects {selector!r}, the Trials ran {', '.join(odd)}") | |
| swarm = next((t.name.removesuffix(f"-{a}-t{t.name.rsplit('-t', 1)[1]}") | |
| for a, ts in trials.items() for t in ts), spec.get("name")) | |
| return {"swarm": swarm, "task": task, "team": team, "start": start, "end": end, | |
| "stop_reason": None, "duration_s": round(end - start, 1) if times else None, | |
| "cost_usd": None, "tokens": {a: trial_tokens(trials.get(a, [])) for a in team}, | |
| "turns": dict.fromkeys(team), "problems": problems} | |
| def row(run_dir: Path) -> dict: | |
| trials = all_trials(run_dir) | |
| run = bundle(run_dir) | |
| info = local_run(run) if run is not None else slurm_run(run_dir, trials) | |
| team = info["team"] | |
| messages, channels, exported = board(run_dir, info["start"], info["end"]) | |
| posts = Counter(sender(m) for m in messages) | |
| graph = edges(messages, channels, team) | |
| per_agent, missing = {}, list(info.get("problems", [])) | |
| for name in team: | |
| value = reward(trials.get(name, [])) | |
| if value is None: | |
| missing.append(f"reward: {name}") | |
| per_agent[name] = {"reward": value, "tokens": info["tokens"][name], | |
| "posts": posts[name], "turns": info["turns"][name]} | |
| if not exported: | |
| missing.append("board export") | |
| rewards = [a["reward"] for a in per_agent.values() if a["reward"] is not None] | |
| task = info["task"] | |
| out = { | |
| "run": run_dir.name, | |
| "swarm": info["swarm"], | |
| "task": re.sub(r"-s\*$", "", task.get("selector") or "") or None, # a team's slots | |
| "dataset": task.get("repo"), | |
| "revision": task.get("revision"), | |
| "agents": len(team), | |
| "stop_reason": info["stop_reason"], | |
| "duration_s": info["duration_s"], | |
| "success": any(r == 1 for r in rewards) if rewards else None, | |
| "rewards": {name: a["reward"] for name, a in per_agent.items()}, | |
| "tokens": {key: sum(a["tokens"][key] for a in per_agent.values()) | |
| for key in TOKEN_FIELDS}, | |
| "cost_usd": info["cost_usd"], | |
| "posts": sum(posts[name] for name in team), | |
| "other_posts": sum(n for who, n in posts.items() if who not in team), | |
| "per_agent": per_agent, | |
| "edges": sorted([a, b] for a, b in graph), | |
| "centralization": centralization(graph, team), | |
| "reciprocity": reciprocity(graph), | |
| "missing": missing, | |
| } | |
| for extra in EXTRAS: | |
| fields = extra(run_dir, team, trials) | |
| out["missing"] += fields.pop("missing_moves", []) | |
| out |= fields | |
| return out | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description="One row per team (JSON lines) from s³ runs.") | |
| parser.add_argument("run_dirs", nargs="+", type=Path) | |
| parser.add_argument("--out", type=Path, help="append the rows here (default: stdout)") | |
| args = parser.parse_args(argv) | |
| rows = [json.dumps(row(d)) for d in args.run_dirs] | |
| if args.out: | |
| with args.out.open("a", encoding="utf-8") as f: | |
| f.write("".join(r + "\n" for r in rows)) | |
| else: | |
| print("\n".join(rows)) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |