Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
Agent Manager commited on
Commit
eae0824
·
1 Parent(s): 37ffff1

Rename flock integration to legion

Browse files
README.md CHANGED
@@ -18,9 +18,9 @@ A [Harbor](https://harborframework.com) environment that measures whether a swar
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 [Flock](https://github.com/huggingface/flock)
22
  swarms, whose agents talk over a shared message board. It isn't a replication of the paper: the
23
- agents are Pi with Flock's board, and the board is what we measure.
24
 
25
  **This dataset is private for now.**
26
 
@@ -50,17 +50,17 @@ 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
- flock/
54
- spec.template.yaml what every team's Flock 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 (flock/sweep/README.md)
57
- eval/metrics.py one row per team from Flock 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. Flock 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
@@ -83,18 +83,18 @@ 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 Flock
87
 
88
- Flock's [`experiments/s3-aggregation/spec.yaml`](https://github.com/huggingface/flock/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 flock 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, `flock/team.py` writes the spec from `flock/spec.template.yaml`,
94
- run from Flock'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 Flock type on
98
  one worker (`agents_per_worker: N`), so they share that worker's board.
99
 
100
  ### On HF Sandboxes
@@ -104,10 +104,10 @@ The controller and the team's one worker run on this machine, each agent in its
104
 
105
  ```sh
106
  DS=../s3-aggregation # this dataset, at the revision team.py pins
107
- uv run python $DS/flock/team.py --problem 7 --agents 4 --where sandbox --out runs/agg-p07-n04
108
- BOARD_SPACE=<you>/s3-agg-p07-n04 uv run flock launch runs/agg-p07-n04/spec.yaml
109
- uv run flock status agg-p07-n04
110
- uv run python $DS/eval/metrics.py .flock/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
  ```
@@ -122,29 +122,29 @@ snapshot bucket, once the run directory has the export.
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 (Flock'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/flock/team.py --problem 7 --agents 4 --where cluster --out runs/src/agg-p07-n04
132
- uv run flock init $PWD/runs/agg-p07-n04 --from runs/src/agg-p07-n04 --profile cluster.env --secrets secrets.env
133
- export FLOCK_RUN_DIR=$PWD/runs/agg-p07-n04
134
- uv run flock launch $FLOCK_RUN_DIR/experiment
135
- uv run flock status agg-p07-n04 # until the loop is done and the agents idle
136
- uv run flock stop agg-p07-n04 --release # drain: each Trial is graded, then the jobs end
137
- uv run python $DS/eval/metrics.py $FLOCK_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 Flock's Slurm results (huggingface/flock#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. `flock/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 (`flock/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.
@@ -159,7 +159,7 @@ proxy, so there they are not enforced and each Trial records a `message_board.wa
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 `.flock/<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
 
@@ -188,7 +188,7 @@ 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 Flock run of a team (below)
192
  ```
193
 
194
  1. **Generator:** `generate.py` reproduces `problems.json` and `tasks/` byte for byte; another
@@ -220,20 +220,20 @@ uv run check.py --env none --run RUN_DIR # also a Flock 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 Flock run** (`--run RUN_DIR`, a local run's `.flock/<swarm>-<time>/`): each
224
- agent's first prompt (its task's instruction and Flock'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 `flock-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 Flock'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
@@ -241,17 +241,17 @@ uv run check.py --env none --run RUN_DIR # also a Flock run of a team (below)
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); Flock's `--env flock.harbor.envs:HFSandbox`, with Flock 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 (Flock'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 (Flock'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.
@@ -260,9 +260,9 @@ To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04-s01
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 (Flock's local board is new each run;
264
  delete a Space board after its run).
265
- - **Board rules** are enforced only where Flock'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
 
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
 
 
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
 
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
 
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
  ```
 
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.
 
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
 
 
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
  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
 
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.
 
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
check.py CHANGED
@@ -2,12 +2,12 @@
2
  # requires-python = ">=3.12"
3
  # dependencies = ["harbor==0.25.0"]
4
  # ///
5
- """s3-aggregation's checks that need no model (huggingface/flock#115, section 5):
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 Flock 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
@@ -42,8 +42,8 @@
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 flock's `--env flock.harbor.envs:HFSandbox` there.
46
- 5. No-cheat, a Flock 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
@@ -51,14 +51,14 @@
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 `flock-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 Flock'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
@@ -122,7 +122,7 @@ def team_of(task: str) -> tuple[int, int]:
122
 
123
 
124
  def held(team: str) -> dict[str, str]:
125
- """A team's agents (Flock'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,7 +361,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", "flock", "eval", ".cache",
365
  "__pycache__", ".git"}
366
  check(not beside, f"folders beside tasks/: {sorted(beside)}")
367
 
@@ -578,9 +578,9 @@ def texts(message: dict) -> str:
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 (Flock's flock-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./-])flock-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.:])",
@@ -605,8 +605,8 @@ def given_away(text: str, team: dict[str, str]) -> set[int]:
605
 
606
 
607
  def audit_run(run: Path) -> tuple[list[str], dict]:
608
- """(problems, report) for a Flock run of one team (a local run's `.flock/<swarm>-<time>/`):
609
- no prompt Flock 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)."""
@@ -650,7 +650,7 @@ def audit_run(run: Path) -> tuple[list[str], dict]:
650
  calls[part.get("id")] = str(arguments.get("command") or json.dumps(
651
  arguments))
652
  elif role in ("system", "user"):
653
- if role == "system" or prompts == 0: # what Flock and the task tell the agent
654
  if given := given_away(text, team) & others:
655
  problems.append(f"run {agent}: its {role} prompt holds {sorted(given)}")
656
  got_own |= role == "user" and own in holds(text, {own})
@@ -681,7 +681,7 @@ AUDIT_TEAM = "agg-p01-n04"
681
 
682
  def synthetic_run(root: Path, prompt: str = "", output: str = "",
683
  poster: dict | None = None, command: str = "cat /tmp/notes.json") -> Path:
684
- """A local run directory of AUDIT_TEAM as Flock leaves it, whose agents behave: each posts
685
  its number and reads the board. `prompt` joins agent-001's first prompt, `output` is
686
  the output of a non-board `command` it runs before it reads the board, and `poster` posts a number
687
  in another agent's name first (agent -> number). Each agent's first prompt is its own slot's
@@ -720,7 +720,7 @@ def synthetic_run(root: Path, prompt: str = "", output: str = "",
720
  prompt if agent == "agent-001" else "")}])]
