Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
lewtun HF Staff commited on
Commit
df0571e
·
verified ·
1 Parent(s): a43f73c

flock/sweep: the scaling sweep's tooling; metrics: first_exit, a cut-off last move-log line

Browse files

The driver, figure and set-aside scripts behind huggingface/flock#123's results (Qwen3.5-27B and Qwen3.5-2B, every tree at N = 1..16). tasks/ is unchanged.

README.md CHANGED
@@ -75,6 +75,7 @@ flock/
75
  spec.template.yaml what every team's Flock run shares: model, board rules, loop, limits
76
  team.py writes one team's spec (the HF cluster, or local docker)
77
  registries.conf podman pulls Docker Hub images through mirror.gcr.io
 
78
  eval/metrics.py one row per team from Flock run directories
79
  generate.py writes tasks/ from its seed (115)
80
  budget.py the move-budget table below, from the service's own engine
@@ -251,6 +252,7 @@ move logs the grader keeps:
251
  | `rooms`, `rooms_union` | the rooms each agent visited (the start included), and the team's together |
252
  | `room_overlap` | the paper's (Appendix M): (V - U) / V, V = sum_i (\|R_i\| - 1), U = \|union of the R_i\| - 1: 0 when no two agents visit the same room, near 1 when all walk the same path; `null` when no agent moved |
253
  | `exit_reached_by` | the agents whose walk reached the exit |
 
