Datasets:

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

Keep s3-aggregation Harbor-native

Browse files

Remove the runner's launch, sweep and result scripts from the dataset. Keep the Harbor tasks, generators and checks that run independently of a runner. The 992 generated Harbor tasks are byte-for-byte unchanged.

The previous named run setup remains reproducible at `bc8474f012ef8270fde97e93a828c929e867ff3d`.

The standalone generator and grader checks passed, and the Harbor Oracle scored 1 in a rootless Podman Trial on `hopper-cpu` (Slurm `515147`).

README.md CHANGED
@@ -17,12 +17,9 @@ size_categories:
17
  A [Harbor](https://harborframework.com) environment that measures whether a swarm of agents
18
  **communicates**: each agent holds one private number, and no agent can solve the task alone. It
19
  adapts the information-aggregation task of
20
- [s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615)
21
- ([scalingswarms.com](https://scalingswarms.com)) to [Legion](https://github.com/huggingface/legion)
22
- swarms, whose agents talk over a shared message board. It isn't a replication of the paper: the
23
- agents are Pi with Legion's board, and the board is what we measure.
24
-
25
- **This dataset is private for now.**
26
 
27
  ## The task
28
 
@@ -50,22 +47,14 @@ tasks/agg-pPP-nNN-sKK/ slot K of team agg-pPP-nNN (zero-padded: name order is
50
  tests/test.sh the grader, the same for every slot of the team
51
  tests/expected.json the team's answer: copied in only after the agent is done
52
  solution/solve.sh an oracle with its own copy of the answer
53
- legion/
54
- spec.template.yaml what every team's Legion run shares: model, board rules, loop, limits
55
- team.py writes one team's spec (docker, HF Sandboxes or the HF cluster)
56
- sweep/ the scaling sweep on the HF cluster (legion/sweep/README.md)
57
- eval/metrics.py one row per team from Legion run directories
58
  problems.json the 32 problems
59
  generate.py writes problems.json and tasks/ from its seed (115)
60
  check.py the checks that need no model
61
  ```
62
 
63
- **Private numbers** reach each agent only through its own task. Legion runs a team with the
64
- selector `agg-pPP-nNN-s*`, `agents.count: N` and `naming: consecutive-id`: the selector matches
65
- the team's N slots, sorted by name, and `agent-00K` runs slot K's task, so its instruction
66
- holds its own number and no one else's. A task folder puts nothing in the container while the
67
- agent works (no `environment/`; `tests/` arrives after the agent is done), so no agent can read
68
- another agent's number until that agent posts it.
69
 
70
  ## Reward
71
 
@@ -83,102 +72,16 @@ working directory or on `PYTHONPATH`, and no `sitecustomize`, `usercustomize` or
83
  can change what it imports; besides `bash`, `python3` is the only command it runs. Each agent is
84
  scored on its own answer; the team succeeds if any agent scores 1.
85
 
86
- ## Run it with Legion
87
-
88
- Legion's [`experiments/s3-aggregation/spec.yaml`](https://github.com/huggingface/legion/tree/main/experiments/s3-aggregation)
89
- runs one team on HF Sandboxes (`TEAM`, default `agg-p01-n04`, with `N` its size) at the revision
90
- it pins: `uv run legion launch experiments/s3-aggregation/spec.yaml`. Its board is a public Space
91
- for the run: delete it afterwards.
92
-
93
- For any other team or place, `legion/team.py` writes the spec from `legion/spec.template.yaml`,
94
- run from Legion's checkout. **Needs** `HF_TOKEN`, which reads the private dataset (and starts the
95
- sandboxes and deploys the board's Space), and `HF_INFERENCE_TOKEN`, a fine-grained token with
96
- only "Make calls to Inference Providers", which goes into the agents' containers. Never the same
97
- token. Each agent of a team is `agent-001` ... (`naming: consecutive-id`), all one Legion type on
98
- one worker (`agents_per_worker: N`), so they share that worker's board.
99
 
100
- ### On HF Sandboxes
101
-
102
- The controller and the team's one worker run on this machine, each agent in its own HF Sandbox
103
- (`cpu-basic`) and the board on a Space:
104
 
105
  ```sh
106
- DS=../s3-aggregation # this dataset, at the revision team.py pins
107
- uv run python $DS/legion/team.py --problem 7 --agents 4 --where sandbox --out runs/agg-p07-n04
108
- BOARD_SPACE=<you>/s3-agg-p07-n04 uv run legion launch runs/agg-p07-n04/spec.yaml
109
- uv run legion status agg-p07-n04
110
- uv run python $DS/eval/metrics.py .legion/agg-p07-n04-<time>/ # once the run has ended
111
- hf repos delete <you>/s3-agg-p07-n04 --repo-type space -y # a new board for every team
112
- hf buckets delete <you>/s3-agg-p07-n04-bucket # its snapshots
113
  ```
114
 
115
- The run ends by itself once its loop is over (4 rounds or 15 minutes) and every agent is idle,
116
- then Harbor grades each agent's `/app/answer.json` and the board is exported into the run
117
- directory. The board's Space must be public while the run uses it (the sandboxes hold no Hub
118
- token), and the instruction has no run tag, so give each team a new Space and delete it, and its
119
- snapshot bucket, once the run directory has the export.
120
-
121
- ### On the HF cluster
122
-
123
- `--where cluster` writes the spec for one Slurm worker running the team in rootless podman
124
- (hopper-cpu has podman 4.9), with a local board on that worker, new each run, so no Space. The
125
- run directory goes on the shared disk (Legion's docs/slurm.md "Deploying"): a cluster profile with
126
- `SLURM_PARTITION=hopper-cpu`, `WORKER_CPUS` and `WORKER_MEM` (at most 2000 MB per CPU there)
127
- and `VENV`, and a mode-600 secrets file with `HF_TOKEN`, `HF_INFERENCE_TOKEN`, `NAMESPACE` and
128
- `BUCKET` (a private bucket for the run's state):
129
-
130
- ```sh
131
- uv run python $DS/legion/team.py --problem 7 --agents 4 --where cluster --out runs/src/agg-p07-n04
132
- uv run legion init $PWD/runs/agg-p07-n04 --from runs/src/agg-p07-n04 --profile cluster.env --secrets secrets.env
133
- export LEGION_RUN_DIR=$PWD/runs/agg-p07-n04
134
- uv run legion launch $LEGION_RUN_DIR/experiment
135
- uv run legion status agg-p07-n04 # until the loop is done and the agents idle
136
- uv run legion stop agg-p07-n04 --release # drain: each Trial is graded, then the jobs end
137
- uv run python $DS/eval/metrics.py $LEGION_RUN_DIR
138
- ```
139
-
140
- A Slurm run doesn't end by itself: `--release` drains its worker, which is when each Trial is
141
- graded. With Legion's Slurm results (huggingface/legion#122) the worker copies the grading
142
- and the board export to `<run dir>/results/` (its own files are in the node's `/tmp`), and
143
- `metrics.py` reads them from there. `legion/sweep/` runs the whole grid this way.
144
-
145
- ### The board rules
146
-
147
- The same for every eval run, since they shape how agents talk (`legion/spec.template.yaml`): one
148
- channel, `#general`, and no other (`max_channels: 1`: an agent can't create a channel); an
149
- agent is woken by a mention or a reply in its thread; a post is
150
- at most 1000 characters, at least 5 s after the agent's previous one, and at most 40 per agent.
151
- One channel keeps every number in one place, as the paper's broadcast does (in earlier runs,
152
- without the cap, about 70% of Qwen3.5-2B teams made extra channels, though about 98% of their
153
- posts stayed in `#general`); waking on mentions and
154
- threads lets agents talk to each other without a reply to every post; the length, gap and count
155
- caps bound what a looping agent can flood the board with, well above what the task needs (one
156
- post per agent). Docker and podman enforce them in each agent's rule proxy. HF Sandboxes have no
157
- proxy, so there they are not enforced and each Trial records a `message_board.warning` event.
158
-
159
- ## Metrics
160
-
161
- `uv run python eval/metrics.py RUN_DIR [RUN_DIR ...] [--out rows.jsonl]` writes one JSON line
162
- per run directory (one team): a local run's `.legion/<swarm>-<time>/`, or a Slurm run's
163
- directory. A Slurm run has no local bundle, so there the tokens come from Harbor's Trial results
164
- (no reasoning split) and `stop_reason`, `cost_usd` and the turns are `null`:
165
-
166
- | field | |
167
- | --- | --- |
168
- | `task`, `agents`, `revision`, `stop_reason`, `duration_s` | the team and how its run ended |
169
- | `success` | any agent's reward is 1 (`null`: no rewards found) |
170
- | `rewards` | each agent's reward: its latest Trial's verifier result |
171
- | `tokens`, `cost_usd` | the team's tokens (input, output, cache, reasoning) and cost |
172
- | `posts`, `other_posts` | the team's board posts in the run; posts by anyone else |
173
- | `per_agent` | each agent's reward, tokens, posts and turns |
174
- | `edges` | the message graph: sender -> each teammate it mentions (a group mention names every member) or messages directly (a DM, or a private channel of the two) |
175
- | `centralization` | the paper's (Appendix M): the sum over agents of (k* - k_j) / (N - 1)^2, k_j the in-degree; 0 when every agent receives from as many teammates, 1 when one receives from all and no one else from anyone; `null` for N = 1 |
176
- | `reciprocity` | the fraction of edges whose reverse exists; `null` without edges |
177
- | `missing` | what the run directory lacks: an agent's reward, the board export |
178
-
179
- Only messages posted between the run's start and end count. A post that mentions no one adds no
180
- edge: on a board everyone reads every post, so a broadcast edge (the paper's) would connect
181
- every pair that posts. s3-maze adds its move-log metrics to the same rows (`EXTRAS`).
182
 
183
  ## Checks
184
 
@@ -188,7 +91,6 @@ The checks that need no model, in one command (`uv` installs Harbor 0.25.0):
188
  uv run check.py # the Trials on HF Sandboxes (HF_TOKEN, twenty cpu-basic sandboxes)
189
  uv run check.py --env docker # the Trials in local docker
190
  uv run check.py --env none # without the Trials
191
- uv run check.py --env none --run RUN_DIR # also a Legion run of a team (below)
192
  ```
193
 
194
  1. **Generator:** `generate.py` reproduces `problems.json` and `tasks/` byte for byte; another
@@ -220,50 +122,18 @@ uv run check.py --env none --run RUN_DIR # also a Legion run of a team (below)
220
  and the verifier scores each 0: `/app/answer.json` as a symlink to `/tests/expected.json`;
221
  `/app` as a symlink into a `/tests` they made; a `json.py` that reads any answer as right
222
  wherever the verifier may start; a `sitecustomize` in site-packages that does the same.
223
- 5. **No-cheat, a Legion run** (`--run RUN_DIR`, a local run's `.legion/<swarm>-<time>/`): each
224
- agent's first prompt (its task's instruction and Legion's) holds its own number and no
225
- teammate's; the first tool output in which an agent sees a teammate's number is a board read,
226
- after that teammate posted it; and the first post holding each number is its owner's. A
227
- number counts in words and in digits where they read as a held number: an array of the
228
- team's integers (the JSON answer, or part of it, down to `[26]`), an agent's number in a
229
- mapping (`"agent-002": 26`) or a stated number (`number is 26`); bare ids, counts and
230
- timestamps don't. A board read is a `legion-tool message_board.*` command, not one that names
231
- the board (`cat /tmp/message_board.txt`). The audit itself runs on synthetic runs every time:
232
- a clean one, and one whose ids and timestamps hold the team's numbers, pass; a teammate's
233
- number in words, the JSON answer, a one-element array, a mapping or a stated number in the
234
- first prompt or in a non-board output before the board (one from a file named after the board
235
- included) fail, and so does a number first posted by an agent that doesn't hold it.
236
- 6. **Metrics:** `eval/metrics.py` on Slurm run directories (the spec Legion's example copies,
237
- with `${TEAM:-...}` and `${N:-4}`, and Trials graded by the tasks' own grader): the task and
238
- the roster come from the spec as the run resolved it (`cluster.env`, then `run.env`, else the
239
- defaults), and a planned agent without results, Trials of an unplanned agent and Trials of
240
- another task than the spec selects are flagged in `missing`, never dropped.
241
-
242
- `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads
243
- `tests/` with the host's file owner, which a sandbox can't take when the host's uid is over
244
- 65535 (some clusters); Legion's `--env legion.harbor.envs:HFSandbox`, with Legion installed, keeps
245
- no owner.
246
-
247
- To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04-s01 --agent oracle --env hf-sandbox`.
248
-
249
  ## Known limits
250
 
251
- - **Private for now**, so whatever resolves and downloads the task (Legion's worker, which then
252
- uploads it into the sandbox) needs a Hub token that can read it. The sandboxes never do.
253
- - **A team needs one agent per slot.** Each slot's task is one agent's view: run a team's N
254
- slots together on one board (Legion's selector `agg-pPP-nNN-s*` with `agents.count: N`), or a
255
- task alone is an agent whose teammates never post.
256
  - **The grader can't see the board:** an agent could guess or copy a wrong number and still be
257
  scored only on its file. The board export in the run directory shows what was said.
258
  - **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the
259
  file and import holes above, but an agent that replaced the container's `python3`, `bash` or
260
  Python's standard library, or left a process running to rewrite the reward, could still forge
261
  one: check the run's board export and the agents' transcripts when a result looks too good.
262
- - **One board per team.** The instruction has no run tag, so a reused board's earlier posts
263
- would read as this team's: give each team a new board (Legion's local board is new each run;
264
- delete a Space board after its run).
265
- - **Board rules** are enforced only where Legion's rule proxy runs (docker, podman); on HF
266
- Sandboxes they are not.
267
  - **Not the paper's setup:** a message board instead of `message`/`read_messages` tools with
268
  notifications, an answer file instead of a `####` line, no example message, no token cost in
269
  the reward, and N = 1 is a solo control rather than a team.
 
17
  A [Harbor](https://harborframework.com) environment that measures whether a swarm of agents
18
  **communicates**: each agent holds one private number, and no agent can solve the task alone. It
19
  adapts the information-aggregation task of
20
+ [s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615).
21
+ A team uses a shared message board supplied by the runner. Each participant receives its own
22
+ Harbor task.
 
 
 
23
 
24
  ## The task
25
 
 
47
  tests/test.sh the grader, the same for every slot of the team
48
  tests/expected.json the team's answer: copied in only after the agent is done
49
  solution/solve.sh an oracle with its own copy of the answer
 
 
 
 
 
50
  problems.json the 32 problems
51
  generate.py writes problems.json and tasks/ from its seed (115)
52
  check.py the checks that need no model
53
  ```
54
 
55
+ **Private numbers** reach each participant through its own task. To run a team, assign each
56
+ participant one of its slots in name order and give the team a fresh board shared only among
57
+ its members. Harbor copies `tests/` in after the agent has finished.
 
 
 
58
 
59
  ## Reward
60
 
 
72
  can change what it imports; besides `bash`, `python3` is the only command it runs. Each agent is
73
  scored on its own answer; the team succeeds if any agent scores 1.
74
 
75
+ ## Run a Harbor task
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ Validate the grader with the oracle for one slot:
 
 
 
78
 
79
  ```sh
80
+ uv run --with harbor==0.25.0 harbor run --path tasks/agg-p01-n02-s01 --agent oracle --env docker
 
 
 
 
 
 
81
  ```
82
 
83
+ For a cooperative run, the runner supplies the shared message board and aggregates the
84
+ individual Trial rewards. The team succeeds if any participant earns 1.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  ## Checks
87
 
 
91
  uv run check.py # the Trials on HF Sandboxes (HF_TOKEN, twenty cpu-basic sandboxes)
92
  uv run check.py --env docker # the Trials in local docker
93
  uv run check.py --env none # without the Trials
 
94
  ```
95
 
96
  1. **Generator:** `generate.py` reproduces `problems.json` and `tasks/` byte for byte; another
 
122
  and the verifier scores each 0: `/app/answer.json` as a symlink to `/tests/expected.json`;
123
  `/app` as a symlink into a `/tests` they made; a `json.py` that reads any answer as right
124
  wherever the verifier may start; a `sitecustomize` in site-packages that does the same.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  ## Known limits
126
 
127
+ - Each multi-agent task is one participant's view. Its teammates' numbers are available
128
+ through the runner's message board.
 
 
 
129
  - **The grader can't see the board:** an agent could guess or copy a wrong number and still be
130
  scored only on its file. The board export in the run directory shows what was said.
131
  - **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the
132
  file and import holes above, but an agent that replaced the container's `python3`, `bash` or
133
  Python's standard library, or left a process running to rewrite the reward, could still forge
134
  one: check the run's board export and the agents' transcripts when a result looks too good.
135
+ - Give each team a fresh board so it only sees posts from its own run.
136
+
 
 
 
137
  - **Not the paper's setup:** a message board instead of `message`/`read_messages` tools with
138
  notifications, an answer file instead of a `####` line, no example message, no token cost in
139
  the reward, and N = 1 is a solo control rather than a team.
check.py CHANGED
@@ -7,7 +7,6 @@
7
  uv run check.py # all of them; the Trials run on HF Sandboxes (HF_TOKEN)
8
  uv run check.py --env docker # the Trials in local docker instead
9
  uv run check.py --env none # skip the Trials
10
- uv run check.py --run RUN_DIR # also a Legion run of a team (group 5)
11
 
12
  1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed;
13
  another seed gives other problems; 32 problems of 16 integers in 1..99; the English words
@@ -40,29 +39,7 @@
40
  /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any
41
  answer as right wherever the verifier may start; a sitecustomize in site-packages that
42
  does the same. The verifier scores each 0.
43
- `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
44
- uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
45
- over 65535 (some clusters): use legion's `--env legion.harbor.envs:HFSandbox` there.
46
- 5. No-cheat, a Legion run (`--run`, a local run's directory with its agents' event streams and
47
- the board export; the team is the selector's `agg-pPP-nNN`, agent K on slot K): no system
48
- prompt or first prompt holds a teammate's number, and each agent's first prompt holds its
49
- own; the first output in which an agent sees a teammate's number is a board read, or a later
50
- prompt (a wake-up quoting the board); and the first post holding each number is its owner's.
51
- A number counts in words ("twenty-six") and in digits where they read as a held number: an
52
- array of the team's integers (the JSON answer, or part of it, down to `[26]`), an agent's
53
- number in a mapping (`"agent-002": 26`) and a stated number (`number is 26`); bare ids,
54
- counts and timestamps don't. A board read is a `legion-tool message_board.*` command, not a
55
- command that names the board (`cat /tmp/message_board.txt`). The audit itself is checked on
56
- synthetic runs, always: a clean one and one whose ids and timestamps hold the team's numbers
57
- pass, and each leak fails (a teammate's number in words, the JSON answer, a one-element
58
- array, a mapping and a stated number, in the first prompt or in a non-board output before the
59
- board, including one from a file named after the board, and a number first posted by an agent
60
- that doesn't hold it).
61
- 6. Metrics: eval/metrics.py on Slurm run directories (the spec Legion's example copies, its
62
- `${TEAM:-...}` and `${N:-4}`, Trials graded by the tasks' own grader): the task and the roster
63
- come from the spec as the run resolved it (`cluster.env`, then `run.env`, else the defaults),
64
- and a planned agent without results, Trials of an unplanned agent and Trials of another task
65
- than the spec selects are flagged in `missing`, never dropped.
66
  """
67
 
68
  import argparse
@@ -76,7 +53,6 @@ import shutil
76
  import subprocess
77
  import sys
78
  import tempfile
79
- from collections import Counter
80
  from pathlib import Path
81
 
82
  HERE = Path(__file__).resolve().parent
@@ -122,7 +98,7 @@ def team_of(task: str) -> tuple[int, int]:
122
 
123
 
124
  def held(team: str) -> dict[str, str]:
125
- """A team's agents (Legion's consecutive names: agent K on slot K) and their numbers."""
126
  problem, n = team_of(team)
127
  numbers = json.loads((HERE / "problems.json").read_text())["problems"][f"p{problem:02d}"]
128
  return {f"agent-{k:03d}": g.words(x) for k, x in enumerate(numbers[:n], 1)}
@@ -361,8 +337,7 @@ def check_files() -> None:
361
  f"{task.name}: the answer is in {sorted(holders)}")
362
  check(all(len(v) == 1 for v in by_size.values()),
363
  "an instruction (but its number) or task.toml differs between tasks of one team size")
364
- beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", "legion", "eval", ".cache",
365
- "__pycache__", ".git"}
366
  check(not beside, f"folders beside tasks/: {sorted(beside)}")
367
 
368
 
@@ -572,304 +547,12 @@ async def check_trials(env: str, jobs: Path) -> dict:
572
  return report
573
 
574
 
575
- def texts(message: dict) -> str:
576
- return "\n".join(part.get("text", "") for part in message.get("content") or []
577
- if isinstance(part, dict))
578
-
579
-
580
- ARRAY = re.compile(r"\[\s*\d{1,2}(?:\s*,\s*\d{1,2})*\s*\]") # one element or more
581
- # a board tool run as a command (Legion's legion-tool CLI, not a path that ends in it), not a file
582
- # or word that merely names the board
583
- BOARD_CALL = re.compile(r"(?<![\w./-])legion-tool\s+message_board\.[a-z_]+")
584
- STATED = ( # digits that read as a number someone holds; bare ids, counts and timestamps don't
585
- re.compile(r"agent-\d{3}[\"']?\s*[:=]\s*[\"']?(\d{1,2})(?![\d.:])"), # "agent-002": 26
586
- re.compile(r"\bnumbers?\b(?:\s+(?:is|are|was|were)|:|=)?\s*[\"']?(\d{1,2})(?![\d.:])",
587
- re.IGNORECASE), # number is 26
588
- )
589
-
590
-
591
- def given_away(text: str, team: dict[str, str]) -> set[int]:
592
- """The team's numbers that `text` holds: as words ("twenty-six"), or as digits where they
593
- read as a held number: an array of the team's integers (a whole or partial answer, e.g.
594
- `[15, 26, 37]`), an agent's number in a mapping or a line (`"agent-002": 26`), or a number
595
- stated as one (`number is 26`, `numbers: 15`)."""
596
- values = Counter(read_words(w) for w in team.values())
597
- out = {read_words(w) for w in holds(text, set(team.values()))}
598
- for array in ARRAY.findall(text):
599
- numbers = Counter(int(x) for x in re.findall(r"\d+", array))
600
- if not numbers - values: # all of them the team's
601
- out |= set(numbers)
602
- for pattern in STATED:
603
- out |= {int(x) for x in pattern.findall(text)} & set(values)
604
- return out
605
-
606
-
607
- def audit_run(run: Path) -> tuple[list[str], dict]:
608
- """(problems, report) for a Legion run of one team (a local run's `.legion/<swarm>-<time>/`):
609
- no prompt Legion gave an agent holds a teammate's number, and its first prompt holds its own;
610
- the first output in which an agent sees a teammate's number is a board read (or a wake-up
611
- that quotes the board), and the first post holding each number is its owner's. A number
612
- counts as words or as digits (given_away)."""
613
- problems = []
614
- spec = json.loads((run / "run.json").read_text())["spec"]
615
- harbor = next(t["harbor"] for t in spec["types"].values() if t.get("harbor"))
616
- selector = harbor["config"]["task"]["selector"] # agent K on slot K
617
- task = selector[0] if isinstance(selector, list) else selector
618
- team = held(task)
619
- numbers = {agent: read_words(word) for agent, word in team.items()}
620
- boards = sorted(run.rglob("resources/message_board/board.jsonl"))
621
- if len(boards) != 1:
622
- problems.append(f"run {run.name}: {len(boards)} board exports")
623
- posts = sorted((json.loads(x)["message"] for b in boards[:1]
624
- for x in b.read_text().splitlines() if x.strip()),
625
- key=lambda m: m["created_at"])
626
- first = {}
627
- for post in posts:
628
- for number in given_away(post["body"], team):
629
- first.setdefault(number, post["sender"]["external_id"])
630
- for number, who in first.items():
631
- if numbers.get(who) != number:
632
- problems.append(f"run {run.name}: {number} was first posted by {who}")
633
- report = {"task": task, "posts": len(posts), "first_posts": first}
634
- for agent, own in team.items():
635
- path = run / "agents" / "_sessions" / f"{agent}.jsonl"
636
- if not path.is_file():
637
- problems.append(f"run {run.name}: no event stream for {agent}")
638
- continue
639
- others = set(numbers.values()) - {numbers[agent]}
640
- seen, calls, prompts, got_own, board_reads = set(), {}, 0, False, 0
641
- for line in path.read_text().splitlines():
642
- event = json.loads(line) if line.strip() else {}
643
- message = event.get("message") or {}
644
- if event.get("type") != "message":
645
- continue
646
- role, text = message.get("role"), texts(message)
647
- if role == "assistant":
648
- for part in message.get("content") or []:
649
- if isinstance(part, dict) and part.get("type") == "toolCall":
650
- arguments = part.get("arguments") or {}
651
- calls[part.get("id")] = str(arguments.get("command") or json.dumps(
652
- arguments))
653
- elif role in ("system", "user"):
654
- if role == "system" or prompts == 0: # what Legion and the task tell the agent
655
- if given := given_away(text, team) & others:
656
- problems.append(f"run {agent}: its {role} prompt holds {sorted(given)}")
657
- got_own |= role == "user" and own in holds(text, {own})
658
- else: # a later prompt may quote the board (a wake-up on a mention)
659
- seen |= given_away(text, team) & others
660
- prompts += role == "user"
661
- elif role == "toolResult":
662
- command = calls.get(message.get("toolCallId"), "")
663
- board_read = bool(BOARD_CALL.search(command))
664
- board_reads += board_read
665
- new = given_away(text, team) & others - seen
666
- if new and not board_read:
667
- problems.append(f"run {agent}: first saw {sorted(new)} in the output of "
668
- f"{command[:120]}")
669
- seen |= new
670
- if not got_own:
671
- problems.append(f"run {agent}: its first prompt doesn't hold its own number")
672
- report[agent] = {"saw": len(seen), "got_own": got_own, "board_reads": board_reads}
673
- return problems, report
674
-
675
-
676
- def check_run(run: Path) -> dict:
677
- problems, report = audit_run(run)
678
- failures.extend(problems)
679
- return report
680
-
681
-
682
- AUDIT_TEAM = "agg-p01-n04"
683
-
684
-
685
- def synthetic_run(root: Path, prompt: str = "", output: str = "",
686
- poster: dict | None = None, command: str = "cat /tmp/notes.json") -> Path:
687
- """A local run directory of AUDIT_TEAM as Legion leaves it, whose agents behave: each posts
688
- its number and reads the board. `prompt` joins agent-001's first prompt, `output` is
689
- the output of a non-board `command` it runs before it reads the board, and `poster` posts a number
690
- in another agent's name first (agent -> number). Each agent's first prompt is its own slot's
691
- instruction."""
692
- team = held(AUDIT_TEAM)
693
- run = root / f"run-{len(list(root.iterdir()))}"
694
- (run / "agents" / "_sessions").mkdir(parents=True)
695
- (run / "run.json").write_text(json.dumps({"spec": {"types": {"agent": {"harbor": {
696
- "config": {"task": {"selector": [f"{AUDIT_TEAM}-s01", f"{AUDIT_TEAM}-s02"]}}}}}}}))
697
- board = run / "agents" / "_harbor" / "_worker" / "resources" / "message_board"
698
- board.mkdir(parents=True)
699
- lines = [f"{who}: my number is {g.words(number)} ({number})"
700
- for who, number in (poster or {}).items()]
701
- lines += [f"{agent}: my number is {word} ({read_words(word)})" for agent, word in team.items()]
702
- senders = [*(poster or {}), *team]
703
- board_lines = [json.dumps({"channel_id": 1, "message": {
704
- "seq": k, "created_at": 1000.0 + k, "body": body, "sender": {"external_id": who}}})
705
- for k, (who, body) in enumerate(zip(senders, lines, strict=True), 1)]
706
- (board / "board.jsonl").write_text("\n".join(board_lines) + "\n")
707
-
708
- def message(role, content, **extra):
709
- return json.dumps({"type": "message", "message": {"role": role, "content": content,
710
- **extra}})
711
-
712
- def call(k, command):
713
- return message("assistant", [{"type": "toolCall", "id": f"c{k}",
714
- "arguments": {"command": command}}])
715
-
716
- def result(k, text):
717
- return message("toolResult", [{"type": "text", "text": text}], toolCallId=f"c{k}")
718
-
719
- for agent in team:
720
- own = HERE / "tasks" / f"{AUDIT_TEAM}-s{agent[-2:]}" / "instruction.md"
721
- events = [message("system", [{"type": "text", "text": "You are Pi."}]),
722
- message("user", [{"type": "text", "text": own.read_text() + (
723
- prompt if agent == "agent-001" else "")}])]
724
- if agent == "agent-001" and output:
725
- events += [call(2, command), result(2, output)]
726
- events += [call(3, "legion-tool message_board.read --json '{}'"),
727
- result(3, json.dumps({"messages": lines}))]
728
- (run / "agents" / "_sessions" / f"{agent}.jsonl").write_text("\n".join(events) + "\n")
729
- return run
730
-
731
-
732
- def check_audit() -> int:
733
- """audit_run on synthetic runs: a clean one passes, ids and timestamps that happen to be
734
- the team's numbers pass, and each leak fails: words, the JSON answer, a one-element array, a
735
- mapping and a stated number, in the first prompt or a non-board output before the board
736
- (a file named after the board is not the board); and a number first posted by an agent that
737
- doesn't hold it. Returns the cases checked."""
738
- team = held(AUDIT_TEAM)
739
- numbers = [read_words(w) for w in team.values()] # agent-001's first
740
- answer = json.dumps(sorted(numbers))
741
- mapping = json.dumps({a: read_words(w) for a, w in team.items()})
742
- noise = json.dumps({"id": numbers[1], "seq": numbers[2], "count": numbers[3],
743
- "created_at": f"2026-11-16T{numbers[2]:02d}:{numbers[3]:02d}:00Z"})
744
- cases = {
745
- "clean": ({}, False),
746
- "ids, counts and a timestamp that hold the numbers": ({"output": noise}, False),
747
- "a teammate's number in words in the first prompt": (
748
- {"prompt": f"\nagent-002 holds {team['agent-002']}."}, True),
749
- "the JSON answer in the first prompt": ({"prompt": f"\nThe answer is {answer}."}, True),
750
- "the JSON answer in a non-board output": ({"output": answer}, True),
751
- "a mapping of agents to numbers in a non-board output": ({"output": mapping}, True),
752
- "a teammate's number stated in digits in a non-board output": (
753
- {"output": f"agent-003's number is {numbers[2]}"}, True),
754
- "a stated number from a file whose name mentions the board": (
755
- {"output": f"agent-002's number is {numbers[1]}",
756
- "command": "cat /tmp/message_board.txt"}, True),
757
- "a teammate's number as a one-element array in the first prompt": (
758
- {"prompt": f"\nagent-002: [{numbers[1]}]"}, True),
759
- "a teammate's number as a one-element array in a non-board output": (
760
- {"output": f"[{numbers[1]}]"}, True),
761
- "a number first posted by an agent that doesn't hold it": (
762
- {"poster": {"agent-001": numbers[1]}}, True),
763
- }
764
- with tempfile.TemporaryDirectory() as d:
765
- for case, (kwargs, leaks) in cases.items():
766
- problems, _ = audit_run(synthetic_run(Path(d), **kwargs))
767
- check(bool(problems) == leaks, f"audit: {case}: {problems or 'no problem found'}")
768
- return len(cases)
769
-
770
-
771
- # ------------------------------------------------------------------ metrics
772
-
773
- # The lines of Legion's experiments/s3-aggregation/spec.yaml that eval/metrics.py reads
774
- RUN_SPEC = """name: ${TEAM:-agg-p01-n04}
775
- naming: consecutive-id
776
- task:
777
- repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation
778
- selector: ${TEAM:-agg-p01-n04}-s*
779
- revision: REVISION
780
- agents:
781
- count: ${N:-4}
782
- """
783
-
784
-
785
- def metrics_module():
786
- import importlib.util
787
-
788
- spec = importlib.util.spec_from_file_location("_s3_metrics", HERE / "eval" / "metrics.py")
789
- module = importlib.util.module_from_spec(spec)
790
- spec.loader.exec_module(module)
791
- return module
792
-
793
-
794
- def slurm_dir(root: Path, team: str, agents: list[str], env_files: dict[str, str]) -> Path:
795
- """A Slurm run's directory as `legion init` and the workers leave it: the spec, the env files
796
- and, per agent in `agents`, one Trial of its own slot of `team`, graded by the task's own
797
- grader (agent-001 answers right, the others wrong)."""
798
- (root / "experiment").mkdir(parents=True)
799
- (root / "experiment" / "spec.yaml").write_text(RUN_SPEC)
800
- for name, text in env_files.items():
801
- (root / name).write_text(text)
802
- for k, agent in enumerate(agents, 1):
803
- task = HERE / "tasks" / f"{team}-s{int(agent[-3:]):02d}"
804
- right = json.loads((task / "tests" / "expected.json").read_text())
805
- reward = grade(task, json.dumps(right if k == 1 else [0]).encode())
806
- trial = root / "results" / "s3" / agent / "trials" / f"s3-{agent}-t1"
807
- (trial / "verifier").mkdir(parents=True)
808
- (trial / "verifier" / "reward.txt").write_text(str(reward))
809
- (trial / "result.json").write_text(json.dumps({
810
- "task_name": f"HuggingFaceSwarms/{task.name}", "trial_name": trial.name,
811
- "started_at": f"2026-11-17T11:38:1{k % 10}+00:00",
812
- "finished_at": "2026-11-17T11:50:04+00:00",
813
- "agent_result": {"n_input_tokens": 1000, "n_cache_tokens": 0, "n_output_tokens": 50},
814
- "verifier_result": {"rewards": {"reward": float(reward)}}}))
815
- return root
816
-
817
-
818
- def check_metrics() -> int:
819
- """eval/metrics.py on Slurm run directories: the spec as the run resolved it (`cluster.env`
820
- then `run.env`, else the defaults) gives the task and the roster; a planned agent without
821
- results, Trials of an unplanned agent and Trials of another task are flagged, never dropped.
822
- Returns the cases checked."""
823
- metrics = metrics_module()
824
- four = [f"agent-{k:03d}" for k in range(1, 5)]
825
- cases = { # name: (team the Trials ran, agents with Trials, env files, task, agents, missing)
826
- "defaults": ("agg-p01-n04", four, {}, "agg-p01-n04", 4, []),
827
- "run.env": ("agg-p02-n02", four[:2],
828
- {"cluster.env": "N=3\nTEAM=agg-p05-n04\n",
829
- "run.env": "#TEAM=agg-p01-n04\nTEAM=agg-p02-n02\nN=2\n"},
830
- "agg-p02-n02", 2, []),
831
- "an agent's results gone": ("agg-p01-n04", four[:3], {}, "agg-p01-n04", 4,
832
- ["reward: agent-004"]),
833
- "run.env gone": ("agg-p02-n02", four[:2], {}, "agg-p01-n04", 4,
834
- [("task: the spec selects 'agg-p01-n04-s*', the Trials ran "
835
- "agg-p02-n02-s01, agg-p02-n02-s02"), "reward: agent-003",
836
- "reward: agent-004"]),
837
- "an unplanned agent": ("agg-p01-n04", four[:3], {"run.env": "N=2\n"}, "agg-p01-n04", 2,
838
- ["agents: Trials of agents the spec didn't plan: agent-003"]),
839
- # inline comments, as Legion's read_env_file reads them: after a quoted value's closing
840
- # quote, and after whitespace in an unquoted one
841
- "quoted values with comments": ("agg-p03-n04", four[:3],
842
- {"run.env": 'TEAM="agg-p03-n04" # group\nN="4" # size\n'},
843
- "agg-p03-n04", 4, ["reward: agent-004"]),
844
- "unquoted values with comments": ("agg-p02-n02", four[:2],
845
- {"cluster.env": "N=3 # size\n",
846
- "run.env": "export TEAM=agg-p02-n02 # group\n"
847
- "N=2\t# size\n"},
848
- "agg-p02-n02", 2, []),
849
- }
850
- with tempfile.TemporaryDirectory() as d:
851
- for case, (team, agents, env_files, task, count, missing) in cases.items():
852
- root = Path(d) / ("run-" + re.sub(r"\W+", "-", case))
853
- r = metrics.row(slurm_dir(root, team, agents, env_files))
854
- check(r["task"] == task and r["agents"] == count and len(r["rewards"]) == count,
855
- f"metrics, {case}: task {r['task']!r}, {r['agents']} agents, not {task!r}, "
856
- f"{count}")
857
- check(sorted(r["missing"]) == sorted([*missing, "board export"]),
858
- f"metrics, {case}: missing {r['missing']}")
859
- expected = {a: 1.0 if a == "agent-001" else 0.0 for a in agents if a in r["rewards"]}
860
- check({a: v for a, v in r["rewards"].items() if v is not None} == expected
861
- and r["success"] is True, f"metrics, {case}: rewards {r['rewards']}")
862
- return len(cases)
863
-
864
-
865
  def main() -> int:
866
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
867
  parser.add_argument("--env", default="hf-sandbox",
868
  help="Harbor environment type or import path for the Trials; none: skip")
869
  parser.add_argument("--jobs-dir", type=Path, default=None,
870
  help="keep the Trials' files here (default: a temporary directory)")
871
- parser.add_argument("--run", type=Path, action="append", default=[],
872
- help="also check a Legion run of a team (a local run's directory)")
873
  args = parser.parse_args()
874
  check_generator()
875
  print(f"1. generator: {len(failures)} failures")
@@ -887,19 +570,6 @@ def main() -> int:
887
  report = asyncio.run(check_trials(args.env, jobs))
888
  print(f"4. no-cheat (Trials on {args.env}, {PROBE_TEAM}): {len(failures) - before} "
889
  f"failures; {json.dumps(report)}")
890
- before = len(failures)
891
- cases = check_audit()
892
- print(f"5. no-cheat (the Legion-run audit on {cases} synthetic runs): "
893
- f"{len(failures) - before} failures")
894
- before = len(failures)
895
- cases = check_metrics()
896
- print(f"6. metrics (eval/metrics.py on {cases} Slurm run directories): "
897
- f"{len(failures) - before} failures")
898
- for run in args.run:
899
- before = len(failures)
900
- report = check_run(run)
901
- print(f"5. no-cheat (Legion run {run.name}): {len(failures) - before} failures; "
902
- f"{json.dumps(report)}")
903
  for failure in failures:
904
  print("FAIL:", failure)
905
  print("all checks passed" if not failures else f"{len(failures)} checks failed")
 
7
  uv run check.py # all of them; the Trials run on HF Sandboxes (HF_TOKEN)
8
  uv run check.py --env docker # the Trials in local docker instead
9
  uv run check.py --env none # skip the Trials
 
10
 
11
  1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed;
12
  another seed gives other problems; 32 problems of 16 integers in 1..99; the English words
 
39
  /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any
40
  answer as right wherever the verifier may start; a sitecustomize in site-packages that
41
  does the same. The verifier scores each 0.
42
+ `--env` takes a Harbor environment type or an import path.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
 
45
  import argparse
 
53
  import subprocess
54
  import sys
55
  import tempfile
 
56
  from pathlib import Path
57
 
58
  HERE = Path(__file__).resolve().parent
 
98
 
99
 
100
  def held(team: str) -> dict[str, str]:
101
+ """A team's slot labels and their private numbers."""
102
  problem, n = team_of(team)
103
  numbers = json.loads((HERE / "problems.json").read_text())["problems"][f"p{problem:02d}"]
104
  return {f"agent-{k:03d}": g.words(x) for k, x in enumerate(numbers[:n], 1)}
 
337
  f"{task.name}: the answer is in {sorted(holders)}")
338
  check(all(len(v) == 1 for v in by_size.values()),
339
  "an instruction (but its number) or task.toml differs between tasks of one team size")
340
+ beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", ".cache", "__pycache__", ".git"}
 
341
  check(not beside, f"folders beside tasks/: {sorted(beside)}")
342
 
343
 
 
547
  return report
548
 
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  def main() -> int:
551
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
552
  parser.add_argument("--env", default="hf-sandbox",
553
  help="Harbor environment type or import path for the Trials; none: skip")
554
  parser.add_argument("--jobs-dir", type=Path, default=None,
555
  help="keep the Trials' files here (default: a temporary directory)")
 
 
556
  args = parser.parse_args()
557
  check_generator()
558
  print(f"1. generator: {len(failures)} failures")
 
570
  report = asyncio.run(check_trials(args.env, jobs))
571
  print(f"4. no-cheat (Trials on {args.env}, {PROBE_TEAM}): {len(failures) - before} "
572
  f"failures; {json.dumps(report)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  for failure in failures:
574
  print("FAIL:", failure)
575
  print("all checks passed" if not failures else f"{len(failures)} checks failed")
eval/metrics.py DELETED
@@ -1,329 +0,0 @@
1
- """One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.py
2
- RUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.
3
-
4
- A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`, docs/local.md), or
5
- a Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where the workers copy what a
6
- run is graded on into `results/`. Under either, each agent's Trials
7
- (`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the board
8
- export (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (one
9
- JSON line; README.md has every field):
10
- - the task and team size, how the run ended, and `success`: any agent's reward is 1;
11
- - per agent: its reward (its latest Trial with a verifier result), tokens and board posts;
12
- - the message graph: an edge from a sender to each teammate it mentions (`@agent-002`; a group
13
- mention such as `@all` names every member) or messages directly (a DM or a private channel of
14
- the two), with in-degree centralization and reciprocity as in the s³ paper's Appendix M. A
15
- post that mentions no one adds no edge;
16
- - `missing`: what the run directory lacks (an agent's reward, the board export) or where its
17
- spec and its Trials disagree, so a row never passes for complete when it is not.
18
-
19
- A local run's `run.json` gives the spec, the agents, their tokens (summed over models), the
20
- cost and how the run ended. A Slurm run has no such bundle: the task and the roster come from
21
- its `experiment/spec.yaml` as the run resolved it (its `${VAR}`s from `cluster.env` and
22
- `run.env`, else their defaults), each agent's tokens from its Trials' results (no reasoning
23
- split), and the run's span from its Trials. Every agent the spec planned has a row entry, so
24
- one without results shows in `missing`; so do Trials of an unplanned agent or of another task
25
- 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):
26
- only those posted within the run's span count. `EXTRAS` takes per-environment metrics (s3-maze:
27
- moves per agent and room overlap, from the move logs its verifier copies next to the reward).
28
- """
29
-
30
- import argparse
31
- import fnmatch
32
- import json
33
- import re
34
- import sys
35
- from collections import Counter
36
- from collections.abc import Callable
37
- from datetime import datetime
38
- from pathlib import Path
39
-
40
- import yaml
41
-
42
- TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning")
43
-
44
-
45
- def load_json(path: Path):
46
- return json.loads(path.read_text(encoding="utf-8"))
47
-
48
-
49
- def epoch(value) -> float:
50
- return float(value) if isinstance(value, int | float) else datetime.fromisoformat(
51
- value).timestamp()
52
-
53
-
54
- def bundle(run_dir: Path) -> dict | None:
55
- """A local run's run.json; None for a Slurm run (its controller's run.json, in the bucket,
56
- holds neither the spec nor the agents)."""
57
- path = run_dir / "run.json"
58
- doc = load_json(path) if path.is_file() else {}
59
- return doc if "spec" in doc and "agents" in doc else None
60
-
61
-
62
- def all_trials(run_dir: Path) -> dict[str, list[Path]]:
63
- """Each agent's Trial directories, oldest first: `<agent>/trials/<swarm>-<agent>-t<N>/`
64
- (a local run's agents/_harbor/, a Slurm run's results/<swarm>/), one per Trial name."""
65
- found: dict[str, dict[str, tuple[int, Path]]] = {}
66
- for trial in run_dir.rglob("trials/*"):
67
- agent = trial.parent.parent.name
68
- m = re.fullmatch(rf"(?:.+-)?{re.escape(agent)}-t(\d+)", trial.name)
69
- if m and trial.is_dir():
70
- found.setdefault(agent, {}).setdefault(trial.name, (int(m[1]), trial))
71
- return {a: [p for _, p in sorted(t.values())] for a, t in sorted(found.items())}
72
-
73
-
74
- def results(trials: list[Path]) -> list[dict]:
75
- return [load_json(t / "result.json") for t in trials if (t / "result.json").is_file()]
76
-
77
-
78
- def reward(trials: list[Path]) -> float | None:
79
- """The reward of the agent's latest Trial that has one."""
80
- for trial in reversed(trials):
81
- result = trial / "result.json"
82
- rewards = ((load_json(result).get("verifier_result") or {}).get("rewards")
83
- if result.is_file() else None)
84
- if rewards and "reward" in rewards:
85
- return float(rewards["reward"])
86
- text = trial / "verifier" / "reward.txt"
87
- if text.is_file() and not text.is_symlink() and text.read_text().strip():
88
- return float(text.read_text().strip())
89
- return None
90
-
91
-
92
- def bundle_tokens(agent: dict) -> dict[str, int]:
93
- usage = dict.fromkeys(TOKEN_FIELDS, 0)
94
- for by_model in (agent.get("tokens") or {}).values():
95
- for key in TOKEN_FIELDS:
96
- usage[key] += int(by_model.get(key) or 0)
97
- return usage
98
-
99
-
100
- def trial_tokens(trials: list[Path]) -> dict[str, int]:
101
- """Harbor's counts: its input includes the cached tokens."""
102
- usage = dict.fromkeys(TOKEN_FIELDS, 0)
103
- for result in results(trials):
104
- agent = result.get("agent_result") or {}
105
- cached = int(agent.get("n_cache_tokens") or 0)
106
- usage["input"] += int(agent.get("n_input_tokens") or 0) - cached
107
- usage["cache_read"] += cached
108
- usage["output"] += int(agent.get("n_output_tokens") or 0)
109
- return usage
110
-
111
-
112
- def board(run_dir: Path, start: float, end: float) -> tuple[list[dict], dict[int, dict], bool]:
113
- """(the run's messages, oldest first, channels by id, whether an export was found)."""
114
- messages, channels, found = {}, {}, False
115
- for export in run_dir.rglob("resources/message_board/board.jsonl"):
116
- found = True
117
- listing = export.with_name("channels.json")
118
- for channel in load_json(listing) if listing.is_file() else []:
119
- channels[channel["id"]] = channel
120
- for line in export.read_text(encoding="utf-8").splitlines():
121
- if line.strip():
122
- record = json.loads(line)
123
- message = record["message"] | {"channel_id": record["channel_id"]}
124
- if start <= epoch(message["created_at"]) <= end:
125
- messages[message["id"]] = message
126
- return sorted(messages.values(), key=lambda m: m["id"]), channels, found
127
-
128
-
129
- def sender(message: dict) -> str | None:
130
- return (message.get("sender") or {}).get("external_id")
131
-
132
-
133
- def edges(messages: list[dict], channels: dict[int, dict], team: list[str]) -> set[tuple]:
134
- """(sender, receiver) for each teammate a message mentions or is sent to directly."""
135
- members = set(team)
136
- out = set()
137
- for message in messages:
138
- source = sender(message)
139
- if source not in members:
140
- continue
141
- targets = {m.get("external_id") for m in message.get("mentions") or []}
142
- channel = channels.get(message["channel_id"]) or {}
143
- if channel.get("kind") in ("dm", "private"):
144
- inside = {m.get("external_id") for m in channel.get("members") or []} & members
145
- if len(inside) == 2 and source in inside: # a DM, or a private channel of the two
146
- targets |= inside
147
- out |= {(source, target) for target in targets & members if target != source}
148
- return out
149
-
150
-
151
- def centralization(graph: set[tuple], team: list[str]) -> float | None:
152
- """Appendix M: sum over agents of (k* - k_j) / (N - 1)^2, k_j agent j's in-degree and k*
153
- the largest: 0 when everyone receives from as many teammates, 1 when one agent receives
154
- from everyone and no one else from anyone. None for a team of one."""
155
- n = len(team)
156
- if n < 2:
157
- return None
158
- degree = Counter(target for _, target in graph)
159
- k = [degree[a] for a in team]
160
- return sum(max(k) - kj for kj in k) / (n - 1) ** 2
161
-
162
-
163
- def reciprocity(graph: set[tuple]) -> float | None:
164
- """Appendix M: the fraction of edges whose reverse edge exists. None without edges."""
165
- return sum((b, a) in graph for a, b in graph) / len(graph) if graph else None
166
-
167
-
168
- # Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields.
169
- # s3-maze adds moves per agent and room overlap, (V - U) / V, from its move logs here.
170
- EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = []
171
-
172
-
173
- def local_run(run: dict) -> dict:
174
- """What a local bundle says about the run."""
175
- harbor = next((t.get("harbor") or {} for t in run["spec"]["types"].values()), {})
176
- task = (harbor.get("config") or {}).get("task") or {}
177
- agents = sorted(run["agents"], key=lambda a: a["name"])
178
- return {"swarm": run.get("swarm"), "task": task, "team": [a["name"] for a in agents],
179
- "start": epoch(run["started_at"]), "end": epoch(run["ended_at"]),
180
- "stop_reason": run.get("stop_reason"), "duration_s": run.get("duration_s"),
181
- "cost_usd": (run.get("totals") or {}).get("cost_usd"),
182
- "tokens": {a["name"]: bundle_tokens(a) for a in agents},
183
- "turns": {a["name"]: a.get("turns_completed") for a in agents}}
184
-
185
-
186
- PLACEHOLDER = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)(?::-([^}]*))?\}")
187
-
188
-
189
- def env_values(path: Path) -> dict[str, str]:
190
- """NAME=value lines as Legion reads them (legion.specrender.read_env_file): an `export `
191
- prefix and `#` comment lines allowed; a quoted value ends at its closing quote (what follows
192
- is a comment), and an unquoted one at whitespace followed by `#`. A line that isn't
193
- NAME=value is skipped, where Legion refuses the file."""
194
- values = {}
195
- for line in path.read_text(encoding="utf-8").splitlines():
196
- line = line.strip()
197
- if not line or line.startswith("#"):
198
- continue
199
- name, sep, raw = line.removeprefix("export ").partition("=")
200
- name, value = name.strip(), raw.strip()
201
- if not sep or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
202
- continue
203
- if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0:
204
- value = value[1:end]
205
- else:
206
- value = re.split(r"\s+#", raw, maxsplit=1)[0].strip()
207
- values[name] = value
208
- return values
209
-
210
-
211
- def run_values(run_dir: Path) -> dict[str, str]:
212
- """The run's `cluster.env` then `run.env` (later wins), as Legion reads them: what fills the
213
- spec's `${VAR}`s."""
214
- values = {}
215
- for name in ("cluster.env", "run.env"):
216
- if (run_dir / name).is_file():
217
- values |= env_values(run_dir / name)
218
- return values
219
-
220
-
221
- def expand(text: str, values: dict[str, str]) -> str:
222
- """`${VAR}` and `${VAR:-default}` in the spec's text, as Legion fills them (empty = unset)."""
223
- return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]),
224
- text)
225
-
226
-
227
- def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict:
228
- """What a Slurm run's directory says: its spec as the run resolved it (`legion init`'s copy
229
- of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their
230
- defaults) and the Trials the workers kept. The spec gives the task and the roster: every
231
- agent it planned is in the row, so one whose results are missing is flagged, not dropped.
232
- `problems` says where the spec and the Trials disagree (e.g. a `run.env` that is gone, its
233
- values replaced by the defaults)."""
234
- path = run_dir / "experiment" / "spec.yaml"
235
- spec = (yaml.safe_load(expand(path.read_text(), run_values(run_dir)))
236
- if path.is_file() else None) or {}
237
- problems = [] if spec else ["spec: no experiment/spec.yaml"]
238
- agents = spec.get("agents") or {}
239
- count = agents.get("count") if type(agents.get("count")) is int else None
240
- if spec and count is None:
241
- problems.append(f"spec: agents.count is {agents.get('count')!r}, not a number")
242
- if spec.get("naming") == "consecutive-id" and count is not None:
243
- team = [f"agent-{k:03d}" for k in range(1, count + 1)]
244
- else:
245
- team = list(trials)
246
- if count is not None and len(team) < count:
247
- problems.append(f"agents: {len(team)} of the {count} planned have Trials")
248
- if outside := sorted(set(trials) - set(team)):
249
- problems.append(f"agents: Trials of agents the spec didn't plan: {', '.join(outside)}")
250
- times = [(epoch(r["started_at"]), epoch(r["finished_at"]))
251
- for ts in trials.values() for r in results(ts)
252
- if r.get("started_at") and r.get("finished_at")]
253
- start, end = (min(t[0] for t in times), max(t[1] for t in times)) if times else (0, 0)
254
- ran = sorted({r["task_name"].split("/")[-1] for ts in trials.values() for r in results(ts)
255
- if r.get("task_name")})
256
- task = spec.get("task") or {"selector": ran[0] if len(ran) == 1 else None}
257
- selector = task.get("selector") or ""
258
- if odd := [name for name in ran if not fnmatch.fnmatchcase(name, selector)]:
259
- problems.append(f"task: the spec selects {selector!r}, the Trials ran {', '.join(odd)}")
260
- swarm = next((t.name.removesuffix(f"-{a}-t{t.name.rsplit('-t', 1)[1]}")
261
- for a, ts in trials.items() for t in ts), spec.get("name"))
262
- return {"swarm": swarm, "task": task, "team": team, "start": start, "end": end,
263
- "stop_reason": None, "duration_s": round(end - start, 1) if times else None,
264
- "cost_usd": None, "tokens": {a: trial_tokens(trials.get(a, [])) for a in team},
265
- "turns": dict.fromkeys(team), "problems": problems}
266
-
267
-
268
- def row(run_dir: Path) -> dict:
269
- trials = all_trials(run_dir)
270
- run = bundle(run_dir)
271
- info = local_run(run) if run is not None else slurm_run(run_dir, trials)
272
- team = info["team"]
273
- messages, channels, exported = board(run_dir, info["start"], info["end"])
274
- posts = Counter(sender(m) for m in messages)
275
- graph = edges(messages, channels, team)
276
- per_agent, missing = {}, list(info.get("problems", []))
277
- for name in team:
278
- value = reward(trials.get(name, []))
279
- if value is None:
280
- missing.append(f"reward: {name}")
281
- per_agent[name] = {"reward": value, "tokens": info["tokens"][name],
282
- "posts": posts[name], "turns": info["turns"][name]}
283
- if not exported:
284
- missing.append("board export")
285
- rewards = [a["reward"] for a in per_agent.values() if a["reward"] is not None]
286
- task = info["task"]
287
- out = {
288
- "run": run_dir.name,
289
- "swarm": info["swarm"],
290
- "task": re.sub(r"-s\*$", "", task.get("selector") or "") or None, # a team's slots
291
- "dataset": task.get("repo"),
292
- "revision": task.get("revision"),
293
- "agents": len(team),
294
- "stop_reason": info["stop_reason"],
295
- "duration_s": info["duration_s"],
296
- "success": any(r == 1 for r in rewards) if rewards else None,
297
- "rewards": {name: a["reward"] for name, a in per_agent.items()},
298
- "tokens": {key: sum(a["tokens"][key] for a in per_agent.values())
299
- for key in TOKEN_FIELDS},
300
- "cost_usd": info["cost_usd"],
301
- "posts": sum(posts[name] for name in team),
302
- "other_posts": sum(n for who, n in posts.items() if who not in team),
303
- "per_agent": per_agent,
304
- "edges": sorted([a, b] for a, b in graph),
305
- "centralization": centralization(graph, team),
306
- "reciprocity": reciprocity(graph),
307
- "missing": missing,
308
- }
309
- for extra in EXTRAS:
310
- out |= extra(run_dir, team, trials)
311
- return out
312
-
313
-
314
- def main(argv=None) -> int:
315
- parser = argparse.ArgumentParser(description="One row per team (JSON lines) from s³ runs.")
316
- parser.add_argument("run_dirs", nargs="+", type=Path)
317
- parser.add_argument("--out", type=Path, help="append the rows here (default: stdout)")
318
- args = parser.parse_args(argv)
319
- rows = [json.dumps(row(d)) for d in args.run_dirs]
320
- if args.out:
321
- with args.out.open("a", encoding="utf-8") as f:
322
- f.write("".join(r + "\n" for r in rows))
323
- else:
324
- print("\n".join(rows))
325
- return 0
326
-
327
-
328
- if __name__ == "__main__":
329
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
generate.py CHANGED
@@ -5,9 +5,8 @@ Writes `problems.json` and `tasks/` next to this file, replacing what is there:
5
  - per problem and team size N in SIZES, a team `agg-pPP-nNN` that holds the problem's first N
6
  numbers, and one task per slot of it, `agg-pPP-nNN-sKK` (K = 1..N, zero-padded so that name
7
  order is slot order): its instruction states that slot's number, and only that one. Every
8
- slot of a team shares the grader and the answer. Legion runs a team with the selector
9
- `agg-pPP-nNN-s*`, `agents.count: N` and `naming: consecutive-id`: agent K gets slot K's task,
10
- and no other agent's.
11
 
12
  check.py checks that this reproduces the committed files byte for byte.
13
  """
@@ -52,7 +51,7 @@ def team_name(problem: int, n: int) -> str:
52
 
53
 
54
  def task_name(problem: int, n: int, slot: int) -> str:
55
- """Slot `slot` (from 1) of the team: Legion's agent `agent-00K` (naming: consecutive-id)."""
56
  return f"{team_name(problem, n)}-s{slot:02d}"
57
 
58
 
 
5
  - per problem and team size N in SIZES, a team `agg-pPP-nNN` that holds the problem's first N
6
  numbers, and one task per slot of it, `agg-pPP-nNN-sKK` (K = 1..N, zero-padded so that name
7
  order is slot order): its instruction states that slot's number, and only that one. Every
8
+ slot of a team shares the grader and the answer. A team runner assigns each participant
9
+ its own slot's task.
 
10
 
11
  check.py checks that this reproduces the committed files byte for byte.
12
  """
 
51
 
52
 
53
  def task_name(problem: int, n: int, slot: int) -> str:
54
+ """Task for slot K of the team, with the first slot numbered 1."""
55
  return f"{team_name(problem, n)}-s{slot:02d}"
56
 
57
 
legion/spec.template.yaml DELETED
@@ -1,72 +0,0 @@
1
- # s3-aggregation: N agents each hold a private number and list the team's numbers in ascending
2
- # order. The template of every team's spec: team.py fills in the team (TEAM) and this dataset's
3
- # revision (REVISION), and merges one of `where:` into it.
4
- # Don't launch this file; README.md.
5
- name: ${RUN_NAME:-TEAM} # team.py: the task's name
6
- model: Qwen/Qwen3.8-27B
7
- naming: consecutive-id # agent-00K runs slot K's task (the K-th by name)
8
- inference:
9
- hf_router:
10
- provider: deepinfra
11
- api_key_env: HF_INFERENCE_TOKEN # inference only: never the workers' HF_TOKEN
12
- task:
13
- repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation # private for now
14
- selector: TEAM-s* # one task per agent: agg-pPP-nNN-s01 ...
15
- revision: REVISION # team.py: --revision, default the Hub's head
16
- agents:
17
- count: 1 # team.py: N
18
- resources:
19
- # The board rules: identical for every eval run, since they shape how agents talk.
20
- # Enforced on docker and podman (each agent's rule proxy); on HF Sandboxes there is no proxy,
21
- # so they are not enforced and each Trial records a message_board.warning event.
22
- message_board:
23
- channels: [general]
24
- wake: [mention, thread]
25
- rules:
26
- max_len: 1000
27
- min_post_gap: 5s
28
- max_posts: 40
29
- max_channels: 1 # #general only: no new channels
30
- workers:
31
- agents_per_worker: 1 # team.py: N, the whole team on one worker and board
32
- turn_timeout: 10m
33
- loop:
34
- prompt: Continue the task until it is complete, then stop.
35
- every: turn_end
36
- while:
37
- until: 15m
38
- max_rounds: 4
39
- limits:
40
- run_timeout_seconds: 1200
41
- agent_max_turns: 60
42
-
43
- # Where the team runs: team.py merges one of these into the spec (--where).
44
- where:
45
- # Local docker, with the controller, the one worker and the board on this machine.
46
- docker:
47
- environment:
48
- backend: docker
49
- # HF Sandboxes (cpu-basic), with the controller and the one worker on this machine and the
50
- # board on a Space. Give each team a new Space and delete it afterwards: the instruction has no
51
- # run tag, so an earlier team's posts on a reused board would read as this team's.
52
- sandbox:
53
- namespace: ${SANDBOX_NAMESPACE:-} # bills the sandboxes; unset: HF_TOKEN's account
54
- environment:
55
- backend: hf-sandbox
56
- resources:
57
- message_board:
58
- space_id: ${BOARD_SPACE:-s3-TEAM} # bare name: HF_TOKEN's account
59
- private: false # a private Space's gate needs HF_TOKEN in every sandbox
60
- # The HF cluster: a Slurm worker running the team in rootless podman, with a local board on
61
- # that worker (a new one each run). Results reach <run dir>/results/ (Legion's docs/slurm.md).
62
- cluster:
63
- namespace: ${NAMESPACE}
64
- bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name>
65
- compute:
66
- kind: slurm
67
- partition: ${SLURM_PARTITION:-} # the cluster profile's
68
- cpus: ${WORKER_CPUS:-16}
69
- mem: ${WORKER_MEM:-30G} # at most 2000 MB per CPU on hopper-cpu
70
- time: '3:00:00'
71
- environment:
72
- backend: podman
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/README.md DELETED
@@ -1,86 +0,0 @@
1
- # s3-aggregation scaling sweep
2
-
3
- What the s³ paper's Figure 5 (information aggregation: success against swarm size) looks like
4
- with Legion: every problem of this dataset at N = 1, 2, 4, 8 and 16 agents, each team its own
5
- Legion run on the HF cluster. The results so far (`Qwen/Qwen3.5-27B` and `Qwen/Qwen3.5-2B`) are
6
- in huggingface/legion#120's comments and on Legion's `s3-aggregation-results` branch, and the raw
7
- runs in the private `HuggingFaceSwarms/s3-aggregation-results`.
8
-
9
- | File | |
10
- | --- | --- |
11
- | `serve-vllm.sbatch` | the model server: vLLM with `$MODEL` (default `Qwen/Qwen3.5-27B`) on one B200 GPU (Legion's docs/open-models.md), thinking off for every request (the Qwen3.5 templates' defaults differ: the 27B's thinks, the 2B's doesn't) |
12
- | `sweep.py` | runs the grid, one command, resumable: a row per team in `<root>/rows.jsonl` |
13
- | `plot.py` | `scaling.png` (Figure 5's style), `teams.csv`, `by_n.csv` and `by_n.md` from the rows, one series per model |
14
- | `setaside.py` | why each attempt in `rows-discarded.jsonl` didn't count, and how many teams needed a rerun |
15
- | `failures.py` | per agent: the answer the verifier saw (no answer, malformed, wrong count, wrong numbers, right) and, from the state bucket's event streams, its tool calls, failed calls and posts |
16
- | `waits.py` | how long each kept team's worker queued |
17
- | `registries.conf` | the workers' podman pulls Docker Hub images through `mirror.gcr.io` |
18
-
19
- ## Run it
20
-
21
- From Legion's checkout at or after `0401df9` (with its Slurm results, huggingface/legion#122, so
22
- each Trial's grading reaches the run directory, and huggingface/legion#129, so the teams' agents
23
- spread over the servers), with this dataset downloaded on the shared disk at the revision
24
- the teams pin (`DS` below), since the workers read `registries.conf` from it. Two model servers,
25
- one GPU each: one B200 is saturated by about 50 agents at a time (the 27B grid needs about 70M
26
- prompt and 2M generated tokens), and a job's time limit is 3 hours.
27
-
28
- ```sh
29
- hf download HuggingFaceSwarms/s3-aggregation --repo-type dataset --revision <sha> --local-dir $DS
30
- sbatch -p hopper-b200 -o .legion/s3-sweep/vllm-%j.log $DS/legion/sweep/serve-vllm.sbatch
31
- sbatch -p hopper-b200 --export=ALL,PORT=8001 -o .legion/s3-sweep/vllm-%j.log $DS/legion/sweep/serve-vllm.sbatch
32
- # each log ends with: serving Qwen/Qwen3.5-27B at http://<node address>:<port>/v1
33
- uv run python $DS/legion/sweep/sweep.py --urls http://<node 1>:8000/v1,http://<node 2>:8001/v1 \
34
- --revision <sha> --parallel 12 --bucket <you>/s3-aggregation-grid \
35
- --dataset HuggingFaceSwarms/s3-aggregation-results --prefix grid
36
- scancel -n s3-sweep-vllm
37
- ```
38
-
39
- The 2B grid is the same with `--export=ALL,MODEL=Qwen/Qwen3.5-2B` for the server, and
40
- `--model Qwen/Qwen3.5-2B --tag q2b-` and its own bucket and `--prefix` for the driver. Its
41
- agents run far longer, so more teams are in flight at once: `--max-worker-cpus 8` keeps their
42
- workers small enough to be scheduled, except at N = 16, whose 2B teams need 16 CPUs (30 GB) and
43
- run from a second driver (`--agents 16`) on the same root. Then plot both:
44
- `plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>`.
45
-
46
- Each team is team.py's cluster spec (`--where cluster`) with the model on all the servers' URLs
47
- (each agent calls one: Legion at or after `0401df9`, huggingface/legion#129, picks it from the run
48
- and the agent's name, so concurrent teams' agents spread over the servers; with an older Legion
49
- every team's `agent-001` lands on the same server): `compute: slurm`, one worker on hopper-cpu
50
- running the team in rootless podman with a local board, sized to the team (a CPU per agent, at
51
- least 4). The board rules, loop and limits are the template's at every N. sweep.py inits and
52
- launches a team, waits until its loop is done and its agents are idle, releases it
53
- (`legion stop --release`: each Trial is graded as the worker drains, and the results land in the
54
- run directory), and appends metrics.py's row with the wall time. The run state goes to a
55
- private bucket (a new one per grid: a swarm's name is used once in a bucket), the run
56
- directories (spec, results, logs; never `run.env`) to the private dataset, and plot.py runs at
57
- the end.
58
-
59
- **A run counts only when it is complete**: one worker incarnation (until legion#121 is fixed, a
60
- relaunched or preempted worker overwrites results), its controller kept, every agent's reward
61
- and the board export, and its worker started within 2 min of the launch (the loop's 15 minutes
62
- and the driver's 40 count from the launch, also for a team a restarted driver adopts). hopper-cpu is spot capacity, so reclaims take workers and controllers
63
- mid-run, and a missing reward means the verifier never ran. A run that doesn't count goes to
64
- `rows-discarded.jsonl` and the team runs again as `<task>-rK` (up to 5 times); its row records
65
- the reruns.
66
-
67
- **Resuming.** The same command resumes: a team with a row is skipped, a team a stopped driver
68
- launched is adopted (waited for, released and scored, or scored from what it left when its
69
- controller is gone), and one that never launched runs again. Stopping the driver to add a server
70
- is safe: in-flight teams keep running and are adopted.
71
-
72
- ## How it differs from the paper's Figure 5
73
-
74
- | | s³ (Figure 5, top row) | here |
75
- | --- | --- | --- |
76
- | Agents | Qwen3-0.6B trained with RL at N = 4, and its controls | `Qwen/Qwen3.5-27B` and `Qwen/Qwen3.5-2B`, not trained: one prompted condition each |
77
- | Harness | their asynchronous harness: `message(to, text)` and `read_messages()`, notifications that interrupt generation, idle until a message arrives | Pi in a container per agent, with legion's board tools (`legion-tool message_board.*`) through its shell; a shared `#general` channel, mentions and a long-poll `wait`; legion's loop prompts again at each turn's end |
78
- | Messages | to one teammate or broadcast | posts on `#general`, the only channel (`max_channels: 1`), which every agent reads |
79
- | Private number | in the agent's prompt | in its own task's instruction (one task per slot) |
80
- | Names | sampled from `agent_1`..`agent_64`, teammates in shuffled order | `agent-001`..`agent-00N`, in order |
81
- | Budget | 8,192 work tokens + 1,024 for the answer per agent; reward reduced by tokens used | no token allowance: 60 model calls per prompt, 4 loop rounds, 15 min, 10 min per turn, 262,144-token window |
82
- | Answer | `####` and a JSON array, from any agent active at the end | `/app/answer.json` per agent, graded after the run; the team succeeds if any agent's is right |
83
- | Instruction | Appendix G's, with an example message and the token-cost rule | adapted from Appendix G for the board, with no example message and no token cost |
84
- | Problems | 32 held-out problems x 6 seeds; N = 1, 2, 4, 6, 8, 12, 16 | 32 problems (our seed, the same recipe: 16 numbers in 1..99, the first N) x 1 attempt; N = 1, 2, 4, 8, 16 |
85
- | Intervals | mean ± SE across six seeds | 95% Wilson intervals across problems |
86
- | Right panel | token efficiency (needs the allowance) | four cost panels: input and generated tokens per team (as the paper's Figure 10), wall time per team and board posts per agent |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/failures.py DELETED
@@ -1,134 +0,0 @@
1
- """How the teams of a grid fail: `uv run legion/sweep/failures.py <root>
2
- [--sessions <dir>]`, writing `<root>/failures.md` and `<root>/agents.csv`.
3
-
4
- For each agent of each team in `<root>/rows.jsonl`: the answer the verifier saw (none, malformed,
5
- the wrong count, the wrong numbers, unsorted, or right), against the problem's numbers
6
- (this checkout's problems.json), and, from its event stream (`--sessions`:
7
- a copy of the state bucket, `<dir>/<run>/agent/<agent>/sessions/<agent>.jsonl`, e.g. from
8
- `hf buckets sync hf://buckets/<bucket> <dir> --include "*/sessions/agent-*.jsonl"`), what it did: board posts
9
- through `legion-tool`, tool calls that failed, and whether it ever reached `legion-tool` at all
10
- (a small model may call util-linux's `flock` instead). A team fails when no agent's answer is
11
- right; the summary counts the failed teams' agents by answer and behaviour.
12
- """
13
-
14
- import argparse
15
- import csv
16
- import json
17
- import re
18
- from collections import Counter
19
- from pathlib import Path
20
-
21
- PROBLEMS = Path(__file__).resolve().parents[2] / "problems.json"
22
-
23
-
24
- def problems() -> dict[str, list[int]]:
25
- return json.loads(PROBLEMS.read_text())["problems"]
26
-
27
-
28
- def answer_kind(text: str | None, team: list[int]) -> str:
29
- if text is None:
30
- return "no answer"
31
- try:
32
- answer = json.loads(text)
33
- except ValueError:
34
- return "malformed"
35
- if not isinstance(answer, list) or not all(type(x) is int for x in answer):
36
- return "malformed"
37
- if answer == sorted(team):
38
- return "right"
39
- if len(answer) != len(team):
40
- return "wrong count"
41
- if sorted(answer) == sorted(team):
42
- return "unsorted"
43
- return "wrong numbers"
44
-
45
-
46
- def latest_answer(run_dir: Path, agent: str) -> str | None:
47
- trials = sorted(run_dir.rglob(f"{agent}/trials/*-{agent}-t*"),
48
- key=lambda p: int(re.search(r"-t(\d+)$", p.name)[1]))
49
- for trial in reversed(trials):
50
- path = trial / "verifier" / "answer.json"
51
- if path.is_file():
52
- return path.read_text(errors="replace")
53
- if (trial / "verifier" / "reward.txt").is_file():
54
- return None # graded, and no answer file
55
- return None
56
-
57
-
58
- def behaviour(path: Path | None) -> dict:
59
- """What an agent did, from its event stream: tool calls, failed ones, board posts."""
60
- out = {"tool_calls": 0, "tool_errors": 0, "posts": 0, "used_legion_tool": False,
61
- "called_util_flock": False, "session": path is not None and path.is_file()}
62
- if not out["session"]:
63
- return out
64
- calls = {}
65
- for line in path.read_text(errors="replace").splitlines():
66
- event = json.loads(line)
67
- message = event.get("message") or {}
68
- if event.get("type") != "message":
69
- continue
70
- if message.get("role") == "assistant":
71
- for part in message.get("content") or []:
72
- if isinstance(part, dict) and part.get("type") == "toolCall":
73
- out["tool_calls"] += 1
74
- command = json.dumps(part.get("arguments") or {})
75
- calls[part.get("id")] = command
76
- out["used_legion_tool"] |= "legion-tool" in command
77
- out["called_util_flock"] |= bool(re.search(r"(^|[^-\w])flock (?!-tool)",
78
- command.replace("\\\\n", " ")))
79
- elif message.get("role") == "toolResult":
80
- text = " ".join(p.get("text", "") for p in message.get("content") or []
81
- if isinstance(p, dict))
82
- failed = message.get("isError") or '"error"' in text
83
- out["tool_errors"] += bool(failed)
84
- command = calls.get(message.get("toolCallId"), "")
85
- if "message_board.post" in command and not failed:
86
- out["posts"] += 1
87
- return out
88
-
89
-
90
- def main(argv=None) -> int:
91
- parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
92
- parser.add_argument("root", type=Path)
93
- parser.add_argument("--sessions", type=Path, help="a copy of the state bucket")
94
- args = parser.parse_args(argv)
95
- numbers = problems()
96
- rows = [json.loads(x) for x in (args.root / "rows.jsonl").read_text().splitlines()]
97
- agents = []
98
- for r in rows:
99
- team = numbers[f"p{r['problem']:02d}"][:r["agents"]]
100
- run_dir = args.root / "runs" / r["run"]
101
- for name in sorted(r["rewards"]):
102
- session = (args.sessions / r["run"] / "agent" / name / "sessions" / f"{name}.jsonl"
103
- if args.sessions else None)
104
- agents.append({"run": r["run"], "task": r["task"], "agents": r["agents"],
105
- "team_success": bool(r["success"]), "agent": name,
106
- "reward": r["rewards"][name],
107
- "answer": answer_kind(latest_answer(run_dir, name), team),
108
- **behaviour(session)})
109
- with (args.root / "agents.csv").open("w", newline="") as f:
110
- writer = csv.DictWriter(f, fieldnames=list(agents[0]))
111
- writer.writeheader()
112
- writer.writerows(agents)
113
- failed = [a for a in agents if not a["team_success"]]
114
- by_n = Counter(r["agents"] for r in rows if not r["success"])
115
- per_n = ", ".join(f"N={n}: {c}" for n, c in sorted(by_n.items()))
116
- lines = [f"Teams: {len(rows)}, failed: {sum(by_n.values())} ({per_n})", "",
117
- "Agents of failed teams, by the answer the verifier saw:", ""]
118
- lines += [f"- {k}: {c}" for k, c in Counter(a["answer"] for a in failed).most_common()]
119
- seen = [a for a in failed if a["session"]]
120
- if seen:
121
- errors, calls = sum(a["tool_errors"] for a in seen), sum(a["tool_calls"] for a in seen)
122
- erring = sum(a["tool_errors"] > 0 for a in seen)
123
- lines += ["", f"Their behaviour ({len(seen)} with an event stream):", "",
124
- f"- never posted on the board: {sum(a['posts'] == 0 for a in seen)}",
125
- f"- never reached legion-tool: {sum(not a['used_legion_tool'] for a in seen)}",
126
- f"- called util-linux `flock` instead: {sum(a['called_util_flock'] for a in seen)}",
127
- f"- had failed tool calls: {erring} ({errors} of {calls} calls)"]
128
- (args.root / "failures.md").write_text("\n".join(lines) + "\n")
129
- print("\n".join(lines))
130
- return 0
131
-
132
-
133
- if __name__ == "__main__":
134
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/plot.py DELETED
@@ -1,224 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.12"
3
- # dependencies = ["matplotlib>=3.8"]
4
- # ///
5
- """The sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`, one per team):
6
-
7
- uv run legion/sweep/plot.py <root> # one grid, into <root>
8
- uv run legion/sweep/plot.py --series Qwen3.5-27B=<root> \
9
- --series Qwen3.5-2B=<root> --out <dir> # one series per model
10
-
11
- - `scaling.png`, five panels against the swarm size N: success (%) in the style of the s³
12
- paper's Figure 5 (information aggregation), with 95% Wilson intervals over the problems; then
13
- what the team costs: input and generated tokens per team and board posts per agent (means
14
- with 95% intervals), and wall time per team (median and interquartile range: a team in flight
15
- across a driver restart waited for it). The paper's right panel is token efficiency, which
16
- needs a token allowance our agents don't have; its Figure 10 shows tokens per team;
17
- - `teams.csv`: one row per team; `by_n.csv` and `by_n.md`: per N, the teams, success rate and
18
- interval, mean reward, tokens per team (input, cached when the server reports it, output),
19
- board posts per agent and the median wall time.
20
- """
21
-
22
- import argparse
23
- import csv
24
- import json
25
- import math
26
- import statistics
27
- import sys
28
- from pathlib import Path
29
-
30
- SURFACE, INK, INK_2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
31
- SERIES = ["#2a78d6", "#eb6834", "#1baf7a"] # the reference palette's first slots, in order
32
-
33
-
34
- def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
35
- if n == 0:
36
- return (math.nan, math.nan)
37
- p = k / n
38
- centre = (p + z * z / (2 * n)) / (1 + z * z / n)
39
- half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
40
- return (max(0.0, centre - half), min(1.0, centre + half))
41
-
42
-
43
- def mean_ci(values: list[float]) -> tuple[float, float, float]:
44
- if not values:
45
- return (math.nan, math.nan, math.nan)
46
- m = statistics.fmean(values)
47
- half = 1.96 * statistics.stdev(values) / math.sqrt(len(values)) if len(values) > 1 else 0.0
48
- return (m, m - half, m + half)
49
-
50
-
51
- def team_row(r: dict) -> dict:
52
- rewards = [v for v in r["rewards"].values() if v is not None]
53
- t = r["tokens"]
54
- return {"task": r["task"], "problem": r.get("problem"), "agents": r["agents"],
55
- "success": int(bool(r["success"])), "mean_reward": statistics.fmean(rewards)
56
- if rewards else None, "input_uncached": t["input"], "cached": t["cache_read"],
57
- "output": t["output"], "posts": r["posts"],
58
- "posts_per_agent": r["posts"] / r["agents"], "wall_s": r.get("wall_s"),
59
- "duration_s": r["duration_s"], "outcome": r.get("outcome"),
60
- "reruns": r.get("reruns", 0), "incarnations": r.get("incarnations"),
61
- "missing": ";".join(r["missing"])}
62
-
63
-
64
- def by_n(teams: list[dict]) -> list[dict]:
65
- out = []
66
- for n in sorted({t["agents"] for t in teams}):
67
- group = [t for t in teams if t["agents"] == n]
68
- k = sum(t["success"] for t in group)
69
- low, high = wilson(k, len(group))
70
- rewards = [t["mean_reward"] for t in group if t["mean_reward"] is not None]
71
- out.append({
72
- "agents": n, "teams": len(group), "successes": k,
73
- "success_rate": k / len(group), "ci_low": low, "ci_high": high,
74
- "mean_reward": statistics.fmean(rewards) if rewards else math.nan,
75
- "input_uncached_per_team": statistics.fmean(t["input_uncached"] for t in group),
76
- "cached_per_team": statistics.fmean(t["cached"] for t in group),
77
- "output_per_team": statistics.fmean(t["output"] for t in group),
78
- "posts_per_agent": statistics.fmean(t["posts_per_agent"] for t in group),
79
- "wall_s": statistics.median(t["wall_s"] for t in group if t["wall_s"] is not None),
80
- "incomplete": sum(bool(t["missing"]) for t in group),
81
- "reruns": sum(t["reruns"] for t in group)})
82
- return out
83
-
84
-
85
- def write_csv(path: Path, rows: list[dict]) -> None:
86
- with path.open("w", newline="") as f:
87
- writer = csv.DictWriter(f, fieldnames=list(rows[0]))
88
- writer.writeheader()
89
- writer.writerows(rows)
90
-
91
-
92
- def table(series: list[tuple[str, list[dict], list[dict]]]) -> str:
93
- # a server that reports no cache hits (vLLM by default) gets no cached column
94
- cached = any(s["cached_per_team"] for _, _, summary in series for s in summary)
95
- tokens = "input / cached / output" if cached else "input / output"
96
- head = (f"| model | N | teams | success | 95% CI | mean reward | {tokens} tokens per team "
97
- "| posts per agent | median wall time |")
98
- lines = [head, "|---|---|---|---|---|---|---|---|---|"]
99
- for model, _, summary in series:
100
- lines += [row(model, s, cached) for s in summary]
101
- return "\n".join(lines) + "\n"
102
-
103
-
104
- def row(model: str, s: dict, cached: bool) -> str:
105
- tokens = (f"{s['input_uncached_per_team'] / 1e3:.0f}k / "
106
- + (f"{s['cached_per_team'] / 1e3:.0f}k / " if cached else "")
107
- + f"{s['output_per_team'] / 1e3:.1f}k")
108
- return (f"| {model} | {s['agents']} | {s['teams']} | {s['successes']}/{s['teams']} "
109
- f"({100 * s['success_rate']:.0f}%) | {100 * s['ci_low']:.0f}-{100 * s['ci_high']:.0f}% "
110
- f"| {s['mean_reward']:.2f} | {tokens} | {s['posts_per_agent']:.1f} "
111
- f"| {s['wall_s'] / 60:.1f} min |")
112
-
113
-
114
- def quartiles(values: list[float]) -> tuple[float, float, float]:
115
- q = statistics.quantiles(values, n=4) if len(values) > 1 else [values[0]] * 3
116
- return (statistics.median(values), q[0], q[2])
117
-
118
-
119
- def panels(teams: list[dict], summary: list[dict]) -> list[tuple]:
120
- """(label, [(middle, low, high) per N], y limits or "log") for each panel: tokens on a log
121
- scale, since two models' teams can differ by more than an order of magnitude."""
122
- ns = [s["agents"] for s in summary]
123
- by_n = {n: [t for t in teams if t["agents"] == n] for n in ns}
124
- return [
125
- ("Success (%)", [(100 * s["success_rate"], 100 * s["ci_low"], 100 * s["ci_high"])
126
- for s in summary], (0, 105)),
127
- ("Input tokens per team",
128
- [mean_ci([t["input_uncached"] + t["cached"] for t in by_n[n]]) for n in ns], "log"),
129
- ("Generated tokens per team", [mean_ci([t["output"] for t in by_n[n]]) for n in ns],
130
- "log"),
131
- ("Wall time per team (min)",
132
- [tuple(v / 60 for v in quartiles([t["wall_s"] for t in by_n[n] if t["wall_s"]]))
133
- for n in ns], None),
134
- ("Board posts per agent", [mean_ci([t["posts_per_agent"] for t in by_n[n]]) for n in ns],
135
- None),
136
- ]
137
-
138
-
139
- def tokens(value: float, _=None) -> str:
140
- """A log axis tick as a token count: 100, 10k, 1M."""
141
- for size, unit in ((1e6, "M"), (1e3, "k")):
142
- if value >= size:
143
- return f"{value / size:g}{unit}"
144
- return f"{value:g}"
145
-
146
-
147
- def figure(path: Path, series: list[tuple[str, list[dict], list[dict]]], title: str) -> None:
148
- import matplotlib
149
-
150
- matplotlib.use("Agg")
151
- import matplotlib.pyplot as plt
152
- from matplotlib.ticker import FuncFormatter
153
-
154
- plt.rcParams.update({"font.size": 10, "axes.edgecolor": GRID, "axes.labelcolor": INK_2,
155
- "xtick.color": INK_2, "ytick.color": INK_2, "text.color": INK})
156
- fig, axes = plt.subplots(1, 5, figsize=(17, 3.9), facecolor=SURFACE)
157
- for k, (model, teams, summary) in enumerate(series):
158
- ns = [s["agents"] for s in summary]
159
- offset = (k - (len(series) - 1) / 2) * 0.18 # side by side, so the bars don't hide
160
- for ax, (label, points, scale) in zip(axes, panels(teams, summary), strict=True):
161
- ax.errorbar([n + offset for n in ns], [p[0] for p in points],
162
- yerr=[[max(0.0, p[0] - p[1]) for p in points], # Wilson at 0/n: 1e-15
163
- [max(0.0, p[2] - p[0]) for p in points]],
164
- color=SERIES[k], linewidth=2, marker="o", markersize=7, capsize=3,
165
- elinewidth=1.5, label=model)
166
- ax.set_ylabel(label)
167
- ax.set_xticks(ns)
168
- for ax, (_, _, scale) in zip(axes, panels(*series[0][1:]), strict=True): # every series in
169
- if scale == "log":
170
- ax.set_yscale("log")
171
- ax.yaxis.set_major_formatter(FuncFormatter(tokens))
172
- elif scale:
173
- ax.set_ylim(*scale)
174
- else:
175
- ax.set_ylim(bottom=0)
176
- for ax in axes:
177
- ax.set_facecolor(SURFACE)
178
- ax.grid(axis="y", color=GRID, linewidth=0.8)
179
- ax.set_axisbelow(True)
180
- ax.spines[["top", "right"]].set_visible(False)
181
- ax.set_xlabel("Swarm size N")
182
- if len(series) > 1:
183
- axes[0].legend(frameon=False, loc="center right", fontsize=9)
184
- fig.suptitle(title, fontsize=11, color=INK, x=0.01, ha="left")
185
- fig.text(0.01, 0.01, "One attempt per problem. Success: share of teams with any agent right, "
186
- "95% Wilson intervals. Tokens (log scale) and posts: means, 95% intervals. Wall time (init "
187
- "to release): median and interquartile range.", fontsize=8, color=INK_2)
188
- fig.tight_layout(rect=(0, 0.05, 1, 0.94))
189
- fig.savefig(path, dpi=200, facecolor=SURFACE)
190
-
191
-
192
- def load(root: Path) -> tuple[list[dict], list[dict]]:
193
- rows = [json.loads(line) for line in (root / "rows.jsonl").read_text().splitlines() if line]
194
- teams = sorted((team_row(r) for r in rows), key=lambda t: (t["agents"], t["problem"]))
195
- return teams, by_n(teams)
196
-
197
-
198
- def main(argv=None) -> int:
199
- parser = argparse.ArgumentParser(description="The sweep's figure, CSVs and table.")
200
- parser.add_argument("root", nargs="?", type=Path, help="one grid; outputs go there too")
201
- parser.add_argument("--series", action="append", default=[], help="MODEL=ROOT, repeatable")
202
- parser.add_argument("--out", type=Path, help="where --series outputs go")
203
- args = parser.parse_args(argv)
204
- if args.root: # the grid's model, from one of its team specs
205
- spec = next(args.root.glob("src/*/spec.yaml"), None)
206
- model = next((x.split(": ", 1)[1].strip() for x in spec.read_text().splitlines()
207
- if x.startswith("model: ")), args.root.name) if spec else args.root.name
208
- sources, out = [(model.split("/")[-1], args.root)], args.root
209
- else:
210
- sources = [(s.split("=", 1)[0], Path(s.split("=", 1)[1])) for s in args.series]
211
- out = args.out
212
- out.mkdir(parents=True, exist_ok=True)
213
- series = [(model, *load(root)) for model, root in sources]
214
- write_csv(out / "teams.csv", [{"model": m} | t for m, teams, _ in series for t in teams])
215
- write_csv(out / "by_n.csv", [{"model": m} | s for m, _, summary in series for s in summary])
216
- (out / "by_n.md").write_text(table(series))
217
- figure(out / "scaling.png", series, "s3-aggregation with legion: success and cost against "
218
- f"swarm size ({', '.join(m for m, _, _ in series)})")
219
- print(table(series))
220
- return 0
221
-
222
-
223
- if __name__ == "__main__":
224
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/registries.conf DELETED
@@ -1,13 +0,0 @@
1
- # podman's registries for the sweep's workers (CONTAINERS_REGISTRIES_CONF in their profile):
2
- # Docker Hub images through Google's pull-through mirror first, since each worker job pulls the
3
- # task image into its own storage and the cluster's shared address meets Docker Hub's
4
- # unauthenticated pull limit (toomanyrequests). Docker Hub stays the fallback.
5
- unqualified-search-registries = ["docker.io"]
6
- short-name-mode = "permissive"
7
-
8
- [[registry]]
9
- prefix = "docker.io"
10
- location = "docker.io"
11
-
12
- [[registry.mirror]]
13
- location = "mirror.gcr.io"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/serve-vllm.sbatch DELETED
@@ -1,29 +0,0 @@
1
- #!/bin/bash
2
- # The sweep's model server: one vLLM on one GPU (docs/open-models.md "On the HF cluster"), in
3
- # Pyxis on hopper-b200. The agents (podman on hopper-cpu) reach it by this node's address.
4
- # sbatch -p hopper-b200 -o <dir>/vllm-%j.log legion/sweep/serve-vllm.sbatch
5
- # Its log ends with: serving <model> at http://<node address>:8000/v1
6
- #SBATCH --job-name=s3-sweep-vllm
7
- #SBATCH --gpus=1
8
- #SBATCH --cpus-per-task=16
9
- #SBATCH --mem=96G
10
- #SBATCH --time=3:00:00
11
- set -uo pipefail
12
- MODEL=${MODEL:-Qwen/Qwen3.5-27B}
13
- PORT=${PORT:-8000}
14
- IMAGE=${IMAGE:-/fsx/anton/shared/images/vllm-openai-v0.32.0.sqsh}
15
- export HF_HOME=/hf
16
- mkdir -p "/scratch/$USER/hf" # the weights, on the node's own disk
17
- # Thinking off for every request: s3 runs compare models without thinking, and the Qwen3.5 chat
18
- # templates' defaults differ (the 27B's thinks, the 2B's doesn't), so the server sets it.
19
- srun --overlap --container-image="$IMAGE" --no-container-mount-home \
20
- --container-mounts="/scratch/$USER/hf:/hf" --container-env=HF_HOME \
21
- vllm serve "$MODEL" --port "$PORT" \
22
- --enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser qwen3 \
23
- --default-chat-template-kwargs '{"enable_thinking": false}' &
24
- until curl -sf -o /dev/null "localhost:$PORT/v1/models"; do
25
- sleep 10
26
- kill -0 $! 2>/dev/null || { echo "vLLM exited during startup"; exit 1; }
27
- done
28
- echo "serving $MODEL at http://$(hostname -I | awk '{print $1}'):$PORT/v1"
29
- wait
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/setaside.py DELETED
@@ -1,74 +0,0 @@
1
- """Why each set-aside attempt of a grid didn't count: `uv run legion/sweep/setaside.py
2
- <root>`, from `<root>/rows-discarded.jsonl` and the attempt's own logs. A restarted
3
- driver scores an attempt again from what it left, so one attempt can have several entries: its
4
- reason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
5
-
6
- - the worker was relaunched (more than one incarnation: legion#121's case) after it ran out of memory
7
- (the worker's memory ladder rotated or preempted it), or else after a node failure;
8
- - the worker ran out of memory and was preempted or killed without a relaunch;
9
- - the worker started more than 2 min after the launch (the loop's 15 minutes count from it);
10
- - the controller's node was reclaimed (spot) mid-run;
11
- - the task image couldn't be pulled (Docker Hub's unauthenticated limit), so the Trials never
12
- started;
13
- - the verifier timed out (Harbor's 60 s) on a loaded worker;
14
- - an agent's Trial failed before its verifier ran (e.g. legion's idle probe of the container);
15
- - the run was cancelled before its Trials were graded (the driver stopped and its in-flight
16
- teams cancelled, e.g. to switch the workers to the image mirror).
17
- """
18
-
19
- import json
20
- import re
21
- import sys
22
- from collections import Counter
23
- from pathlib import Path
24
-
25
-
26
- def reason(row: dict, run_dir: Path) -> str:
27
- logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*")
28
- if p.is_file()} if (run_dir / "logs").is_dir() else {}
29
- workers = " ".join(v for k, v in logs.items() if "-agent-w" in k)
30
- controllers = " ".join(v for k, v in logs.items() if k.startswith("legion-ctl-"))
31
- if (row.get("incarnations") or 0) > 1:
32
- if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers):
33
- return "worker relaunched after running out of memory (legion#121's case)"
34
- return "worker relaunched after a node failure (legion#121's case)"
35
- if (row.get("worker_wait_s") or 0) > 120: # sweep.py's WAIT_LIMIT
36
- return "worker queued past the launch (the loop counts from it)"
37
- if "DUE TO NODE FAILURE" in controllers or row.get("outcome") == "controller lost":
38
- return "controller's node reclaimed (spot)"
39
- if "toomanyrequests" in workers:
40
- return "task image not pulled (Docker Hub limit): Trials never started"
41
- if re.search(r"preempted \(memory\)|oom_kill", workers):
42
- return "worker ran out of memory (preempted or killed, not relaunched)"
43
- if any("VerifierTimeoutError" in p.read_text(errors="replace")
44
- for p in run_dir.glob("results/*/agent-*/trials/*/result.json")):
45
- return "verifier timed out (60 s) on a loaded worker"
46
- failed = [(json.loads(p.read_text()).get("exception_info") or {}).get("exception_type")
47
- for p in run_dir.glob("results/*/agent-*/trials/*/result.json")]
48
- if kinds := sorted({k for k in failed if k and k != "CancelledError"}): # cancelled: below
49
- return f"an agent's Trial failed before its verifier ran ({', '.join(kinds)})"
50
- return "cancelled before grading (driver stopped, in-flight teams cancelled)"
51
-
52
-
53
- def main(root: Path) -> int:
54
- attempts = {}
55
- for line in (root / "rows-discarded.jsonl").read_text().splitlines():
56
- row = json.loads(line)
57
- seen = attempts.setdefault(row["run"], row) # the driver that watched it knew most
58
- seen["incarnations"] = max(seen.get("incarnations") or 0, row.get("incarnations") or 0)
59
- if row.get("outcome") == "controller lost":
60
- seen["outcome"] = row["outcome"]
61
- kept = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines()]
62
- reasons = Counter(reason(r, root / "runs" / run) for run, r in attempts.items())
63
- rerun = sum(r.get("reruns", 0) > 0 for r in kept)
64
- head = (f"Attempts set aside: {len(attempts)} (rows-discarded.jsonl); "
65
- f"teams that needed a rerun: {rerun} of {len(kept)}")
66
- lines = [head, ""]
67
- lines += [f"- {why}: {k}" for why, k in reasons.most_common()]
68
- (root / "setaside.md").write_text("\n".join(lines) + "\n")
69
- print("\n".join(lines))
70
- return 0
71
-
72
-
73
- if __name__ == "__main__":
74
- raise SystemExit(main(Path(sys.argv[1])))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/sweep.py DELETED
@@ -1,341 +0,0 @@
1
- """The s3-aggregation scaling sweep on the HF cluster, one command for the whole grid, run from
2
- Legion's checkout (its environment, and its `.venv` for the workers):
3
-
4
- uv run python <this dataset>/legion/sweep/sweep.py --urls http://<vllm node>:8000/v1 \\
5
- [--problems 1-32] [--agents 1,2,4,8,16] [--parallel 8] [--root .legion/s3-sweep] \\
6
- [--bucket lewtun/s3-aggregation-sweep] [--dataset HuggingFaceSwarms/s3-aggregation-results]
7
-
8
- Each (problem, N) team is its own legion run (`compute: slurm`, podman agents on hopper-cpu, a
9
- local board on its one worker), from team.py's cluster spec with the sweep's model on `urls`
10
- (the same board rules, loop and limits at every N). Every team lists every server: Legion at or
11
- after 0401df9 (legion#129) picks each agent's server from its run and its name, so concurrent
12
- teams' agents spread over the servers. Per team: `legion init` (a worker sized to
13
- N), `legion launch`, wait until its loop is done and its agents are idle, `legion stop --release`
14
- (each Trial is graded as the worker drains; the results land in the run directory), then
15
- eval/metrics.py's row plus the wall time goes to `<root>/rows.jsonl`. Until legion#121
16
- is fixed, a team must run on one worker incarnation (a relaunch or a preemption overwrites
17
- results); and a spot reclaim may take its controller, or leave rewards unverified. A run that
18
- doesn't count (why_invalid) runs again as `<task>-rK` (its row: `reruns`). A team that
19
- has a row is skipped, so the same command resumes. At the end plot.py writes the figure, CSV
20
- and table, and with --dataset each run directory (spec, results, logs; never run.env) goes to
21
- that private dataset under `<prefix>/<task>/`.
22
-
23
- Needs HF_TOKEN (or `hf auth login`): the workers clone the private task dataset and sync the
24
- private state bucket with it. The agents get no Hub token; the vLLM server takes no key.
25
- """
26
-
27
- import argparse
28
- import importlib.util
29
- import json
30
- import os
31
- import re
32
- import shutil
33
- import subprocess
34
- import sys
35
- import threading
36
- import time
37
- from concurrent.futures import ThreadPoolExecutor
38
- from datetime import UTC, datetime
39
- from pathlib import Path
40
-
41
- import yaml
42
- from huggingface_hub import HfApi, get_token
43
-
44
- HERE = Path(__file__).resolve().parent
45
- REPO = Path.cwd() # Legion's checkout
46
- MODEL = "Qwen/Qwen3.5-27B"
47
- SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")
48
- lock, init_lock = threading.Lock(), threading.Semaphore(4)
49
- LOST, GONE = "controller lost", "no controller left"
50
- # the loop's `until` (and the driver's team timeout) count from the launch, not from the worker's
51
- # start: a run whose worker queued longer than this (a busy or scaling partition) doesn't count
52
- WAIT_LIMIT = 120 # s
53
-
54
-
55
- def load(name: str, path: Path):
56
- spec = importlib.util.spec_from_file_location(name, path)
57
- module = importlib.util.module_from_spec(spec)
58
- spec.loader.exec_module(module)
59
- return module
60
-
61
-
62
- team = load("team", HERE.parent / "team.py")
63
- metrics = load("metrics", HERE.parents[1] / "eval" / "metrics.py")
64
-
65
-
66
- def say(*parts) -> None:
67
- with lock:
68
- print(datetime.now(UTC).strftime("%H:%M:%S"), *parts, flush=True)
69
-
70
-
71
- def numbers(text: str) -> list[int]:
72
- """`1-32` or `1,3,7` -> the numbers."""
73
- out = []
74
- for part in text.split(","):
75
- a, _, b = part.partition("-")
76
- out += range(int(a), int(b or a) + 1)
77
- return out
78
-
79
-
80
- def legion(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess:
81
- env = {**os.environ, "LEGION_RUN_DIR": str(run_dir)}
82
- env.pop("VIRTUAL_ENV", None)
83
- return subprocess.run([str(Path(sys.executable).with_name("legion")), *args], cwd=REPO,
84
- env=env, capture_output=True, text=True, timeout=timeout, check=False)
85
-
86
-
87
- def write_experiment(src: Path, problem: int, n: int, name: str, urls: list[str],
88
- model: str, revision: str) -> None:
89
- """team.py's cluster spec at the dataset `revision`, with the sweep's model on its servers,
90
- as swarm `name`."""
91
- team.main(["--problem", str(problem), "--agents", str(n), "--where", "cluster",
92
- "--revision", revision,
93
- "--out", str(src)])
94
- spec = yaml.safe_load((src / "spec.yaml").read_text())
95
- spec["name"] = name
96
- spec["model"] = model
97
- spec["inference"] = {"urls": urls} # no key: the servers take none
98
- (src / "spec.yaml").write_text(
99
- f"# {spec['task']['selector']} for the scaling sweep (sweep.py): team.py's cluster spec "
100
- f"with {model} on the sweep's servers.\n" + yaml.safe_dump(spec, sort_keys=False))
101
-
102
-
103
- def profile(root: Path, n: int, most: int = 16) -> Path:
104
- """A worker sized to the team: a CPU per agent (at least 4), 1900 MB per CPU (hopper-cpu
105
- allows 2000); its podman pulls Docker Hub images through a mirror (registries.conf)."""
106
- cpus = max(4, min(n, most)) # `most`: a big job can queue past the loop's until
107
- path = root / "profiles" / f"n{n:02d}.env"
108
- path.parent.mkdir(parents=True, exist_ok=True)
109
- path.write_text(f"SLURM_PARTITION=hopper-cpu\nWORKER_CPUS={cpus}\nWORKER_MEM={cpus * 1900}M\n"
110
- f"SLURM_MAX_MEM_PER_CPU_MB=2000\nVENV={REPO / '.venv'}\n"
111
- f"CONTAINERS_REGISTRIES_CONF={HERE / 'registries.conf'}\n")
112
- return path
113
-
114
-
115
- def controller_state(name: str) -> str:
116
- """The Slurm state of the run's controller job (`legion-ctl-<run>`), '' when it has none."""
117
- out = subprocess.run(["squeue", "-h", "-n", f"legion-ctl-{name}", "-o", "%T"],
118
- capture_output=True, text=True, check=False).stdout.split()
119
- return out[0] if out else ""
120
-
121
-
122
- def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
123
- """Poll `legion status` until the loop is done and every agent is idle: 'done', or why not.
124
- A controller that stops answering and isn't running (a spot reclaim requeued it, or it is
125
- gone) is LOST."""
126
- deadline, unanswered = time.monotonic() + timeout, 0
127
- while time.monotonic() < deadline:
128
- status = legion(run_dir, "status", task, timeout=120)
129
- text = status.stdout
130
- unanswered = unanswered + 1 if status.returncode != 0 else 0
131
- if unanswered >= 3 and controller_state(task) != "RUNNING":
132
- return LOST
133
- if re.search(r"crashloop|launch_refused", text):
134
- return "worker failed: " + " ".join(text.split())[:300]
135
- if re.search(r"^loop agent: done", text, re.MULTILINE) and re.search(
136
- rf"^agent .*\bidle:{n}\b", text, re.MULTILINE):
137
- return "done"
138
- time.sleep(20)
139
- return f"not done after {timeout:.0f} s"
140
-
141
-
142
- def attempt(args, root: Path, secrets: Path, problem: int, n: int, name: str) -> dict | None:
143
- """One run of a team as swarm `name`: its row, or None when it could not start."""
144
- run_dir, src = root / "runs" / name, root / "src" / name
145
- if run_dir.exists() and (any((run_dir / "launch").glob("*.env"))
146
- or (run_dir / "hosts" / "controller.host").exists()):
147
- # a previous driver launched it and stopped before its row: finish it from here, or,
148
- # with its controller gone (released, cancelled or reclaimed), score what it left
149
- alive = bool(controller_state(name))
150
- say(name, "adopting the run a previous driver launched" + ("" if alive else
151
- " (no controller left)"))
152
- return finish(args, run_dir, name, problem, n, (run_dir / "cluster.env").stat().st_mtime,
153
- None if alive else GONE)
154
- if run_dir.exists():
155
- shutil.rmtree(run_dir) # init failed before: nothing ran
156
- started = time.time()
157
- write_experiment(src, problem, n, name, args.urls, args.model, args.revision)
158
- log = root / "logs" / f"{name}-init.log"
159
- log.parent.mkdir(parents=True, exist_ok=True)
160
- for tries in range(3):
161
- with init_lock: # a few at a time: many at once race on the bucket's write check
162
- init = legion(run_dir, "init", str(run_dir), "--from", str(src), "--profile",
163
- str(profile(root, n, args.max_worker_cpus)), "--secrets", str(secrets))
164
- log.write_text(init.stdout + init.stderr)
165
- if init.returncode == 0:
166
- break
167
- time.sleep(10 * (tries + 1))
168
- else:
169
- failed = [x for x in init.stdout.splitlines() if x.startswith("FAIL")]
170
- say(name, "init failed 3 times:", failed or init.stdout[-300:], "(log:", log, ")")
171
- return None
172
- say(name, "launching")
173
- launch = legion(run_dir, "launch", str(run_dir / "experiment"))
174
- if launch.returncode != 0:
175
- say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:])
176
- return finish(args, run_dir, name, problem, n, started, "launch")
177
- return finish(args, run_dir, name, problem, n, started)
178
-
179
-
180
- def finish(args, run_dir: Path, name: str, problem: int, n: int, started: float,
181
- why: str | None = None) -> dict:
182
- """Wait for a launched team, release it (its Trials are graded) and make its row."""
183
- # the team's limit counts from its own start, also when a restarted driver adopts it
184
- why = why or wait_done(run_dir, name, n, max(0.0, args.team_timeout - (time.time() - started)))
185
- if why == LOST: # nothing to release: end its jobs, and the team runs again
186
- say(name, "controller lost (spot reclaim?): cancelling its jobs")
187
- for job in (f"legion-ctl-{name}", f"{name}-agent-w0000"):
188
- subprocess.run(["scancel", "-n", job], check=False)
189
- release = subprocess.CompletedProcess([], 1)
190
- elif why == GONE: # its rewards and export are on disk, or it doesn't count
191
- release = subprocess.CompletedProcess([], 1)
192
- else:
193
- say(name, "loop:", why, "- releasing")
194
- release = legion(run_dir, "stop", name, "--release")
195
- ended = time.time()
196
- return metrics.row(run_dir) | {
197
- "problem": problem, "wall_s": round(ended - started, 1), "outcome": why,
198
- "released": release.returncode == 0,
199
- # each launch of the worker slot writes one env file: more than one is a relaunch or a
200
- # preemption, whose results a later incarnation overwrites (legion#121)
201
- "incarnations": len(list((run_dir / "launch").glob("*.env"))),
202
- "worker_wait_s": worker_wait(run_dir),
203
- "started_at": datetime.fromtimestamp(started, UTC).isoformat()}
204
-
205
-
206
- def worker_wait(run_dir: Path) -> float | None:
207
- """Seconds from the controller writing the worker's first launch file to the worker job's
208
- first log line (None: not known)."""
209
- launches = sorted((run_dir / "launch").glob("*.env"), key=lambda p: p.stat().st_mtime)
210
- logs = sorted((run_dir / "logs").glob("*-agent-w*.out"))
211
- if not launches or not logs:
212
- return None
213
- first = logs[0].read_text(errors="replace").split("\n", 1)[0]
214
- try:
215
- started = datetime.fromisoformat(first.split(" ", 1)[0])
216
- except ValueError:
217
- return None
218
- return round(started.timestamp() - launches[0].stat().st_mtime, 1)
219
-
220
-
221
- def why_invalid(row: dict) -> str:
222
- """Why a team's run doesn't count ('' when it does): a model result needs the run on one
223
- worker incarnation (legion#121), its controller kept, every agent's reward and the board export.
224
- A missing reward means the verifier never ran: the infrastructure failed, not the team. And
225
- its worker started within WAIT_LIMIT of the launch, so the loop's 15 minutes were the team's."""
226
- wait = row.get("worker_wait_s") or 0
227
- return "; ".join(why for why, bad in (
228
- (f"{row.get('incarnations')} worker incarnations", row.get("incarnations") != 1),
229
- (f"worker started {wait:.0f} s after the launch", wait > WAIT_LIMIT),
230
- (LOST, row.get("outcome") == LOST),
231
- (f"missing {', '.join(row['missing'])}"[:120], bool(row["missing"]))) if bad)
232
-
233
-
234
- def valid(row: dict) -> bool:
235
- return not why_invalid(row)
236
-
237
-
238
- def run_team(args, root: Path, secrets: Path, problem: int, n: int) -> dict | None:
239
- """A team, run again (as `<task>-rK`) until it runs on one worker incarnation (legion#121)."""
240
- task = f"{args.tag}agg-p{problem:02d}-n{n:02d}"
241
- for reruns in range(args.max_reruns + 1):
242
- row = attempt(args, root, secrets, problem, n, task if reruns == 0 else f"{task}-r{reruns}")
243
- if row is None:
244
- return None
245
- row["reruns"] = reruns
246
- if valid(row):
247
- break
248
- say(task, f"run doesn't count ({why_invalid(row)}): running it again")
249
- with lock, (root / "rows-discarded.jsonl").open("a") as f:
250
- f.write(json.dumps(row) + "\n")
251
- with lock, (root / "rows.jsonl").open("a") as f:
252
- f.write(json.dumps(row) + "\n")
253
- say(task, f"success={row['success']} rewards={list(row['rewards'].values())} "
254
- f"posts={row['posts']} wall={row['wall_s']} s reruns={row['reruns']} "
255
- f"incarnations={row['incarnations']} missing={row['missing']}")
256
- return row
257
-
258
-
259
- def upload(root: Path, dataset: str, prefix: str) -> None:
260
- """Each run directory's spec, results and logs, and the rows, to a private dataset; never
261
- run.env, and nothing that holds a Hub token."""
262
- api = HfApi()
263
- api.create_repo(dataset, repo_type="dataset", private=True, exist_ok=True)
264
- if not api.dataset_info(dataset).private:
265
- raise SystemExit(f"{dataset} is public: refusing to upload")
266
- allow = ["*.jsonl", "*.csv", "*.md", "*.png", "runs/*/experiment/**", "runs/*/results/**",
267
- "runs/*/logs/**"]
268
- leaks = [str(p) for p in (root / "runs").rglob("*") if p.is_file()
269
- and not p.name.endswith(".env") and SECRET.search(p.read_text(errors="ignore"))]
270
- if leaks:
271
- raise SystemExit(f"refusing to upload: Hub tokens in {leaks[:5]}")
272
- api.upload_folder(repo_id=dataset, repo_type="dataset", folder_path=root,
273
- path_in_repo=prefix, allow_patterns=allow,
274
- commit_message=f"s3-aggregation sweep: {prefix}")
275
- say("uploaded", root, "to", f"{dataset}/{prefix}")
276
-
277
-
278
- def main(argv=None) -> int:
279
- parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
280
- parser.add_argument("--urls", required=True, help="the model servers, comma-separated")
281
- parser.add_argument("--model", default=MODEL)
282
- parser.add_argument("--revision", help="the dataset revision every team pins (default: its "
283
- "head; this checkout's resources/ must be that revision's)")
284
- parser.add_argument("--problems", default="1-32")
285
- parser.add_argument("--agents", default="1,2,4,8,16")
286
- parser.add_argument("--parallel", type=int, default=8, help="teams at once")
287
- parser.add_argument("--team-timeout", type=float, default=2400, help="s until a release")
288
- parser.add_argument("--max-reruns", type=int, default=5,
289
- help="runs again of a team whose run doesn't count (why_invalid)")
290
- parser.add_argument("--root", type=Path, default=REPO / ".legion" / "s3-sweep")
291
- parser.add_argument("--bucket", default="lewtun/s3-aggregation-sweep",
292
- help="private bucket for the runs' state (a new one per root: a "
293
- "swarm's name is used once in a bucket)")
294
- parser.add_argument("--namespace", default="lewtun")
295
- parser.add_argument("--dataset", help="private dataset for the run directories")
296
- parser.add_argument("--prefix", default="grid", help="folder in the dataset")
297
- parser.add_argument("--max-worker-cpus", type=int, default=16,
298
- help="cap a team's worker (a busy partition can hold a 16-CPU job past "
299
- "the loop's 15 minutes: its run then doesn't count)")
300
- parser.add_argument("--tag", default="",
301
- help="put before every run and swarm name (e.g. q2b-): two grids at once "
302
- "then never share a Slurm job name")
303
- args = parser.parse_args(argv)
304
- args.urls = args.urls.split(",")
305
- args.revision = team.pinned(args.revision)
306
- root = args.root.resolve()
307
- root.mkdir(parents=True, exist_ok=True)
308
- api = HfApi()
309
- api.create_bucket(args.bucket, private=True, exist_ok=True)
310
- if not api.bucket_info(args.bucket).private:
311
- raise SystemExit(f"bucket {args.bucket} is public: refusing")
312
- token = os.environ.get("HF_TOKEN") or get_token()
313
- secrets = root / f"secrets-{os.getpid()}.env" # per driver: two may share a root
314
- old = os.umask(0o077)
315
- secrets.write_text(f"HF_TOKEN={token}\nNAMESPACE={args.namespace}\n"
316
- f"BUCKET=hf://buckets/{args.bucket}\n")
317
- os.umask(old)
318
- rows_file = root / "rows.jsonl"
319
- rows = [json.loads(x) for x in rows_file.read_text().splitlines()] if rows_file.exists() else []
320
- if bad := [r for r in rows if not valid(r)]: # an earlier driver kept them: run them again
321
- with (root / "rows-discarded.jsonl").open("a") as f:
322
- f.write("".join(json.dumps(r) + "\n" for r in bad))
323
- rows_file.write_text("".join(json.dumps(r) + "\n" for r in rows if valid(r)))
324
- say(f"{len(bad)} rows that don't count moved to rows-discarded.jsonl")
325
- done = {(r["problem"], r["agents"]) for r in rows if valid(r)}
326
- teams = [(p, n) for p in numbers(args.problems) for n in numbers(args.agents)
327
- if (p, n) not in done]
328
- say(f"{len(teams)} teams to run ({len(done)} done), {args.parallel} at once, on {args.urls}")
329
- try:
330
- with ThreadPoolExecutor(args.parallel) as pool:
331
- list(pool.map(lambda t: run_team(args, root, secrets, *t), teams))
332
- finally:
333
- secrets.unlink(missing_ok=True)
334
- subprocess.run(["uv", "run", str(HERE / "plot.py"), str(root)], check=False) # matplotlib
335
- if args.dataset:
336
- upload(root, args.dataset, args.prefix)
337
- return 0
338
-
339
-
340
- if __name__ == "__main__":
341
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/sweep/waits.py DELETED
@@ -1,41 +0,0 @@
1
- """How long each kept team's worker waited in the Slurm queue: `uv run legion/sweep/waits.py
2
- <root>`. The loop's `until` counts from the launch, so a worker that starts late
3
- leaves its agents less of the 15 minutes; a run whose loop ran out before its worker started has
4
- no rewards and was run again (sweep.py). The wait is from the controller writing the worker's
5
- launch file to the worker job's first log line.
6
- """
7
-
8
- import json
9
- import statistics
10
- import sys
11
- from datetime import datetime
12
- from pathlib import Path
13
-
14
-
15
- def wait_s(run_dir: Path) -> float | None:
16
- launches = sorted((run_dir / "launch").glob("*.env"), key=lambda p: p.stat().st_mtime)
17
- logs = sorted((run_dir / "logs").glob("*-agent-w*.out"))
18
- if not launches or not logs:
19
- return None
20
- first = logs[0].read_text(errors="replace").split("\n", 1)[0]
21
- try:
22
- started = datetime.fromisoformat(first.split(" ", 1)[0])
23
- except ValueError:
24
- return None
25
- return started.timestamp() - launches[0].stat().st_mtime
26
-
27
-
28
- def main(root: Path) -> int:
29
- rows = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines()]
30
- waits = [(r, wait_s(root / "runs" / r["run"])) for r in rows]
31
- known = [(r, w) for r, w in waits if w is not None]
32
- long = [(r, w) for r, w in known if w > 300]
33
- print(f"teams: {len(rows)}, worker wait known for {len(known)}: median "
34
- f"{statistics.median(w for _, w in known):.0f} s, max {max(w for _, w in known):.0f} s; "
35
- f"over 5 min: {len(long)} (succeeded: {sum(bool(r['success']) for r, _ in long)}; "
36
- f"by N: {sorted(r['agents'] for r, _ in long)})")
37
- return 0
38
-
39
-
40
- if __name__ == "__main__":
41
- raise SystemExit(main(Path(sys.argv[1])))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
legion/team.py DELETED
@@ -1,85 +0,0 @@
1
- """Write the Legion spec for one s3-aggregation team, from Legion's checkout (it needs Legion):
2
-
3
- uv run python <this dataset>/legion/team.py --problem 7 --agents 4 [--where docker|sandbox|cluster]
4
-
5
- writes `out/agg-p07-n04/spec.yaml` next to this script (or `--out DIR`) from spec.template.yaml:
6
- the team `agg-p07-n04` at `--revision` (default: the dataset's head on the Hub), its 4 agents
7
- (agent-001 .. agent-004, one worker and board) on the selector `agg-p07-n04-s*`, so that agent K
8
- runs slot K's task, the one that states its number. `--where` picks the template's `where:`
9
- block: local docker, HF Sandboxes with a Space board, or the HF cluster with a local board. The
10
- dataset is private for now: HF_TOKEN must read it.
11
- """
12
-
13
- import argparse
14
- import copy
15
- import sys
16
- from pathlib import Path
17
-
18
- import yaml
19
- from huggingface_hub import HfApi
20
-
21
- from legion.models import load_spec_yaml
22
-
23
- HERE = Path(__file__).resolve().parent
24
- DATASET = "HuggingFaceSwarms/s3-aggregation"
25
- PROBLEMS, SIZES = range(1, 33), (1, 2, 4, 8, 16)
26
-
27
-
28
- def merge(base: dict, extra: dict) -> dict:
29
- out = dict(base)
30
- for key, value in extra.items():
31
- both = isinstance(value, dict) and isinstance(out.get(key), dict)
32
- out[key] = merge(out[key], value) if both else value
33
- return out
34
-
35
-
36
- def fill(value, names: dict[str, str]):
37
- if isinstance(value, dict):
38
- return {k: fill(v, names) for k, v in value.items()}
39
- if isinstance(value, list):
40
- return [fill(v, names) for v in value]
41
- if isinstance(value, str):
42
- for placeholder, text in names.items():
43
- value = value.replace(placeholder, text)
44
- return value
45
-
46
-
47
- def team_spec(template: dict, problem: int, agents: int, where: str,
48
- revision: str) -> tuple[str, dict]:
49
- """(the task's name, the team's spec) from the template."""
50
- template = copy.deepcopy(template)
51
- places = template.pop("where")
52
- task = f"agg-p{problem:02d}-n{agents:02d}"
53
- spec = fill(merge(template, places[where]), {"TEAM": task, "REVISION": revision})
54
- spec["agents"] = {"count": agents}
55
- spec["workers"]["agents_per_worker"] = agents
56
- return task, spec
57
-
58
-
59
- def pinned(revision: str | None) -> str:
60
- """The revision (default: the dataset's head) as a commit."""
61
- return HfApi().dataset_info(DATASET, revision=revision).sha
62
-
63
-
64
- def main(argv=None) -> int:
65
- parser = argparse.ArgumentParser(description="Write one s3-aggregation team's Legion spec.")
66
- parser.add_argument("--problem", type=int, required=True, choices=PROBLEMS)
67
- parser.add_argument("--agents", type=int, required=True, choices=SIZES)
68
- parser.add_argument("--where", choices=("docker", "sandbox", "cluster"), default="sandbox")
69
- parser.add_argument("--revision", help="the dataset revision to pin (default: its head)")
70
- parser.add_argument("--out", type=Path, help="default: out/<task> next to this script")
71
- args = parser.parse_args(argv)
72
- template = load_spec_yaml((HERE / "spec.template.yaml").read_text())
73
- task, spec = team_spec(template, args.problem, args.agents, args.where,
74
- pinned(args.revision))
75
- out = args.out or HERE / "out" / task
76
- out.mkdir(parents=True, exist_ok=True)
77
- header = (f"# {task} ({args.where}), written by {DATASET}'s legion/team.py from "
78
- "spec.template.yaml: edit the template, not this file.\n")
79
- (out / "spec.yaml").write_text(header + yaml.safe_dump(spec, sort_keys=False, width=100))
80
- print(out / "spec.yaml")
81
- return 0
82
-
83
-
84
- if __name__ == "__main__":
85
- sys.exit(main())