721
  if agent == "agent-001" and output:
722
  events += [call(2, command), result(2, output)]
723
- events += [call(3, "flock-tool message_board.read --json '{}'"),
724
  result(3, json.dumps({"messages": lines}))]
725
  (run / "agents" / "_sessions" / f"{agent}.jsonl").write_text("\n".join(events) + "\n")
726
  return run
@@ -767,7 +767,7 @@ def check_audit() -> int:
767
 
768
  # ------------------------------------------------------------------ metrics
769
 
770
- # The lines of Flock's experiments/s3-aggregation/spec.yaml that eval/metrics.py reads
771
  RUN_SPEC = """name: ${TEAM:-agg-p01-n04}
772
  naming: consecutive-id
773
  task:
@@ -789,7 +789,7 @@ def metrics_module():
789
 
790
 
791
  def slurm_dir(root: Path, team: str, agents: list[str], env_files: dict[str, str]) -> Path:
792
- """A Slurm run's directory as `flock init` and the workers leave it: the spec, the env files
793
  and, per agent in `agents`, one Trial of its own slot of `team`, graded by the task's own
794
  grader (agent-001 answers right, the others wrong)."""
795
  (root / "experiment").mkdir(parents=True)
@@ -833,7 +833,7 @@ def check_metrics() -> int:
833
  "reward: agent-004"]),
834
  "an unplanned agent": ("agg-p01-n04", four[:3], {"run.env": "N=2\n"}, "agg-p01-n04", 2,
835
  ["agents: Trials of agents the spec didn't plan: agent-003"]),
836
- # inline comments, as Flock's read_env_file reads them: after a quoted value's closing
837
  # quote, and after whitespace in an unquoted one
838
  "quoted values with comments": ("agg-p03-n04", four[:3],
839
  {"run.env": 'TEAM="agg-p03-n04" # group\nN="4" # size\n'},
@@ -866,7 +866,7 @@ def main() -> int:
866
  parser.add_argument("--jobs-dir", type=Path, default=None,
867
  help="keep the Trials' files here (default: a temporary directory)")
868
  parser.add_argument("--run", type=Path, action="append", default=[],
869
- help="also check a Flock run of a team (a local run's directory)")
870
  args = parser.parse_args()
871
  check_generator()
872
  print(f"1. generator: {len(failures)} failures")
@@ -886,7 +886,7 @@ def main() -> int:
886
  f"failures; {json.dumps(report)}")
887
  before = len(failures)
888
  cases = check_audit()
889
- print(f"5. no-cheat (the Flock-run audit on {cases} synthetic runs): "
890
  f"{len(failures) - before} failures")
891
  before = len(failures)
892
  cases = check_metrics()
@@ -895,7 +895,7 @@ def main() -> int:
895
  for run in args.run:
896
  before = len(failures)
897
  report = check_run(run)
898
- print(f"5. no-cheat (Flock run {run.name}): {len(failures) - before} failures; "
899
  f"{json.dumps(report)}")
900
  for failure in failures:
901
  print("FAIL:", failure)
 
2
  # requires-python = ">=3.12"
3
  # dependencies = ["harbor==0.25.0"]
4
  # ///
5
+ """s3-aggregation's checks that need no model (huggingface/legion#115, section 5):
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
 
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
 
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
 
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
  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
 
 
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.:])",
 
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)."""
 
650
  calls[part.get("id")] = str(arguments.get("command") or json.dumps(
651
  arguments))
652
  elif role in ("system", "user"):
653
+ if role == "system" or prompts == 0: # what Legion and the task tell the agent
654
  if given := given_away(text, team) & others:
655
  problems.append(f"run {agent}: its {role} prompt holds {sorted(given)}")
656
  got_own |= role == "user" and own in holds(text, {own})
 
681
 
682
  def synthetic_run(root: Path, prompt: str = "", output: str = "",
683
  poster: dict | None = None, command: str = "cat /tmp/notes.json") -> Path:
684
+ """A local run directory of AUDIT_TEAM as Legion leaves it, whose agents behave: each posts
685
  its number and reads the board. `prompt` joins agent-001's first prompt, `output` is