254
  | `missing` | what the run directory lacks (an agent's reward or move log, the board export), and where its spec and its Trials disagree |
255
 
256
  A reward and a move log count only from a Trial whose `result.json` holds Harbor's verifier
 
75
  spec.template.yaml what every team's Flock run shares: model, board rules, loop, limits
76
  team.py writes one team's spec (the HF cluster, or local docker)
77
  registries.conf podman pulls Docker Hub images through mirror.gcr.io
78
+ sweep/ the scaling sweep (every tree at N = 1..16, one model per grid): its README
79
  eval/metrics.py one row per team from Flock run directories
80
  generate.py writes tasks/ from its seed (115)
81
  budget.py the move-budget table below, from the service's own engine
 
252
  | `rooms`, `rooms_union` | the rooms each agent visited (the start included), and the team's together |
253
  | `room_overlap` | the paper's (Appendix M): (V - U) / V, V = sum_i (\|R_i\| - 1), U = \|union of the R_i\| - 1: 0 when no two agents visit the same room, near 1 when all walk the same path; `null` when no agent moved |
254
  | `exit_reached_by` | the agents whose walk reached the exit |
255
+ | `first_exit` | the first agent to reach the exit, how long after the team's Trials started, with how many moves of its own, and the team's moves by then; `null` when no agent got out |
256
  | `missing` | what the run directory lacks (an agent's reward or move log, the board export), and where its spec and its Trials disagree |
257
 
258
  A reward and a move log count only from a Trial whose `result.json` holds Harbor's verifier
eval/metrics.py CHANGED
@@ -181,9 +181,12 @@ def maze_moves(run_dir: Path, team: list[str], trials: dict[str, list[Path]]) ->
181
  (R_i: the start and every room it moved into, over all its Trials) and whether it reached
182
  the exit; and the team's room overlap, Appendix M's (V - U) / V with V = sum_i (|R_i| - 1)
183
  and U = |union of the R_i| - 1: 0 when no two agents visit the same room, near 1 when all
184
- walk the same path; None when no agent moved. Empty for a run without move logs (not a
185
- maze)."""
 
 
186
  per_agent, union, missing, any_log = {}, set(), [], False
 
187
  for name in team:
188
  rooms, moves, refused, reached, logs = set(), 0, 0, False, 0
189
  for trial in trials.get(name, []):
@@ -191,17 +194,30 @@ def maze_moves(run_dir: Path, team: list[str], trials: dict[str, list[Path]]) ->
191
  if verified(trial) is None or not log.is_file() or log.is_symlink():
192
  continue
193
  logs += 1
 
194
  if final.is_file() and not final.is_symlink():
195
  export = load_json(final)
196
  rooms.add(export.get("start"))
197
  reached |= export.get("reached") is True
198
- for line in log.read_text(encoding="utf-8").splitlines():
199
- record = json.loads(line) if line.strip() else {}
 
 
 
 
 
 
 
200
  if record.get("ok") is True:
201
  moves += 1
 
202
  rooms |= {record["from"], record["to"]}
 
 
203
  elif record:
204
  refused += 1
 
 
205
  rooms.discard(None)
206
  any_log |= logs > 0
207
  if not logs:
@@ -212,7 +228,16 @@ def maze_moves(run_dir: Path, team: list[str], trials: dict[str, list[Path]]) ->
212
  if not any_log:
213
  return {}
214
  v = sum(max(a["rooms"] - 1, 0) for a in per_agent.values())
 
 
 
 
 
 
 
 
215
  return {"moves": {n: a["moves"] for n, a in per_agent.items()},
 
216
  "refused_moves": {n: a["refused"] for n, a in per_agent.items()},
217
  "rooms": {n: a["rooms"] for n, a in per_agent.items()},
218
  "rooms_union": len(union),
 
181
  (R_i: the start and every room it moved into, over all its Trials) and whether it reached
182
  the exit; and the team's room overlap, Appendix M's (V - U) / V with V = sum_i (|R_i| - 1)
183
  and U = |union of the R_i| - 1: 0 when no two agents visit the same room, near 1 when all
184
+ walk the same path; None when no agent moved. And the first exit: which agent reached it,
185
+ how long after the team's Trials started (the earliest `started_at`), with how many moves of
186
+ its own, and how many moves the whole team had made by then (`first_exit`, None when no
187
+ agent got out). Empty for a run without move logs (not a maze)."""
188
  per_agent, union, missing, any_log = {}, set(), [], False
189
+ accepted, exits = [], [] # (time, agent) of every accepted move; (time, agent, its moves)
190
  for name in team:
191
  rooms, moves, refused, reached, logs = set(), 0, 0, False, 0
192
  for trial in trials.get(name, []):
 
194
  if verified(trial) is None or not log.is_file() or log.is_symlink():
195
  continue
196
  logs += 1
197
+ export = {}
198
  if final.is_file() and not final.is_symlink():
199
  export = load_json(final)
200
  rooms.add(export.get("start"))
201
  reached |= export.get("reached") is True
202
+ last, own = None, 0
203
+ lines = log.read_text(encoding="utf-8").splitlines()
204
+ for i, line in enumerate(lines):
205
+ try:
206
+ record = json.loads(line) if line.strip() else {}
207
+ except ValueError: # the last line cut off when the Trial stopped mid-write
208
+ if i < len(lines) - 1:
209
+ missing.append(f"move log: {name} (line {i + 1} unreadable)")
210
+ continue
211
  if record.get("ok") is True:
212
  moves += 1
213
+ own += 1
214
  rooms |= {record["from"], record["to"]}
215
+ last = (epoch(record["time"]), record["to"])
216
+ accepted.append((last[0], name))
217
  elif record:
218
  refused += 1
219
+ if export.get("reached") is True and last and last[1] == export.get("room"):
220
+ exits.append((last[0], name, own))
221
  rooms.discard(None)
222
  any_log |= logs > 0
223
  if not logs:
 
228
  if not any_log:
229
  return {}
230
  v = sum(max(a["rooms"] - 1, 0) for a in per_agent.values())
231
+ first_exit = None
232
+ if exits:
233
+ at, who, own = min(exits)
234
+ started = [epoch(r["started_at"]) for ts in trials.values() for r in results(ts)
235
+ if r.get("started_at")]
236
+ first_exit = {"agent": who, "agent_moves": own,
237
+ "team_moves": sum(1 for t, _ in accepted if t <= at),
238
+ "after_s": round(at - min(started), 1) if started else None}
239
  return {"moves": {n: a["moves"] for n, a in per_agent.items()},
240
+ "first_exit": first_exit,
241
  "refused_moves": {n: a["refused"] for n, a in per_agent.items()},
242
  "rooms": {n: a["rooms"] for n, a in per_agent.items()},
243
  "rooms_union": len(union),
flock/sweep/README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # s3-maze scaling sweep
2
+
3
+ The s³ paper's maze results (Figure 4 bottom: success against swarm size) with Flock: every tree
4
+ of this dataset at N = 1, 2, 4, 8 and 16 agents, one team each, every team its own Flock run on
5
+ the HF cluster, for one model per grid. The results for `Qwen/Qwen3.5-27B` and
6
+ `Qwen/Qwen3.5-2B` are on Flock's `s3-maze-results` branch (`experiments/s3-maze/results/`) and in
7
+ huggingface/flock#123's description; the raw runs are in the private
8
+ `HuggingFaceSwarms/s3-maze-results`.
9
+
10
+ | File | |
11
+ | --- | --- |
12
+ | `serve-vllm.sbatch` | one model server: vLLM on one B200 (s3-aggregation's image and parsers), `MODEL` and `PORT` from the environment |
13
+ | `sweep.py` | runs one model's grid, one command, resumable: a row per team in `<root>/rows.jsonl` |
14
+ | `health-log.sh` | each model server's prefix-cache hit rate and load every minute, to `servers.jsonl` (`--health`) |
15
+ | `plot.py` | `scaling.png`, `teams.csv`, `by_n.csv` and `by_n.md` from the rows, one series per model |
16
+ | `setaside.py` | why each attempt in `rows-discarded.jsonl` didn't count |
17
+
18
+ ## Run it
19
+
20
+ From Flock's checkout, with this dataset on the shared disk (`DS`; the workers read
21
+ `flock/registries.conf`) and the private-repo credential helper exported (Flock's docs/slurm.md):
22
+
23
+ ```sh
24
+ sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 \
25
+ -o vllm-%j.log $DS/flock/sweep/serve-vllm.sbatch # one per GPU; the log ends with its URL
26
+ uv run python $DS/flock/sweep/sweep.py --model Qwen/Qwen3.5-27B --tag q27- --revision <sha> \
27
+ --urls http://<node>:8011/v1,http://<node>:8012/v1,... --per-server 9 --parallel 50 \
28
+ --root runs/q27 --health servers.jsonl --dataset HuggingFaceSwarms/s3-maze-results
29
+ uv run $DS/flock/sweep/plot.py --series Qwen3.5-27B=runs/q27 --series Qwen3.5-2B=runs/q2 --out results
30
+ ```
31
+
32
+ Each team is team.py's cluster spec with the model on the servers (`urls`): `compute: slurm`, one
33
+ worker on hopper-cpu running the team's compose Trials in rootless podman with a local board,
34
+ and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per maze service and two
35
+ more (at least 4), at 1900 MB per CPU. The driver inits and launches a team, waits for the first
36
+ exit (and the grading) or the end of the loop, releases it (`flock stop --release`, which also
37
+ ends its controller), and appends metrics.py's row with the team's exit branch and wall time.
38
+
39
+ ## What counts
40
+
41
+ A run counts only when its worker started within 2 minutes of its launch (the loop's 45 minutes
42
+ count from the launch), on one worker incarnation, with its controller kept, every agent's
43
+ reward and move log and the board export, and no agent's model server thrashing for 5 minutes or
44
+ more during it (below). Anything else is the infrastructure's: the team runs again as
45
+ `<task>-rK`, and `setaside.py` says why. What the model does (no move, no post, no exit) is a
46
+ result. A restarted driver adopts the teams in flight and keeps each team's own start time.
47
+
48
+ ## Model servers: KV cache and names
49
+
50
+ One B200 holds about 1.7M tokens of a 27B model's KV cache, and a maze agent's context grows past
51
+ 100k tokens. A server with more such agents than fit evicts their cached prefixes and recomputes
52
+ each agent's whole context on every call (its prefix-cache hit rate falls from ~95% to a few
53
+ percent, and calls take minutes): the loop's time limit, not the move budget, then decides the
54
+ run. So:
55
+
56
+ - **at most `--per-server` agents per server** (9 to 19 for the 27B model, read again from
57
+ `<root>/per_server` before each launch, so it can change while the grid runs; the 2B model's
58
+ smaller cache entries, ~13M tokens per B200, fit a whole grid on one GPU);
59
+ - **each team gets its own subset of the servers.** Flock sends each agent to a server by
60
+ hashing its name over the URLs, and with `naming: consecutive-id` every team has an
61
+ `agent-001`: with one URL list, every team's `agent-001` (and every N = 1 agent) calls the same
62
+ server. The driver picks, per team, the subset of `--urls` that puts its agents on the
63
+ least-loaded servers within the cap;
64
+ - **runs on a thrashing server don't count**: `health-log.sh` logs each server's hit rate every
65
+ minute, and a run whose agents' server had under 50% while prefilling 200k+ tokens in 5 or more
66
+ minutes runs again (`health-log.sh servers.jsonl <host:port> ...`).
67
+
68
+ ## Workers: memory
69
+
70
+ Rootless podman on hopper-cpu can't hold a container to a memory limit, so a runaway process in
71
+ one agent's container (the 2B model's agents sometimes start one) grows the whole worker until
72
+ Flock's memory guard drains or preempts it, and the team runs again on a second incarnation.
73
+ For the 2B grid, `--cpus-per-agent 2` doubles each agent's share of the worker (and its memory,
74
+ at 1900 MB per CPU) and `--memory-ladder 0.97,0.98,0.99` lets the worker go closer to its limit
75
+ before the guard acts.
flock/sweep/health-log.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Every 60 s, each model server's requests, prompt tokens, prefix-cache hit rate, running and
3
+ # waiting requests over the last minute, one JSON line per server to OUT (sweep.py --health):
4
+ # health-log.sh servers.jsonl 10.53.14.57:8011 10.53.14.57:8012 ...
5
+ OUT=$1
6
+ shift
7
+ declare -A last
8
+ while true; do
9
+ for s in "$@"; do
10
+ now=$(curl -s -m 5 "$s/metrics" | awk '
11
+ /^vllm:request_success_total\{/ {a+=$2} /^vllm:prompt_tokens_total\{/ {p+=$2}
12
+ /^vllm:prefix_cache_hits_total\{/ {h+=$2} /^vllm:prefix_cache_queries_total\{/ {q+=$2}
13
+ /^vllm:num_requests_running\{/ {r+=$2} /^vllm:num_requests_waiting\{/ {w+=$2}
14
+ END {print a+0, p+0, h+0, q+0, r+0, w+0}')
15
+ if [ -n "${last[$s]}" ] && [ -n "$now" ]; then
16
+ python3 -c "
17
+ import json, sys, time
18
+ a0, p0, h0, q0, _, _ = map(float, sys.argv[1].split())
19
+ a1, p1, h1, q1, r, w = map(float, sys.argv[2].split())
20
+ print(json.dumps({'t': time.time(), 'server': sys.argv[3], 'requests': a1 - a0, 'prompt': p1 - p0,
21
+ 'hit_rate': (h1 - h0) / (q1 - q0) if q1 > q0 else None, 'running': r, 'waiting': w}))
22
+ " "${last[$s]}" "$now" "$s" >> "$OUT"
23
+ fi
24
+ last[$s]=$now
25
+ done
26
+ sleep 60
27
+ done
flock/sweep/plot.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = ["matplotlib>=3.8"]
4
+ # ///
5
+ """The s3-maze sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`):
6
+
7
+ uv run flock/sweep/plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>
8
+
9
+ - `scaling.png`, eight panels, one series per model, after the s³ paper's maze results
10
+ (Figure 4, bottom: success against swarm size; Figure 5c: success by the branch that holds
11
+ the exit; Appendix M: room overlap):
12
+ - success (%) against N, with 95% Wilson intervals over the trees, and best-of-N from the
13
+ model's own N = 1 rate (1 - (1 - p1)^N, the paper's independent-attempts baseline) dashed;
14
+ - the team's moves and the time (from its Trials' start) to the first exit, over the teams
15
+ that got out: median and interquartile range;
16
+ - room overlap, (V - U) / V, mean and 95% interval (N >= 2);
17
+ - input and generated tokens per team (log scale): median and interquartile range;
18
+ - board posts per agent: mean and 95% interval;
19
+ - success by which of the start room's three doors, in the listed order, leads to the exit,
20
+ over every N >= 2 team (95% Wilson intervals).
21
+ - `teams.csv` (one row per team), `by_n.csv` and `by_n.md` (per model and N).
22
+ """
23
+
24
+ import argparse
25
+ import csv
26
+ import json
27
+ import math
28
+ import statistics
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ SURFACE, INK, INK_2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
33
+ SERIES = ["#2a78d6", "#eb6834", "#1baf7a"]
34
+
35
+
36
+ def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
37
+ if n == 0:
38
+ return (math.nan, math.nan)
39
+ p = k / n
40
+ centre = (p + z * z / (2 * n)) / (1 + z * z / n)
41
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
42
+ return (max(0.0, centre - half), min(1.0, centre + half))
43
+
44
+
45
+ def mean_ci(values: list[float]) -> tuple[float, float, float]:
46
+ if not values:
47
+ return (math.nan, math.nan, math.nan)
48
+ m = statistics.fmean(values)
49
+ half = 1.96 * statistics.stdev(values) / math.sqrt(len(values)) if len(values) > 1 else 0.0
50
+ return (m, m - half, m + half)
51
+
52
+
53
+ def quartiles(values: list[float]) -> tuple[float, float, float]:
54
+ if not values:
55
+ return (math.nan, math.nan, math.nan)
56
+ q = statistics.quantiles(values, n=4) if len(values) > 1 else [values[0]] * 3
57
+ return (statistics.median(values), q[0], q[2])
58
+
59
+
60
+ def team_row(r: dict) -> dict:
61
+ t, first = r["tokens"], r.get("first_exit") or {}
62
+ return {"task": r["task"], "tree": r["tree"], "agents": r["agents"],
63
+ "exit_branch": r["exit_branch"], "success": int(bool(r["success"])),
64
+ "exit_by": first.get("agent"), "exit_after_s": first.get("after_s"),
65
+ "exit_team_moves": first.get("team_moves"),
66
+ "exit_agent_moves": first.get("agent_moves"),
67
+ "moves": sum((r.get("moves") or {}).values()),
68
+ "refused_moves": sum((r.get("refused_moves") or {}).values()),
69
+ "room_overlap": r.get("room_overlap"), "rooms_union": r.get("rooms_union"),
70
+ "input_uncached": t["input"], "cached": t["cache_read"], "output": t["output"],
71
+ "posts": r["posts"], "posts_per_agent": r["posts"] / r["agents"],
72
+ "edges": len(r["edges"]), "outcome": r.get("outcome"), "wall_s": r.get("wall_s"),
73
+ "duration_s": r["duration_s"], "reruns": r.get("reruns", 0),
74
+ "worker_wait_s": r.get("worker_wait_s"), "run": r["run"]}
75
+
76
+
77
+ def by_n(teams: list[dict]) -> list[dict]:
78
+ """Per N. A tree with no team that counted at that N (every attempt set aside) is
79
+ `missing`: left out of the rates, not a failure."""
80
+ out, p1 = [], None
81
+ trees = {t["tree"] for t in teams}
82
+ for n in sorted({t["agents"] for t in teams}):
83
+ group = [t for t in teams if t["agents"] == n]
84
+ missing = sorted(trees - {t["tree"] for t in group})
85
+ won = [t for t in group if t["success"]]
86
+ k = len(won)
87
+ low, high = wilson(k, len(group))
88
+ if n == 1:
89
+ p1 = k / len(group)
90
+ overlap = [t["room_overlap"] for t in group if t["room_overlap"] is not None]
91
+ moves, minutes = (quartiles([t["exit_team_moves"] for t in won]),
92
+ quartiles([t["exit_after_s"] / 60 for t in won]))
93
+ out.append({
94
+ "agents": n, "teams": len(group), "missing": len(missing),
95
+ "missing_trees": " ".join(f"t{x:02d}" for x in missing),
96
+ "successes": k, "success_rate": k / len(group),
97
+ "ci_low": low, "ci_high": high,
98
+ "best_of_n_from_n1": 1 - (1 - p1) ** n if p1 is not None else math.nan,
99
+ "exit_team_moves_median": moves[0], "exit_team_moves_q1": moves[1],
100
+ "exit_team_moves_q3": moves[2],
101
+ "exit_agent_moves_median": quartiles([t["exit_agent_moves"] for t in won])[0],
102
+ "exit_minutes_median": minutes[0], "exit_minutes_q1": minutes[1],
103
+ "exit_minutes_q3": minutes[2],
104
+ "moves_per_agent": statistics.fmean(t["moves"] / n for t in group),
105
+ "room_overlap": statistics.fmean(overlap) if overlap else math.nan,
106
+ "input_per_team": statistics.fmean(t["input_uncached"] + t["cached"] for t in group),
107
+ "output_per_team": statistics.fmean(t["output"] for t in group),
108
+ "input_per_team_median": statistics.median(t["input_uncached"] + t["cached"]
109
+ for t in group),
110
+ "output_per_team_median": statistics.median(t["output"] for t in group),
111
+ "posts_per_agent": statistics.fmean(t["posts_per_agent"] for t in group),
112
+ "wall_minutes_median": statistics.median(t["wall_s"] / 60 for t in group
113
+ if t["wall_s"] is not None),
114
+ "reruns": sum(t["reruns"] for t in group)})
115
+ return out
116
+
117
+
118
+ def write_csv(path: Path, rows: list[dict]) -> None:
119
+ with path.open("w", newline="") as f:
120
+ writer = csv.DictWriter(f, fieldnames=list(rows[0]), lineterminator="\n")
121
+ writer.writeheader()
122
+ writer.writerows(rows)
123
+
124
+
125
+ def table(series) -> str:
126
+ lines = [("| model | N | teams | success | 95% CI | best-of-N from N=1 | team moves to exit "
127
+ "| minutes to exit | moves per agent | median input / output tokens per team "
128
+ "| posts per agent | room overlap |"),
129
+ "|---|---|---|---|---|---|---|---|---|---|---|---|"]
130
+ for model, _, summary in series:
131
+ for s in summary:
132
+ def num(x, f="{:.0f}"):
133
+ return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else f.format(x)
134
+ gone = f" ({s['missing']} missing)" if s["missing"] else ""
135
+ lines.append(
136
+ f"| {model} | {s['agents']} | {s['teams']}{gone} | {s['successes']}/{s['teams']} "
137
+ f"({100 * s['success_rate']:.0f}%) | {100 * s['ci_low']:.0f}-"
138
+ f"{100 * s['ci_high']:.0f}% | {num(100 * s['best_of_n_from_n1'], '{:.0f}%')} "
139
+ f"| {num(s['exit_team_moves_median'])} | {num(s['exit_minutes_median'], '{:.1f}')} "
140
+ f"| {s['moves_per_agent']:.0f} | {s['input_per_team_median'] / 1e6:.1f}M / "
141
+ f"{s['output_per_team_median'] / 1e3:.0f}k | {s['posts_per_agent']:.1f} "
142
+ f"| {num(s['room_overlap'], '{:.2f}')} |")
143
+ return "\n".join(lines) + "\n"
144
+
145
+
146
+ def panels(teams: list[dict], summary: list[dict]) -> list[tuple]:
147
+ """(label, x values, [(middle, low, high)], y scale, dashed reference or None)."""
148
+ ns = [s["agents"] for s in summary]
149
+ group = {n: [t for t in teams if t["agents"] == n] for n in ns}
150
+ won = {n: [t for t in group[n] if t["success"]] for n in ns}
151
+ multi = [n for n in ns if n > 1]
152
+ branches = [1, 2, 3]
153
+ by_branch = [[t for t in teams if t["agents"] > 1 and t["exit_branch"] == b] for b in branches]
154
+ return [
155
+ ("Success (%)", ns, [(100 * s["success_rate"], 100 * s["ci_low"], 100 * s["ci_high"])
156
+ for s in summary], (0, 105),
157
+ [100 * s["best_of_n_from_n1"] for s in summary]),
158
+ ("Team moves to the first exit", ns,
159
+ [quartiles([t["exit_team_moves"] for t in won[n]]) for n in ns], None, None),
160
+ ("Minutes to the first exit", ns,
161
+ [quartiles([t["exit_after_s"] / 60 for t in won[n]]) for n in ns], None, None),
162
+ ("Room overlap", multi,
163
+ [mean_ci([t["room_overlap"] for t in group[n] if t["room_overlap"] is not None])
164
+ for n in multi], (0, 1), None),
165
+ ("Input tokens per team", ns,
166
+ [quartiles([t["input_uncached"] + t["cached"] for t in group[n]]) for n in ns], "log",
167
+ None),
168
+ ("Generated tokens per team", ns, [quartiles([t["output"] for t in group[n]]) for n in ns],
169
+ "log", None),
170
+ ("Board posts per agent", ns, [mean_ci([t["posts_per_agent"] for t in group[n]])
171
+ for n in ns], None, None),
172
+ ("Success (%) by the exit's branch, N ≥ 2", branches,
173
+ [(100 * sum(t["success"] for t in g) / len(g) if g else math.nan,
174
+ *(100 * v for v in wilson(sum(t["success"] for t in g), len(g)))) for g in by_branch],
175
+ (0, 105), None),
176
+ ]
177
+
178
+
179
+ def tokens(value: float, _=None) -> str:
180
+ for size, unit in ((1e6, "M"), (1e3, "k")):
181
+ if value >= size:
182
+ return f"{value / size:g}{unit}"
183
+ return f"{value:g}"
184
+
185
+
186
+ def figure(path: Path, series, title: str) -> None:
187
+ import matplotlib
188
+
189
+ matplotlib.use("Agg")
190
+ import matplotlib.pyplot as plt
191
+ from matplotlib.ticker import FixedLocator, FuncFormatter, NullFormatter
192
+
193
+ plt.rcParams.update({"font.size": 10, "axes.edgecolor": GRID, "axes.labelcolor": INK_2,
194
+ "xtick.color": INK_2, "ytick.color": INK_2, "text.color": INK})
195
+ fig, grid = plt.subplots(2, 4, figsize=(17, 7.8), facecolor=SURFACE)
196
+ axes = grid.flatten()
197
+ xs_by_panel: dict[int, set] = {}
198
+ for k, (model, teams, summary) in enumerate(series):
199
+ step = (k - (len(series) - 1) / 2) # side by side, so the bars don't hide each other
200
+ for i, (ax, (label, xs, points, scale, reference)) in enumerate(
201
+ zip(axes, panels(teams, summary), strict=True)):
202
+ xs_by_panel.setdefault(i, set()).update(xs)
203
+ # N on a log2 axis: shift by a factor; the branches (panel 7) by a step
204
+ moved = [x + 0.08 * step if i == 7 else x * 2 ** (0.07 * step) for x in xs]
205
+ ax.errorbar(moved, [p[0] for p in points],
206
+ yerr=[[max(0.0, p[0] - p[1]) if not math.isnan(p[1]) else 0 for p in points],
207
+ [max(0.0, p[2] - p[0]) if not math.isnan(p[2]) else 0 for p in points]],
208
+ color=SERIES[k], linewidth=2, marker="o", markersize=6, capsize=3,
209
+ elinewidth=1.4, label=model, linestyle="-" if i != 7 else "none")
210
+ if reference:
211
+ ax.plot(xs, reference, color=SERIES[k], linewidth=1.3, linestyle="--",
212
+ label=f"{model}: best-of-N from N = 1")
213
+ ax.set_ylabel(label)
214
+ scales = [p[3] for p in panels(*series[0][1:])]
215
+ for i, ax in enumerate(axes): # after every series is in, so each scales to all of them
216
+ if scales[i] == "log":
217
+ ax.set_yscale("log")
218
+ ax.yaxis.set_major_formatter(FuncFormatter(tokens))
219
+ ax.yaxis.set_minor_formatter(NullFormatter())
220
+ elif scales[i]:
221
+ ax.set_ylim(*scales[i])
222
+ else:
223
+ ax.set_ylim(bottom=0)
224
+ ticks = sorted(xs_by_panel.get(i, ()))
225
+ if i != 7 and ticks:
226
+ ax.set_xlim(min(ticks) / 1.4, max(ticks) * 1.4)
227
+ ax.set_xscale("log", base=2)
228
+ ax.xaxis.set_minor_formatter(NullFormatter())
229
+ ax.xaxis.set_major_locator(FixedLocator(ticks))
230
+ ax.set_xticklabels([str(t) for t in ticks])
231
+ ax.set_facecolor(SURFACE)
232
+ ax.grid(axis="y", color=GRID, linewidth=0.8)
233
+ ax.set_axisbelow(True)
234
+ ax.spines[["top", "right"]].set_visible(False)
235
+ ax.set_xlabel("Door at the start room (listed order)" if i == 7 else "Swarm size N")
236
+ axes[0].legend(frameon=False, loc="upper left", fontsize=8)
237
+ fig.suptitle(title, fontsize=11, color=INK, x=0.01, ha="left")
238
+ gone = "".join(f"; {m} at N = {s['agents']}: {s['missing']} missing (every attempt set "
239
+ "aside), left out, not failures" for m, _, summary in series
240
+ for s in summary if s["missing"])
241
+ fig.text(0.01, 0.012, f"One counted team per tree (32 trees{gone}). Success: share of "
242
+ "teams in which any agent reached the exit, 95% Wilson intervals; dashed: best-of-N "
243
+ "from the model's own N = 1 rate.\nMoves (all agents') and minutes (from the "
244
+ "Trials' start) to the first exit: teams that got out; tokens per team (log scale): "
245
+ "every team; medians and interquartile ranges. Overlap and posts: means, 95% "
246
+ "intervals.", fontsize=8, color=INK_2, wrap=True)
247
+ fig.tight_layout(rect=(0, 0.06, 1, 0.95))
248
+ fig.savefig(path, dpi=200, facecolor=SURFACE)
249
+
250
+
251
+ def load(root: Path) -> tuple[list[dict], list[dict]]:
252
+ rows = [json.loads(line) for line in (root / "rows.jsonl").read_text().splitlines() if line]
253
+ teams = sorted((team_row(r) for r in rows), key=lambda t: (t["agents"], t["tree"]))
254
+ return teams, by_n(teams)
255
+
256
+
257
+ def main(argv=None) -> int:
258
+ parser = argparse.ArgumentParser(description="The sweep's figure, CSVs and table.")
259
+ parser.add_argument("--series", action="append", required=True, help="MODEL=ROOT, repeatable")
260
+ parser.add_argument("--out", type=Path, required=True)
261
+ args = parser.parse_args(argv)
262
+ sources = [(s.split("=", 1)[0], Path(s.split("=", 1)[1])) for s in args.series]
263
+ args.out.mkdir(parents=True, exist_ok=True)
264
+ series = [(model, *load(root)) for model, root in sources]
265
+ write_csv(args.out / "teams.csv", [{"model": m} | t for m, teams, _ in series for t in teams])
266
+ write_csv(args.out / "by_n.csv", [{"model": m} | s for m, _, summary in series
267
+ for s in summary])
268
+ (args.out / "by_n.md").write_text(table(series))
269
+ figure(args.out / "scaling.png", series, "s3-maze with flock: success and cost against swarm "
270
+ f"size ({', '.join(m for m, _, _ in series)})")
271
+ print(table(series))
272
+ return 0
273
+
274
+
275
+ if __name__ == "__main__":
276
+ sys.exit(main())
flock/sweep/serve-vllm.sbatch ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # The s3-maze sweep's model server: one vLLM on one GPU, in Pyxis on hopper-b200, as
3
+ # s3-aggregation's flock/sweep/serve-vllm.sbatch (the same image and parsers). The agents
4
+ # (podman on hopper-cpu) reach it by this node's address.
5
+ # sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 -o <dir>/vllm-%j.log serve-vllm.sbatch
6
+ # Its log ends with: serving <model> at http://<node address>:<port>/v1
7
+ #SBATCH --job-name=s3-maze-vllm
8
+ #SBATCH --gpus=1
9
+ #SBATCH --cpus-per-task=16
10
+ #SBATCH --mem=96G
11
+ #SBATCH --time=12:00:00
12
+ set -uo pipefail
13
+ MODEL=${MODEL:-Qwen/Qwen3.5-27B}
14
+ PORT=${PORT:-8000}
15
+ IMAGE=${IMAGE:-/fsx/anton/shared/images/vllm-openai-v0.32.0.sqsh}
16
+ export HF_HOME=/hf
17
+ mkdir -p "/scratch/$USER/hf" # the weights, on the node's own disk
18
+ srun --overlap --container-image="$IMAGE" --no-container-mount-home \
19
+ --container-mounts="/scratch/$USER/hf:/hf" --container-env=HF_HOME \
20
+ vllm serve "$MODEL" --port "$PORT" \
21
+ --enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser qwen3 &
22
+ until curl -sf -o /dev/null "localhost:$PORT/v1/models"; do
23
+ sleep 10
24
+ kill -0 $! 2>/dev/null || { echo "vLLM exited during startup"; exit 1; }
25
+ done
26
+ echo "serving $MODEL at http://$(hostname -I | awk '{print $1}'):$PORT/v1"
27
+ wait
flock/sweep/setaside.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Why each set-aside attempt of a grid didn't count: `python flock/sweep/setaside.py <root>`,
2
+ from `<root>/rows-discarded.jsonl` and the attempt's own logs (s3-aggregation's, for the maze).
3
+ A restarted driver scores an attempt again from what it left, so one attempt can have several
4
+ entries: its reason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
5
+
6
+ - it ran while its model server was overloaded (`--overloaded`), or an agent's server thrashed
7
+ for 5 minutes or more (`--health`);
8
+ - the worker was relaunched (more than one incarnation: flock#121's case), after running out of
9
+ memory or after a node failure;
10
+ - the launch failed (or was cancelled), so its controller never came up;
11
+ - the worker never started, or started more than 2 min after the launch (the loop counts from
12
+ the launch);
13
+ - the controller's node was reclaimed (spot) mid-run;
14
+ - the task images couldn't be pulled or built, so the Trials never started;
15
+ - the worker ran out of memory;
16
+ - the verifier timed out on a loaded worker;
17
+ - an agent's Trial failed before its verifier ran;
18
+ - the run was cancelled before its Trials were graded (e.g. the driver stopped).
19
+
20
+ What the model does (no move, no post, no exit) is never a reason: those runs count.
21
+ """
22
+
23
+ import json
24
+ import re
25
+ import sys
26
+ from collections import Counter
27
+ from pathlib import Path
28
+
29
+
30
+ def reason(row: dict, run_dir: Path) -> str:
31
+ logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*")
32
+ if p.is_file()} if (run_dir / "logs").is_dir() else {}
33
+ workers = " ".join(v for k, v in logs.items() if "-agent-w" in k)
34
+ controllers = " ".join(v for k, v in logs.items() if k.startswith(("flock-ctl-",
35
+ "controller-")))
36
+ if "overloaded model server" in (row.get("set_aside") or ""):
37
+ return "ran on an overloaded model server (one 27B GPU, KV-cache thrash)"
38
+ if (row.get("thrashed_min") or 0) >= 5: # sweep.py's THRASH_LIMIT
39
+ return "an agent's model server thrashed (prefix-cache hits under 50%) for 5+ min"
40
+ if (row.get("incarnations") or 0) > 1:
41
+ if re.search(r"CANCELED: unresponsive", controllers):
42
+ return "worker stopped answering (e.g. while grading its Trials) and was relaunched"
43
+ if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers):
44
+ return "worker relaunched after running out of memory (flock#121's case)"
45
+ return "worker relaunched after a node failure (flock#121's case)"
46
+ if row.get("outcome") == "launch":
47
+ return "launch failed or was cancelled (the controller ended before it came up)"
48
+ if row.get("worker_wait_s") is None:
49
+ return "worker never started"
50
+ if row["worker_wait_s"] > 120: # sweep.py's WAIT_LIMIT
51
+ return "worker started more than 2 min after the launch (the loop counts from it)"
52
+ if "DUE TO NODE FAILURE" in controllers or row.get("outcome") == "controller lost":
53
+ return "controller's node reclaimed (spot)"
54
+ if re.search(r"toomanyrequests|Error: building at STEP|failed to build", workers):
55
+ return "task images not pulled or built: Trials never started"
56
+ if re.search(r"preempted \(memory\)|oom_kill", workers):
57
+ return "worker ran out of memory (preempted or killed, not relaunched)"
58
+ results = list(run_dir.glob("results/*/agent-*/trials/*/result.json"))
59
+ if any("VerifierTimeoutError" in p.read_text(errors="replace") for p in results):
60
+ return "verifier timed out on a loaded worker"
61
+ failed = [(json.loads(p.read_text()).get("exception_info") or {}).get("exception_type")
62
+ for p in results]
63
+ if kinds := sorted({k for k in failed if k and k != "CancelledError"}):
64
+ return f"an agent's Trial failed before its verifier ran ({', '.join(kinds)})"
65
+ return "cancelled before grading (e.g. the driver stopped)"
66
+
67
+
68
+ def main(root: Path) -> int:
69
+ attempts = {}
70
+ path = root / "rows-discarded.jsonl"
71
+ for line in path.read_text().splitlines() if path.exists() else []:
72
+ row = json.loads(line)
73
+ seen = attempts.setdefault(row["run"], row) # the driver that watched it knew most
74
+ seen["incarnations"] = max(seen.get("incarnations") or 0, row.get("incarnations") or 0)
75
+ seen["set_aside"] = "; ".join(filter(None, {seen.get("set_aside"), row.get("set_aside")}))
76
+ if row.get("outcome") == "controller lost":
77
+ seen["outcome"] = row["outcome"]
78
+ kept = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines() if x]
79
+ reasons = Counter(reason(r, root / "runs" / run) for run, r in attempts.items())
80
+ counted = {(r["tree"], r["agents"]) for r in kept}
81
+ missing = sorted({(r["tree"], r["agents"]) for r in attempts.values()} - counted)
82
+ rerun = sum(r.get("reruns", 0) > 0 for r in kept) + len(missing)
83
+ lines = [(f"Attempts set aside: {len(attempts)} (rows-discarded.jsonl); teams that needed a "
84
+ f"rerun: {rerun} of {len(counted) + len(missing)}"), ""]
85
+ lines += [f"- {why}: {k}" for why, k in reasons.most_common()]
86
+ if missing:
87
+ lines += ["", f"Teams with no attempt that counted ({len(missing)}; missing from the "
88
+ "results, not failures): " + ", ".join(f"tree {t:02d} at N = {n}"
89
+ for t, n in missing)]
90
+ (root / "setaside.md").write_text("\n".join(lines) + "\n")
91
+ print("\n".join(lines))
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ raise SystemExit(main(Path(sys.argv[1])))
flock/sweep/sweep.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The s3-maze scaling sweep on the HF cluster, one command per model for the whole grid, run
2
+ from Flock's checkout (its environment, and its `.venv` for the workers):
3
+
4
+ uv run python <this dataset>/flock/sweep/sweep.py --urls http://<vllm node>:8000/v1 \\
5
+ --model Qwen/Qwen3.5-27B --tag q27- --revision <sha> [--trees 1-32] \\
6
+ [--agents 1,2,4,8,16] [--parallel 20] [--max-agents 64] [--root .flock/s3-maze-sweep/q27]
7
+
8
+ s3-aggregation's flock/sweep/sweep.py for the maze. Each (tree, N) team is its own flock run
9
+ (`compute: slurm`, podman agents on hopper-cpu, a local board on its one worker), from team.py's
10
+ cluster spec with the sweep's model on `urls`: the same board rules, loop, limits and move
11
+ budget at every N, and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per
12
+ maze service and two more (at least 4), at 1900 MB per CPU. Per team: `flock init`,
13
+ `flock launch`, then wait until the first agent's exit stops the run (and every Trial is
14
+ graded) or the loop is done and the agents are idle; `flock stop --release` (which grades the
15
+ Trials of a run nobody won, and ends the controller in either case); then eval/metrics.py's row
16
+ plus the wall time and the tree's exit branch go to `<root>/rows.jsonl`.
17
+
18
+ A run counts only when its worker started within WAIT_LIMIT of its launch (the loop's time
19
+ counts from the launch), on one worker incarnation (flock#121), with its controller kept and
20
+ nothing missing (every agent's reward and move log, the board export). Anything else is the
21
+ infrastructure's, so the team runs again as `<task>-rK` and the attempt goes to
22
+ `rows-discarded.jsonl`; what the model does (no move, no post, no exit) is a result. A team with
23
+ a row is skipped, so the same command resumes; a team a stopped driver launched is adopted and
24
+ keeps its own start time for its time cap.
25
+
26
+ At most `--parallel` teams and `--max-agents` agents run at once (the agents of the teams in
27
+ flight; `<root>/max_agents`, when present, overrides it while the driver runs): one GPU's KV
28
+ cache holds a few dozen agents' contexts of a large model, and an overloaded server would make
29
+ the loop's time limit, not the move budget, decide the result.
30
+
31
+ Needs HF_TOKEN (or `hf auth login`): the workers clone the private task dataset and sync the
32
+ private state bucket with it. The agents get no Hub token; the vLLM servers take no key.
33
+ """
34
+
35
+ import argparse
36
+ import importlib.util
37
+ import itertools
38
+ import json
39
+ import os
40
+ import re
41
+ import shutil
42
+ import subprocess
43
+ import sys
44
+ import threading
45
+ import time
46
+ from collections import Counter
47
+ from concurrent.futures import ThreadPoolExecutor
48
+ from datetime import UTC, datetime
49
+ from pathlib import Path
50
+
51
+ import httpx
52
+ import yaml
53
+ from huggingface_hub import HfApi, get_token
54
+
55
+ from flock.models import Inference
56
+
57
+ HERE = Path(__file__).resolve().parent
58
+ DATASET_DIR = HERE.parents[1]
59
+ REPO = Path.cwd() # Flock's checkout
60
+ SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")
61
+ lock, init_lock = threading.Lock(), threading.Semaphore(4)
62
+ LOST, GONE = "controller lost", "no controller left"
63
+ WAIT_LIMIT = 120 # s: a worker that started later than this after the launch doesn't count
64
+ MB_PER_CPU = 1900
65
+ # runs started in this window (`--overloaded START/END`, ISO times) ran on a model server whose
66
+ # KV cache was thrashing (too many agents for its GPU): the server, not the model, decided them
67
+ OVERLOADED: tuple[datetime, datetime] | None = None
68
+ # the servers' health log (`--health`: one JSON line per server and minute, with its prefix-cache
69
+ # hit rate): a run in which an agent's server thrashed this many minutes doesn't count
70
+ HEALTH: Path | None = None
71
+ THRASH_LIMIT = 5
72
+
73
+
74
+ def load(name: str, path: Path):
75
+ spec = importlib.util.spec_from_file_location(name, path)
76
+ module = importlib.util.module_from_spec(spec)
77
+ spec.loader.exec_module(module)
78
+ return module
79
+
80
+
81
+ team = load("team", HERE.parent / "team.py")
82
+ metrics = load("metrics", DATASET_DIR / "eval" / "metrics.py")
83
+
84
+
85
+ def say(*parts) -> None:
86
+ with lock:
87
+ print(datetime.now(UTC).strftime("%H:%M:%S"), *parts, flush=True)
88
+
89
+
90
+ def numbers(text: str) -> list[int]:
91
+ """`1-32` or `1,3,7` -> the numbers."""
92
+ out = []
93
+ for part in text.split(","):
94
+ a, _, b = part.partition("-")
95
+ out += range(int(a), int(b or a) + 1)
96
+ return out
97
+
98
+
99
+ def flock(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess:
100
+ env = {**os.environ, "FLOCK_RUN_DIR": str(run_dir)}
101
+ env.pop("VIRTUAL_ENV", None)
102
+ return subprocess.run([str(Path(sys.executable).with_name("flock")), *args], cwd=REPO,
103
+ env=env, capture_output=True, text=True, timeout=timeout, check=False)
104
+
105
+
106
+ CPUS_PER_AGENT = 1 # --cpus-per-agent; memory follows at MB_PER_CPU
107
+ MEMORY_LADDER: dict | None = None # --memory-ladder: the workers' rotate/drain/preempt fractions
108
+
109
+
110
+ def worker_cpus(n: int) -> int:
111
+ """CPUS_PER_AGENT per agent's container, a quarter of one per maze service, two for the
112
+ worker, podman and the image builds."""
113
+ return max(4, CPUS_PER_AGENT * n + 2 + (n + 3) // 4)
114
+
115
+
116
+ def exit_branch(tree: int) -> int:
117
+ """Which of the start room's doors (1, 2 or 3, in the listed order) leads to the exit."""
118
+ layout = json.loads((DATASET_DIR / "tasks" / f"maze-t{tree:02d}" / "environment" / "maze"
119
+ / "tree.json").read_text())
120
+ path = load("generate", DATASET_DIR / "generate.py").shortest_path(layout)
121
+ return layout["doors"][layout["start"]].index(path[0]) + 1
122
+
123
+
124
+ def write_experiment(src: Path, tree: int, n: int, name: str, urls: list[str], model: str,
125
+ revision: str) -> None:
126
+ """team.py's cluster spec at the dataset `revision`, with the sweep's model on its servers
127
+ and a worker sized to the team, as swarm `name`."""
128
+ team.main(["--tree", str(tree), "--agents", str(n), "--where", "cluster",
129
+ "--revision", revision, "--out", str(src)])
130
+ spec = yaml.safe_load((src / "spec.yaml").read_text())
131
+ spec["name"] = name
132
+ spec["model"] = model
133
+ spec["inference"] = {"urls": urls} # no key: the servers take none
134
+ cpus = worker_cpus(n)
135
+ spec["compute"] |= {"cpus": cpus, "mem": f"{cpus * MB_PER_CPU}M"}
136
+ if MEMORY_LADDER: # an agent's runaway process spikes the worker's memory (podman can't
137
+ # cap a container here): drain or rotate later, so the spike doesn't end the run
138
+ spec["workers"].setdefault("worker", {})["memory"] = dict(MEMORY_LADDER)
139
+ (src / "spec.yaml").write_text(
140
+ f"# {spec['task']['selector']} with N = {n} for the scaling sweep (sweep.py): team.py's "
141
+ f"cluster spec with {model} on the sweep's servers.\n" + yaml.safe_dump(spec,
142
+ sort_keys=False))
143
+
144
+
145
+ def profile(root: Path) -> Path:
146
+ """The cluster profile: hopper-cpu, the venv, podman pulling Docker Hub images through a
147
+ mirror (registries.conf)."""
148
+ path = root / "profiles" / "cluster.env"
149
+ path.parent.mkdir(parents=True, exist_ok=True)
150
+ path.write_text(f"SLURM_PARTITION=hopper-cpu\nSLURM_MAX_MEM_PER_CPU_MB=2000\n"
151
+ f"VENV={REPO / '.venv'}\n"
152
+ f"CONTAINERS_REGISTRIES_CONF={HERE.parent / 'registries.conf'}\n")
153
+ path.chmod(0o644)
154
+ return path
155
+
156
+
157
+ def serving(url: str) -> bool:
158
+ """The model server answers `GET /models`."""
159
+ try:
160
+ return httpx.get(f"{url.rstrip('/')}/models", timeout=10).status_code == 200
161
+ except httpx.HTTPError:
162
+ return False
163
+
164
+
165
+ def job_state(name: str) -> str:
166
+ """The Slurm state of the job called `name`, '' when there is none."""
167
+ out = subprocess.run(["squeue", "-h", "-n", name, "-o", "%T"], capture_output=True,
168
+ text=True, check=False).stdout.split()
169
+ return out[0] if out else ""
170
+
171
+
172
+ def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
173
+ """Poll `flock status` until the first exit stopped the run and its Trials are graded
174
+ ('success'), or the loop is done and every agent is idle ('done'): or why not. A controller
175
+ that stops answering and isn't running (a spot reclaim requeued it, or it is gone) is LOST."""
176
+ deadline, unanswered, stopped = time.monotonic() + timeout, 0, None
177
+ while time.monotonic() < deadline:
178
+ status = flock(run_dir, "status", task, timeout=120)
179
+ text = status.stdout
180
+ unanswered = unanswered + 1 if status.returncode != 0 else 0
181
+ if unanswered >= 3 and job_state(f"flock-ctl-{task}") != "RUNNING":
182
+ return LOST
183
+ if re.search(r"crashloop|launch_refused", text):
184
+ return "worker failed: " + " ".join(text.split())[:300]
185
+ if m := re.search(r"STOPPED ON SUCCESS: .*verification: (\w+)", text):
186
+ stopped = stopped or time.monotonic()
187
+ graded = m[1] != "pending" and not job_state(f"{task}-agent-w0000")
188
+ if graded or time.monotonic() - stopped > 600: # the cleanup budget is 5 min
189
+ return "success"
190
+ elif re.search(r"^loop agent: done", text, re.MULTILINE) and (agents := re.search(
191
+ r"^agent .*$", text, re.MULTILINE)) and "working:" not in agents[0]:
192
+ return "done" # no agent in a turn (idle, or stuck: a turn that timed out)
193
+ time.sleep(20)
194
+ return f"not done after {timeout:.0f} s"
195
+
196
+
197
+ def release(run_dir: Path, name: str) -> bool:
198
+ """`flock stop --release`: drains (and so grades) a run nobody won and ends its
199
+ controller; then make sure no job of the run is left."""
200
+ out = flock(run_dir, "stop", name, "--release")
201
+ # once the worker is gone its results are on the shared disk: a controller still up a
202
+ # minute later (it sometimes outlives the release) only holds the team's slot, and SIGTERM
203
+ # makes it push its state and exit
204
+ for job, wait in ((f"{name}-agent-w0000", 900), (f"flock-ctl-{name}", 60)):
205
+ for _ in range(wait // 10): # a draining worker is still grading its Trials
206
+ if not job_state(job):
207
+ break
208
+ time.sleep(10)
209
+ else:
210
+ say(name, f"{job} still there after the release: cancelling it")
211
+ subprocess.run(["scancel", "-n", job], check=False)
212
+ return out.returncode == 0
213
+
214
+
215
+ def attempt(args, root: Path, secrets: Path, tree: int, n: int, name: str,
216
+ urls: list[str]) -> dict | None:
217
+ """One run of a team as swarm `name` on the servers `urls`: its row, or None when it could
218
+ not start."""
219
+ run_dir, src = root / "runs" / name, root / "src" / name
220
+ if run_dir.exists() and (any((run_dir / "launch").glob("*.env"))
221
+ or (run_dir / "hosts" / "controller.host").exists()):
222
+ # a previous driver launched it and stopped before its row: finish it from here (its
223
+ # time cap counts from its own start, cluster.env's), or, with its controller gone,
224
+ # score what it left
225
+ alive = bool(job_state(f"flock-ctl-{name}"))
226
+ say(name, "adopting the run a previous driver launched" + ("" if alive else
227
+ " (no controller left)"))
228
+ return finish(args, run_dir, name, tree, n, (run_dir / "cluster.env").stat().st_mtime,
229
+ None if alive else GONE)
230
+ if run_dir.exists():
231
+ shutil.rmtree(run_dir) # init failed before: nothing ran
232
+ started = time.time()
233
+ # servers retired while the grid drained (or down) are left out, e.g. for a rerun
234
+ urls = [u for u in urls if serving(u)] or [u for u in args.urls if serving(u)] or urls
235
+ write_experiment(src, tree, n, name, urls, args.model, args.revision)
236
+ log = root / "logs" / f"{name}-init.log"
237
+ log.parent.mkdir(parents=True, exist_ok=True)
238
+ for tries in range(6): # its checks probe the model servers, which may be busy
239
+ with init_lock: # a few at a time: many at once race on the bucket's write check
240
+ init = flock(run_dir, "init", str(run_dir), "--from", str(src), "--profile",
241
+ str(profile(root)), "--secrets", str(secrets))
242
+ log.write_text(init.stdout + init.stderr)
243
+ if init.returncode == 0:
244
+ break
245
+ time.sleep(30 * (tries + 1))
246
+ else:
247
+ failed = [x for x in init.stdout.splitlines() if x.startswith("FAIL")]
248
+ say(name, "init failed 6 times:", failed or init.stdout[-300:], "(log:", log, ")")
249
+ return None
250
+ say(name, "launching")
251
+ launch = flock(run_dir, "launch", str(run_dir / "experiment"))
252
+ if launch.returncode != 0:
253
+ say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:])
254
+ return finish(args, run_dir, name, tree, n, started, "launch")
255
+ return finish(args, run_dir, name, tree, n, started)
256
+
257
+
258
+ def finish(args, run_dir: Path, name: str, tree: int, n: int, started: float,
259
+ why: str | None = None) -> dict:
260
+ """Wait for a launched team, release it (its Trials are graded, its controller ends) and
261
+ make its row."""
262
+ why = why or wait_done(run_dir, name, n, max(0.0, args.team_timeout - (time.time() - started)))
263
+ if why == LOST: # nothing to release: end its jobs, and the team runs again
264
+ say(name, "controller lost (spot reclaim?): cancelling its jobs")
265
+ for job in (f"flock-ctl-{name}", f"{name}-agent-w0000"):
266
+ subprocess.run(["scancel", "-n", job], check=False)
267
+ released = False
268
+ elif why == GONE: # its rewards and export are on disk, or it doesn't count
269
+ released = False
270
+ else:
271
+ say(name, "outcome:", why, "- releasing")
272
+ released = release(run_dir, name)
273
+ ended = time.time()
274
+ return metrics.row(run_dir) | {
275
+ "model": args.model, "tree": tree, "exit_branch": exit_branch(tree),
276
+ "wall_s": round(ended - started, 1), "outcome": why, "released": released,
277
+ # each launch of the worker slot writes one env file: more than one is a relaunch or a
278
+ # preemption, whose results a later incarnation overwrites (flock#121)
279
+ "incarnations": len(list((run_dir / "launch").glob("*.env"))),
280
+ "worker_wait_s": worker_wait(run_dir),
281
+ "thrashed_min": thrashed_minutes(run_dir, n, started, ended),
282
+ "started_at": datetime.fromtimestamp(started, UTC).isoformat()}
283
+
284
+
285
+ def thrashed_minutes(run_dir: Path, n: int, start: float, end: float) -> int | None:
286
+ """Minutes, within the run, in which a server one of its agents calls was thrashing: a
287
+ prefix-cache hit rate under 50% while prefilling at least 200k prompt tokens (every call
288
+ recomputing an agent's long context; a cold server's first small prompts don't count), from
289
+ the health log (`--health`); None without one."""
290
+ spec = run_dir / "experiment" / "spec.yaml"
291
+ if HEALTH is None or not HEALTH.is_file() or not spec.is_file():
292
+ return None
293
+ urls = yaml.safe_load(spec.read_text())["inference"]["urls"]
294
+ servers = {u.split("//")[1].removesuffix("/v1") for u in agents_on(urls, n)}
295
+ minutes = set()
296
+ for line in HEALTH.read_text().splitlines():
297
+ s = json.loads(line)
298
+ if (start <= s["t"] <= end and s["server"] in servers and s["hit_rate"] is not None
299
+ and s["hit_rate"] < 0.5 and s["prompt"] >= 200_000):
300
+ minutes.add(int(s["t"] // 60))
301
+ return len(minutes)
302
+
303
+
304
+ def worker_wait(run_dir: Path) -> float | None:
305
+ """Seconds from the controller writing the worker's first launch file to the worker job's
306
+ first log line (None: not known)."""
307
+ launches = sorted((run_dir / "launch").glob("*.env"), key=lambda p: p.stat().st_mtime)
308
+ logs = sorted((run_dir / "logs").glob("*-agent-w*.out"))
309
+ if not launches or not logs:
310
+ return None
311
+ first = logs[0].read_text(errors="replace").split("\n", 1)[0]
312
+ try:
313
+ began = datetime.fromisoformat(first.split(" ", 1)[0])
314
+ except ValueError:
315
+ return None
316
+ return round(began.timestamp() - launches[0].stat().st_mtime, 1)
317
+
318
+
319
+ def why_invalid(row: dict) -> str:
320
+ """Why a team's run doesn't count ('' when it does): the infrastructure's failures, never the
321
+ model's."""
322
+ wait = row.get("worker_wait_s")
323
+ started = datetime.fromisoformat(row["started_at"]) if row.get("started_at") else None
324
+ overloaded = bool(OVERLOADED and started and OVERLOADED[0] <= started < OVERLOADED[1])
325
+ thrashed = row.get("thrashed_min") or 0
326
+ return "; ".join(why for why, bad in (
327
+ ("ran on an overloaded model server (KV-cache thrash)", overloaded),
328
+ (f"an agent's model server thrashed for {thrashed} min", thrashed >= THRASH_LIMIT),
329
+ (f"{row.get('incarnations')} worker incarnations", row.get("incarnations") != 1),
330
+ ("worker never started", wait is None),
331
+ (f"worker started {wait or 0:.0f} s after the launch", (wait or 0) > WAIT_LIMIT),
332
+ (LOST, row.get("outcome") == LOST),
333
+ (f"missing {', '.join(row['missing'])}"[:160], bool(row["missing"]))) if bad)
334
+
335
+
336
+ def valid(row: dict) -> bool:
337
+ return not why_invalid(row)
338
+
339
+
340
+ def run_team(args, root: Path, secrets: Path, tree: int, n: int,
341
+ urls: list[str]) -> dict | None:
342
+ """A team, run again (as `<task>-rK`) until its run counts."""
343
+ task = f"{args.tag}maze-t{tree:02d}-n{n:02d}"
344
+ row = None
345
+ for reruns in range(args.max_reruns + 1):
346
+ row = attempt(args, root, secrets, tree, n, task if reruns == 0 else f"{task}-r{reruns}",
347
+ urls)
348
+ if row is None:
349
+ return None
350
+ row["reruns"] = reruns
351
+ if valid(row):
352
+ break
353
+ say(task, f"run doesn't count ({why_invalid(row)}): running it again")
354
+ row["set_aside"] = why_invalid(row)
355
+ with lock, (root / "rows-discarded.jsonl").open("a") as f:
356
+ f.write(json.dumps(row) + "\n")
357
+ else:
358
+ say(task, f"gave up after {args.max_reruns} reruns")
359
+ return row
360
+ with lock, (root / "rows.jsonl").open("a") as f:
361
+ f.write(json.dumps(row) + "\n")
362
+ first = row.get("first_exit") or {}
363
+ say(task, f"success={row['success']} exit={first.get('agent')} after "
364
+ f"{first.get('after_s')} s, {first.get('team_moves')} team moves; posts={row['posts']} "
365
+ f"overlap={row.get('room_overlap')} wall={row['wall_s']} s reruns={row['reruns']}")
366
+ return row
367
+
368
+
369
+ def agents_on(urls: list[str], n: int) -> Counter:
370
+ """How many of a team's agents (agent-001 .. agent-00N) call each server: flock hashes each
371
+ agent's name over the team's URLs (Inference.endpoint_for), so with consecutive names
372
+ agent-001 calls the same server in every team that has the same URLs."""
373
+ block = Inference(urls=urls)
374
+ return Counter(block.endpoint_for(f"agent-{k:03d}") for k in range(1, n + 1))
375
+
376
+
377
+ class Slots:
378
+ """At most `parallel` teams, `max_agents` agents and `per_server` agents per model server
379
+ (`<root>/max_agents` and `<root>/per_server` override them while the driver runs) in flight,
380
+ granted in order. Each new team gets the subset of the servers that spreads its agents onto
381
+ the least-loaded ones (one server's KV cache holds about a dozen long agent contexts)."""
382
+
383
+ def __init__(self, root: Path, urls: list[str], parallel: int, max_agents: int,
384
+ per_server: int):
385
+ self.root, self.urls, self.parallel = root, urls, parallel
386
+ self.defaults = {"max_agents": max_agents, "per_server": per_server}
387
+ self.cond, self.teams, self.agents, self.load = threading.Condition(), 0, 0, Counter()
388
+
389
+ def cap(self, name: str) -> int:
390
+ try:
391
+ return int((self.root / name).read_text().strip())
392
+ except (OSError, ValueError):
393
+ return self.defaults[name]
394
+
395
+ def choose(self, n: int) -> list[str] | None:
396
+ """The subset of the servers whose mapping keeps every server within its cap and the
397
+ busiest as idle as possible; None when none fits now."""
398
+ best, cap = None, self.cap("per_server")
399
+ for size in range(1, len(self.urls) + 1):
400
+ for subset in itertools.combinations(self.urls, size):
401
+ added = agents_on(list(subset), n)
402
+ busiest = max(self.load[u] + k for u, k in added.items()) # where it adds only
403
+ after = self.load + added
404
+ score = (busiest, sum(v * v for v in after.values()))
405
+ if busiest <= cap and (best is None or score < best[0]):
406
+ best = (score, list(subset))
407
+ return best[1] if best else None
408
+
409
+ def take(self, n: int, urls: list[str] | None = None) -> list[str]:
410
+ """Wait for room for a team of n; `urls`: an adopted team's own (it already runs)."""
411
+ with self.cond:
412
+ while True:
413
+ if self.teams < self.parallel and (not self.agents or urls is not None
414
+ or self.agents + n <= self.cap("max_agents")):
415
+ chosen = urls or self.choose(n)
416
+ if chosen is not None or not self.agents:
417
+ chosen = chosen or list(self.urls)
418
+ break
419
+ self.cond.wait(30)
420
+ self.teams, self.agents = self.teams + 1, self.agents + n
421
+ self.load += agents_on(chosen, n)
422
+ return chosen
423
+
424
+ def give(self, n: int, urls: list[str]) -> None:
425
+ with self.cond:
426
+ self.teams, self.agents = self.teams - 1, self.agents - n
427
+ self.load -= agents_on(urls, n)
428
+ self.cond.notify_all()
429
+
430
+
431
+ def live_urls(root: Path, tag: str, tree: int, n: int) -> list[str] | None:
432
+ """The URLs of a team's run that a stopped driver launched and whose controller is still
433
+ there (it keeps them), else None."""
434
+ for spec in sorted((root / "src").glob(f"{tag}maze-t{tree:02d}-n{n:02d}*/spec.yaml")):
435
+ if job_state(f"flock-ctl-{spec.parent.name}"):
436
+ return yaml.safe_load(spec.read_text())["inference"]["urls"]
437
+ return None
438
+
439
+
440
+ def upload(root: Path, dataset: str, prefix: str) -> None:
441
+ """Each run directory's spec, results and logs, and the rows, to a private dataset; never
442
+ run.env, and nothing that holds a Hub token."""
443
+ api = HfApi()
444
+ api.create_repo(dataset, repo_type="dataset", private=True, exist_ok=True)
445
+ if not api.dataset_info(dataset).private:
446
+ raise SystemExit(f"{dataset} is public: refusing to upload")
447
+ allow = ["*.jsonl", "*.csv", "*.md", "*.png", "runs/*/experiment/**", "runs/*/results/**",
448
+ "runs/*/logs/**", "driver.log"]
449
+ leaks = [str(p) for p in root.rglob("*") if p.is_file() and not p.name.endswith(".env")
450
+ and SECRET.search(p.read_text(errors="ignore"))]
451
+ if leaks:
452
+ raise SystemExit(f"refusing to upload: Hub tokens in {leaks[:5]}")
453
+ api.upload_folder(repo_id=dataset, repo_type="dataset", folder_path=root,
454
+ path_in_repo=prefix, allow_patterns=allow,
455
+ commit_message=f"s3-maze sweep: {prefix}")
456
+ say("uploaded", root, "to", f"{dataset}/{prefix}")
457
+
458
+
459
+ def main(argv=None) -> int:
460
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
461
+ parser.add_argument("--urls", required=True, help="the model servers, comma-separated")
462
+ parser.add_argument("--model", required=True)
463
+ parser.add_argument("--tag", required=True,
464
+ help="put before every run and swarm name (e.g. q27-): two grids at "
465
+ "once then never share a Slurm job name")
466
+ parser.add_argument("--revision", help="the dataset revision every team pins (default: its "
467
+ "head)")
468
+ parser.add_argument("--trees", default="1-32")
469
+ parser.add_argument("--agents", default="1,2,4,8,16")
470
+ parser.add_argument("--parallel", type=int, default=20, help="teams at once")
471
+ parser.add_argument("--max-agents", type=int, default=1000, help="agents at once")
472
+ parser.add_argument("--per-server", type=int, default=1000,
473
+ help="agents at once per model server (each team gets the subset of "
474
+ "--urls that keeps the servers within it)")
475
+ parser.add_argument("--team-timeout", type=float, default=4800,
476
+ help="s from a team's start until it is released anyway")
477
+ parser.add_argument("--max-reruns", type=int, default=4,
478
+ help="runs again of a team whose run doesn't count (why_invalid)")
479
+ parser.add_argument("--root", type=Path, required=True)
480
+ parser.add_argument("--bucket", default="lewtun/s3-maze-sweep",
481
+ help="private bucket for the runs' state (a swarm's name is used once "
482
+ "in a bucket)")
483
+ parser.add_argument("--namespace", default="lewtun")
484
+ parser.add_argument("--dataset", help="private dataset for the run directories")
485
+ parser.add_argument("--prefix", help="folder in the dataset (default: the root's name)")
486
+ parser.add_argument("--overloaded", help="START/END (ISO times): runs started then ran on "
487
+ "an overloaded model server, and run again")
488
+ parser.add_argument("--health", type=Path,
489
+ help="the servers' health log (health-log.sh's servers.jsonl)")
490
+ parser.add_argument("--cpus-per-agent", type=int, default=1,
491
+ help="worker CPUs (and so memory, at 1900 MB each) per agent")
492
+ parser.add_argument("--memory-ladder", help="ROTATE,DRAIN,PREEMPT: the workers' memory "
493
+ "fractions (default: flock's 0.75,0.85,0.93)")
494
+ args = parser.parse_args(argv)
495
+ global HEALTH, CPUS_PER_AGENT, MEMORY_LADDER
496
+ HEALTH = args.health
497
+ CPUS_PER_AGENT = args.cpus_per_agent
498
+ if args.memory_ladder:
499
+ MEMORY_LADDER = dict(zip(("rotate", "drain", "preempt"),
500
+ map(float, args.memory_ladder.split(",")), strict=True))
501
+ if args.overloaded:
502
+ global OVERLOADED
503
+ start, end = (datetime.fromisoformat(t) for t in args.overloaded.split("/"))
504
+ OVERLOADED = (start, end)
505
+ args.urls = args.urls.split(",")
506
+ args.revision = team.pinned(args.revision)
507
+ root = args.root.resolve()
508
+ root.mkdir(parents=True, exist_ok=True)
509
+ api = HfApi()
510
+ api.create_bucket(args.bucket, private=True, exist_ok=True)
511
+ if not api.bucket_info(args.bucket).private:
512
+ raise SystemExit(f"bucket {args.bucket} is public: refusing")
513
+ token = os.environ.get("HF_TOKEN") or get_token()
514
+ secrets = root / f"secrets-{os.getpid()}.env" # per driver
515
+ old = os.umask(0o077)
516
+ secrets.write_text(f"HF_TOKEN={token}\nNAMESPACE={args.namespace}\n"
517
+ f"BUCKET=hf://buckets/{args.bucket}\n")
518
+ os.umask(old)
519
+ rows_file = root / "rows.jsonl"
520
+ rows = [json.loads(x) for x in rows_file.read_text().splitlines()] if rows_file.exists() else []
521
+ for r in rows: # rows from before the health check get it too
522
+ if r.get("thrashed_min") is None and r.get("started_at") and r.get("wall_s"):
523
+ start = datetime.fromisoformat(r["started_at"]).timestamp()
524
+ r["thrashed_min"] = thrashed_minutes(root / "runs" / r["run"], r["agents"], start,
525
+ start + r["wall_s"])
526
+ if bad := [r for r in rows if not valid(r)]: # an earlier driver kept them: run them again
527
+ with (root / "rows-discarded.jsonl").open("a") as f:
528
+ f.write("".join(json.dumps(r | {"set_aside": why_invalid(r)}) + "\n" for r in bad))
529
+ rows_file.write_text("".join(json.dumps(r) + "\n" for r in rows if valid(r)))
530
+ say(f"{len(bad)} rows that don't count moved to rows-discarded.jsonl")
531
+ done = {(r["tree"], r["agents"]) for r in rows if valid(r)}
532
+ teams = [(t, n) for t in numbers(args.trees) for n in numbers(args.agents)
533
+ if (t, n) not in done]
534
+ # teams a stopped driver launched first: they hold their own time and their workers
535
+ launched = {(t, n) for t, n in teams if any((root / "runs").glob(
536
+ f"{args.tag}maze-t{t:02d}-n{n:02d}*/launch/*.env"))}
537
+ teams.sort(key=lambda t: t not in launched)
538
+ say(f"{len(teams)} teams to run ({len(done)} done, {len(launched)} to adopt), "
539
+ f"{args.parallel} teams and {args.max_agents} agents at once, on {args.urls}")
540
+ slots = Slots(root, args.urls, args.parallel, args.max_agents, args.per_server)
541
+
542
+ def one(t: int, n: int, urls: list[str]):
543
+ try:
544
+ return run_team(args, root, secrets, t, n, urls)
545
+ except Exception as e: # noqa: BLE001 - one team's failure must not stop the grid
546
+ say(f"{args.tag}maze-t{t:02d}-n{n:02d}", "failed:", repr(e)[:300])
547
+ finally:
548
+ slots.give(n, urls)
549
+
550
+ try:
551
+ with ThreadPoolExecutor(args.parallel) as pool:
552
+ for t, n in teams:
553
+ urls = slots.take(n, live_urls(root, args.tag, t, n))
554
+ pool.submit(one, t, n, urls)
555
+ finally:
556
+ secrets.unlink(missing_ok=True)
557
+ if args.dataset:
558
+ upload(root, args.dataset, args.prefix or root.name)
559
+ return 0
560
+
561
+
562
+ if __name__ == "__main__":
563
+ sys.exit(main())