686
  the output of a non-board `command` it runs before it reads the board, and `poster` posts a number
687
  in another agent's name first (agent -> number). Each agent's first prompt is its own slot's
 
720
  prompt if agent == "agent-001" else "")}])]
721
  if agent == "agent-001" and output:
722
  events += [call(2, command), result(2, output)]
723
+ events += [call(3, "legion-tool message_board.read --json '{}'"),
724
  result(3, json.dumps({"messages": lines}))]
725
  (run / "agents" / "_sessions" / f"{agent}.jsonl").write_text("\n".join(events) + "\n")
726
  return run
 
767
 
768
  # ------------------------------------------------------------------ metrics
769
 
770
+ # The lines of Legion's experiments/s3-aggregation/spec.yaml that eval/metrics.py reads
771
  RUN_SPEC = """name: ${TEAM:-agg-p01-n04}
772
  naming: consecutive-id
773
  task:
 
789
 
790
 
791
  def slurm_dir(root: Path, team: str, agents: list[str], env_files: dict[str, str]) -> Path:
792
+ """A Slurm run's directory as `legion init` and the workers leave it: the spec, the env files
793
  and, per agent in `agents`, one Trial of its own slot of `team`, graded by the task's own
794
  grader (agent-001 answers right, the others wrong)."""
795
  (root / "experiment").mkdir(parents=True)
 
833
  "reward: agent-004"]),
834
  "an unplanned agent": ("agg-p01-n04", four[:3], {"run.env": "N=2\n"}, "agg-p01-n04", 2,
835
  ["agents: Trials of agents the spec didn't plan: agent-003"]),
836
+ # inline comments, as Legion's read_env_file reads them: after a quoted value's closing
837
  # quote, and after whitespace in an unquoted one
838
  "quoted values with comments": ("agg-p03-n04", four[:3],
839
  {"run.env": 'TEAM="agg-p03-n04" # group\nN="4" # size\n'},
 
866
  parser.add_argument("--jobs-dir", type=Path, default=None,
867
  help="keep the Trials' files here (default: a temporary directory)")
868
  parser.add_argument("--run", type=Path, action="append", default=[],
869
+ help="also check a Legion run of a team (a local run's directory)")
870
  args = parser.parse_args()
871
  check_generator()
872
  print(f"1. generator: {len(failures)} failures")
 
886
  f"failures; {json.dumps(report)}")
887
  before = len(failures)
888
  cases = check_audit()
889
+ print(f"5. no-cheat (the Legion-run audit on {cases} synthetic runs): "
890
  f"{len(failures) - before} failures")
891
  before = len(failures)
892
  cases = check_metrics()
 
895
  for run in args.run:
896
  before = len(failures)
897
  report = check_run(run)
898
+ print(f"5. no-cheat (Legion run {run.name}): {len(failures) - before} failures; "
899
  f"{json.dumps(report)}")
900
  for failure in failures:
901
  print("FAIL:", failure)
eval/metrics.py CHANGED
@@ -1,8 +1,8 @@
1
- """One row per team from s³ runs (huggingface/flock#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 (`.flock/<swarm>-<time>/`, docs/local.md), or
5
- a Slurm run's directory (`flock 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
@@ -187,10 +187,10 @@ 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 Flock reads them (flock.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 Flock refuses the file."""
194
  values = {}
195
  for line in path.read_text(encoding="utf-8").splitlines():
196
  line = line.strip()
@@ -209,7 +209,7 @@ def env_values(path: Path) -> dict[str, str]:
209
 
210
 
211
  def run_values(run_dir: Path) -> dict[str, str]:
212
- """The run's `cluster.env` then `run.env` (later wins), as Flock reads them: what fills the
213
  spec's `${VAR}`s."""
214
  values = {}
215
  for name in ("cluster.env", "run.env"):
@@ -219,13 +219,13 @@ def run_values(run_dir: Path) -> dict[str, str]:
219
 
220
 
221
  def expand(text: str, values: dict[str, str]) -> str:
222
- """`${VAR}` and `${VAR:-default}` in the spec's text, as Flock 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 (`flock 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.
 
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
 
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()
 
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"):
 
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.
generate.py CHANGED
@@ -5,7 +5,7 @@ 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. Flock 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
 
@@ -17,7 +17,7 @@ import random
17
  import shutil
18
  from pathlib import Path
19
 
20
- SEED = 115 # huggingface/flock#115
21
  PROBLEMS = 32 # the paper's held-out set size
22
  NUMBERS = 16 # per problem; a team of N holds the first N
23
  SIZES = (1, 2, 4, 8, 16)
@@ -52,7 +52,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: Flock'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. 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
 
 
17
  import shutil
18
  from pathlib import Path
19
 
20
+ SEED = 115 # huggingface/legion#115
21
  PROBLEMS = 32 # the paper's held-out set size
22
  NUMBERS = 16 # per problem; a team of N holds the first N
23
  SIZES = (1, 2, 4, 8, 16)
 
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
 
{flock → legion}/spec.template.yaml RENAMED
@@ -58,7 +58,7 @@ where:
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/ (Flock's docs/slurm.md).
62
  cluster:
63
  namespace: ${NAMESPACE}
64
  bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name>
 
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>
{flock → legion}/sweep/README.md RENAMED
@@ -1,14 +1,14 @@
1
  # s3-aggregation scaling sweep
2
 
3
  What the s³ paper's Figure 5 (information aggregation: success against swarm size) looks like
4
- with Flock: every problem of this dataset at N = 1, 2, 4, 8 and 16 agents, each team its own
5
- Flock run on the HF cluster. The results so far (`Qwen/Qwen3.5-27B` and `Qwen/Qwen3.5-2B`) are
6
- in huggingface/flock#120's comments and on Flock'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 (Flock'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 |
@@ -18,8 +18,8 @@ runs in the private `HuggingFaceSwarms/s3-aggregation-results`.
18
 
19
  ## Run it
20
 
21
- From Flock's checkout at or after `0401df9` (with its Slurm results, huggingface/flock#122, so
22
- each Trial's grading reaches the run directory, and huggingface/flock#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
@@ -27,10 +27,10 @@ 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 .flock/s3-sweep/vllm-%j.log $DS/flock/sweep/serve-vllm.sbatch
31
- sbatch -p hopper-b200 --export=ALL,PORT=8001 -o .flock/s3-sweep/vllm-%j.log $DS/flock/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/flock/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
@@ -44,19 +44,19 @@ 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: Flock at or after `0401df9`, huggingface/flock#129, picks it from the run
48
- and the agent's name, so concurrent teams' agents spread over the servers; with an older Flock
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
- (`flock 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 flock#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
@@ -74,7 +74,7 @@ is safe: in-flight teams keep running and are adopted.
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 flock's board tools (`flock-tool message_board.*`) through its shell; a shared `#general` channel, mentions and a long-poll `wait`; flock'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 |
 
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 |
 
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
 
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
 
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
 
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 |
{flock → legion}/sweep/failures.py RENAMED
@@ -1,4 +1,4 @@
1
- """How the teams of a grid fail: `uv run flock/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,
@@ -6,7 +6,7 @@ the wrong count, the wrong numbers, unsorted, or right), against the problem's n
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 `flock-tool`, tool calls that failed, and whether it ever reached `flock-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
  """
@@ -57,7 +57,7 @@ def latest_answer(run_dir: Path, agent: str) -> str | None:
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_flock_tool": False,
61
  "called_util_flock": False, "session": path is not None and path.is_file()}
62
  if not out["session"]:
63
  return out
@@ -73,7 +73,7 @@ def behaviour(path: Path | None) -> dict:
73
  out["tool_calls"] += 1
74
  command = json.dumps(part.get("arguments") or {})
75
  calls[part.get("id")] = command
76
- out["used_flock_tool"] |= "flock-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":
@@ -122,7 +122,7 @@ def main(argv=None) -> int:
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 flock-tool: {sum(not a['used_flock_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")
 
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,
 
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
  """
 
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
 
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":
 
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")
{flock → legion}/sweep/plot.py RENAMED
@@ -4,8 +4,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 flock/sweep/plot.py <root> # one grid, into <root>
8
- uv run flock/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³
@@ -214,7 +214,7 @@ def main(argv=None) -> int:
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 flock: success and cost against "
218
  f"swarm size ({', '.join(m for m, _, _ in series)})")
219
  print(table(series))
220
  return 0
 
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³
 
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
{flock → legion}/sweep/registries.conf RENAMED
File without changes
{flock → legion}/sweep/serve-vllm.sbatch RENAMED
@@ -1,7 +1,7 @@
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 flock/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
 
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
{flock → legion}/sweep/setaside.py RENAMED
@@ -1,9 +1,9 @@
1
- """Why each set-aside attempt of a grid didn't count: `uv run flock/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: flock#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);
@@ -11,7 +11,7 @@ reason uses them all. Writes `<root>/setaside.md`; the reasons, first that appli
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. flock'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
  """
@@ -27,11 +27,11 @@ 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("flock-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 (flock#121's case)"
34
- return "worker relaunched after a node failure (flock#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":
 
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);
 
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
  """
 
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":
{flock → legion}/sweep/sweep.py RENAMED
@@ -1,18 +1,18 @@
1
  """The s3-aggregation scaling sweep on the HF cluster, one command for the whole grid, run from
2
- Flock's checkout (its environment, and its `.venv` for the workers):
3
 
4
- uv run python <this dataset>/flock/sweep/sweep.py --urls http://<vllm node>:8000/v1 \\
5
- [--problems 1-32] [--agents 1,2,4,8,16] [--parallel 8] [--root .flock/s3-sweep] \\
6
  [--bucket lewtun/s3-aggregation-sweep] [--dataset HuggingFaceSwarms/s3-aggregation-results]
7
 
8
- Each (problem, N) team is its own flock 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: Flock at or
11
- after 0401df9 (flock#129) picks each agent's server from its run and its name, so concurrent
12
- teams' agents spread over the servers. Per team: `flock init` (a worker sized to
13
- N), `flock launch`, wait until its loop is done and its agents are idle, `flock 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 flock#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
@@ -42,7 +42,7 @@ import yaml
42
  from huggingface_hub import HfApi, get_token
43
 
44
  HERE = Path(__file__).resolve().parent
45
- REPO = Path.cwd() # Flock'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)
@@ -77,10 +77,10 @@ def numbers(text: str) -> list[int]:
77
  return out
78
 
79
 
80
- def flock(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess:
81
- env = {**os.environ, "FLOCK_RUN_DIR": str(run_dir)}
82
  env.pop("VIRTUAL_ENV", None)
83
- return subprocess.run([str(Path(sys.executable).with_name("flock")), *args], cwd=REPO,
84
  env=env, capture_output=True, text=True, timeout=timeout, check=False)
85
 
86
 
@@ -113,19 +113,19 @@ def profile(root: Path, n: int, most: int = 16) -> Path:
113
 
114
 
115
  def controller_state(name: str) -> str:
116
- """The Slurm state of the run's controller job (`flock-ctl-<run>`), '' when it has none."""
117
- out = subprocess.run(["squeue", "-h", "-n", f"flock-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 `flock 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 = flock(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":
@@ -159,7 +159,7 @@ def attempt(args, root: Path, secrets: Path, problem: int, n: int, name: str) ->
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 = flock(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:
@@ -170,7 +170,7 @@ def attempt(args, root: Path, secrets: Path, problem: int, n: int, name: str) ->
170
  say(name, "init failed 3 times:", failed or init.stdout[-300:], "(log:", log, ")")
171
  return None
172
  say(name, "launching")
173
- launch = flock(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")
@@ -184,20 +184,20 @@ def finish(args, run_dir: Path, name: str, problem: int, n: int, started: float,
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"flock-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 = flock(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 (flock#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()}
@@ -220,7 +220,7 @@ def worker_wait(run_dir: Path) -> float | None:
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 (flock#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
@@ -236,7 +236,7 @@ def valid(row: dict) -> bool:
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 (flock#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}")
@@ -287,7 +287,7 @@ def main(argv=None) -> int:
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 / ".flock" / "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)")
 
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
 
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)
 
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
 
 
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":
 
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:
 
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")
 
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()}
 
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
 
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}")
 
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)")
{flock → legion}/sweep/waits.py RENAMED
@@ -1,4 +1,4 @@
1
- """How long each kept team's worker waited in the Slurm queue: `uv run flock/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
 
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
{flock → legion}/team.py RENAMED
@@ -1,6 +1,6 @@
1
- """Write the Flock spec for one s3-aggregation team, from Flock's checkout (it needs Flock):
2
 
3
- uv run python <this dataset>/flock/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
@@ -18,7 +18,7 @@ from pathlib import Path
18
  import yaml
19
  from huggingface_hub import HfApi
20
 
21
- from flock.models import load_spec_yaml
22
 
23
  HERE = Path(__file__).resolve().parent
24
  DATASET = "HuggingFaceSwarms/s3-aggregation"
@@ -62,7 +62,7 @@ def pinned(revision: str | None) -> str:
62
 
63
 
64
  def main(argv=None) -> int:
65
- parser = argparse.ArgumentParser(description="Write one s3-aggregation team's Flock 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")
@@ -74,7 +74,7 @@ def main(argv=None) -> int:
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 flock/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")
 
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
 
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"
 
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")
 
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")