Datasets:

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

Private numbers from a resource (resources/private_number.py) instead of role files; Flock tooling, metrics and sweep move here from huggingface/flock#120

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +153 -45
  2. check.py +303 -80
  3. eval/metrics.py +267 -0
  4. flock/spec.template.yaml +75 -0
  5. flock/sweep/README.md +82 -0
  6. flock/sweep/failures.py +134 -0
  7. flock/sweep/plot.py +224 -0
  8. flock/sweep/registries.conf +13 -0
  9. flock/sweep/serve-vllm.sbatch +26 -0
  10. flock/sweep/setaside.py +63 -0
  11. flock/sweep/sweep.py +316 -0
  12. flock/sweep/waits.py +41 -0
  13. flock/team.py +94 -0
  14. generate.py +29 -18
  15. resources/message_board.py +5 -0
  16. resources/numbers.json +162 -0
  17. resources/private_number.py +58 -0
  18. roles/agg-p01-n01/slot-01.md +0 -1
  19. roles/agg-p01-n02/slot-01.md +0 -1
  20. roles/agg-p01-n02/slot-02.md +0 -1
  21. roles/agg-p01-n04/slot-01.md +0 -1
  22. roles/agg-p01-n04/slot-02.md +0 -1
  23. roles/agg-p01-n04/slot-03.md +0 -1
  24. roles/agg-p01-n04/slot-04.md +0 -1
  25. roles/agg-p01-n08/slot-01.md +0 -1
  26. roles/agg-p01-n08/slot-02.md +0 -1
  27. roles/agg-p01-n08/slot-03.md +0 -1
  28. roles/agg-p01-n08/slot-04.md +0 -1
  29. roles/agg-p01-n08/slot-05.md +0 -1
  30. roles/agg-p01-n08/slot-06.md +0 -1
  31. roles/agg-p01-n08/slot-07.md +0 -1
  32. roles/agg-p01-n08/slot-08.md +0 -1
  33. roles/agg-p01-n16/slot-01.md +0 -1
  34. roles/agg-p01-n16/slot-02.md +0 -1
  35. roles/agg-p01-n16/slot-03.md +0 -1
  36. roles/agg-p01-n16/slot-04.md +0 -1
  37. roles/agg-p01-n16/slot-05.md +0 -1
  38. roles/agg-p01-n16/slot-06.md +0 -1
  39. roles/agg-p01-n16/slot-07.md +0 -1
  40. roles/agg-p01-n16/slot-08.md +0 -1
  41. roles/agg-p01-n16/slot-09.md +0 -1
  42. roles/agg-p01-n16/slot-10.md +0 -1
  43. roles/agg-p01-n16/slot-11.md +0 -1
  44. roles/agg-p01-n16/slot-12.md +0 -1
  45. roles/agg-p01-n16/slot-13.md +0 -1
  46. roles/agg-p01-n16/slot-14.md +0 -1
  47. roles/agg-p01-n16/slot-15.md +0 -1
  48. roles/agg-p01-n16/slot-16.md +0 -1
  49. roles/agg-p02-n01/slot-01.md +0 -1
  50. roles/agg-p02-n02/slot-01.md +0 -1
README.md CHANGED
@@ -28,10 +28,11 @@ agents are Pi with Flock's board, and the board is what we measure.
28
 
29
  Each of the N agents holds one private integer from 1 to 99, written in English words
30
  ("seventy-three"). The team must list all N numbers in ascending order, keeping equal numbers
31
- from different agents as separate entries. Each agent shares its number on the board, reads the
32
- others', keeps one number per participant, writes `/app/answer.json` (a JSON array of N
33
- integers in ascending order) and stops. The team succeeds if any agent's answer is right. The
34
- instruction adapts the paper's (Appendix G) to the board and prescribes no protocol beyond that.
 
35
 
36
  | | |
37
  | --- | --- |
@@ -43,23 +44,33 @@ instruction adapts the paper's (Appendix G) to the board and prescribes no proto
43
 
44
  ```text
45
  tasks/agg-pPP-nNN/
46
- instruction.md the same for every problem of a team size: no number in it
47
  task.toml
48
- tests/test.sh the grader
49
- tests/expected.json the answer: copied in only after the agent is done
50
- solution/solve.sh an oracle with its own copy of the answer
51
- roles/agg-pPP-nNN/
52
- slot-01.md ... "Your private number: seventy-three", one per agent
53
- problems.json the 32 problems
54
- generate.py writes problems.json, tasks/ and roles/ from its seed (115)
55
- check.py the checks that need no model
 
 
 
 
 
 
 
56
  ```
57
 
58
- **Private numbers** reach each agent only through its own instructions: Flock's
59
- `agents.role_files` gives agent `agent-00k` the text of `slot-0k.md` and nothing else. The role
60
- files live outside the task folders, and a task folder puts nothing in the container while the
61
- agent works (no `environment/`; `tests/` arrives after the agent is done), so no agent's
62
- container holds another agent's number.
 
 
 
63
 
64
  ## Reward
65
 
@@ -79,32 +90,117 @@ scored on its own answer; the team succeeds if any agent scores 1.
79
 
80
  ## Run it with Flock
81
 
82
- Flock's [`experiments/s3-aggregation`](https://github.com/huggingface/flock/tree/main/experiments/s3-aggregation)
83
- writes the spec for one team (the task, its N agents and their role files, the board) and
84
- `experiments/s3/metrics.py` turns a run into one row per team: success, each agent's reward,
85
- tokens and board posts, and the message graph's centralization and reciprocity (the paper's
86
- Appendix M). On HF Sandboxes, with the board on a Space:
87
 
88
  ```sh
89
- uv run experiments/s3-aggregation/team.py --problem 7 --agents 4 # out/agg-p07-n04/
90
- uv run flock launch experiments/s3-aggregation/out/agg-p07-n04/spec.yaml
91
- uv run experiments/s3/metrics.py .flock/agg-p07-n04-<time>/
92
  ```
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  ## Checks
95
 
96
  The checks that need no model, in one command (`uv` installs Harbor 0.25.0):
97
 
98
  ```sh
99
- uv run check.py # the Trials on HF Sandboxes (HF_TOKEN, five cpu-basic sandboxes)
100
  uv run check.py --env docker # the Trials in local docker
101
  uv run check.py --env none # without the Trials
 
102
  ```
103
 
104
- 1. **Generator:** `generate.py` reproduces `problems.json`, `tasks/` and `roles/` byte for byte;
105
- another seed gives other problems; 32 problems of 16 integers in 1..99; the words read back
106
- to their numbers; each task's team is its problem's first N numbers, and each role file holds
107
- its own slot's number.
108
  2. **Graders**, run as Harbor runs them (`tests/` copied in after the agent is done, through
109
  any link the agent left): on all 160 tasks the oracle scores 1, and wrong, partial, padded,
110
  unsorted and duplicate-dropping answers score 0. On one task per team size, twelve kinds of
@@ -117,16 +213,27 @@ uv run check.py --env none # without the Trials
117
  `PYTHONPATH`, a `sitecustomize` on `PYTHONPATH`, a `usercustomize` or a `.pth` file in the user
118
  site, and a `dirname` shadowed on the `PATH` that points `expected.json` at the agent's file.
119
  3. **No-cheat, in the files:** a task folder holds only its five files, its instruction is the
120
- same for every problem of its team size, the answer is only in `tests/` and `solution/`, and
121
- the role files are outside `tasks/`.
122
- 4. **No-cheat, from inside Trials** of `agg-p01-n16`, with probe agents (no model): one runs in
123
- the container while "the agent works" and finds no `tests/` or `solution/` and no file
124
- holding the answer, a role line or a hyphenated number word of the problem; then it writes
125
- the answer, the same search finds it (a control), and the task's verifier scores it 1. Four
126
- more leave a cheat with a wrong answer, and the verifier scores each 0: `/app/answer.json` as
127
- a symlink to `/tests/expected.json`; `/app` as a symlink into a `/tests` they made; a
128
- `json.py` that reads any answer as right wherever the verifier may start; a `sitecustomize`
129
- in site-packages that does the same.
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads
132
  `tests/` with the host's file owner, which a sandbox can't take when the host's uid is over
@@ -139,8 +246,8 @@ To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04 --ag
139
 
140
  - **Private for now**, so whatever resolves and downloads the task (Flock's worker, which then
141
  uploads it into the sandbox) needs a Hub token that can read it. The sandboxes never do.
142
- - **Roles need Flock.** Harbor alone has no per-agent text: a task run without Flock's
143
- `agents.role_files` gives the agent no number to share.
144
  - **The grader can't see the board:** an agent could guess or copy a wrong number and still be
145
  scored only on its file. The board export in the run directory shows what was said.
146
  - **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the
@@ -153,5 +260,6 @@ To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04 --ag
153
  - **Board rules** are enforced only where Flock's rule proxy runs (docker, podman); on HF
154
  Sandboxes they are not.
155
  - **Not the paper's setup:** a message board instead of `message`/`read_messages` tools with
156
- notifications, an answer file instead of a `####` line, no example message, no token cost in
157
- the reward, and N = 1 is a solo control rather than a team.
 
 
28
 
29
  Each of the N agents holds one private integer from 1 to 99, written in English words
30
  ("seventy-three"). The team must list all N numbers in ascending order, keeping equal numbers
31
+ from different agents as separate entries. Each agent reads its number from its environment,
32
+ shares it on the board, reads the others', keeps one number per participant, writes
33
+ `/app/answer.json` (a JSON array of N integers in ascending order) and stops. The team succeeds
34
+ if any agent's answer is right. The instruction adapts the paper's (Appendix G) to the board and
35
+ prescribes no protocol beyond that.
36
 
37
  | | |
38
  | --- | --- |
 
44
 
45
  ```text
46
  tasks/agg-pPP-nNN/
47
+ instruction.md the same for every problem of a team size: no number in it
48
  task.toml
49
+ tests/test.sh the grader
50
+ tests/expected.json the answer: copied in only after the agent is done
51
+ solution/solve.sh an oracle with its own copy of the answer
52
+ resources/ Flock's resources_dir for these tasks
53
+ private_number.py puts each agent's own number in its environment (PRIVATE_NUMBER)
54
+ numbers.json each task's agents (agent-001 ...) and their numbers, in words
55
+ message_board.py Flock's own board, brought along (a resources_dir replaces Flock's)
56
+ flock/
57
+ spec.template.yaml what every team's Flock run shares: model, board rules, loop, limits
58
+ team.py writes one team's spec (docker, HF Sandboxes or the HF cluster)
59
+ sweep/ the scaling sweep on the HF cluster (flock/sweep/README.md)
60
+ eval/metrics.py one row per team from Flock run directories
61
+ problems.json the 32 problems
62
+ generate.py writes problems.json, tasks/ and resources/numbers.json from its seed (115)
63
+ check.py the checks that need no model
64
  ```
65
 
66
+ **Private numbers** reach each agent only through its own environment. With the spec's
67
+ `resources_dir` on `resources/` and `resources.private_number.team` naming the task, Flock's
68
+ worker loads `private_number.py`, and its `bind(name)` gives agent `agent-00k`'s Trial
69
+ `PRIVATE_NUMBER=<its number in words>` and nothing else. The module and `numbers.json` stay on
70
+ the worker: they are not in Flock's tool bundle, the task folder or any container. A task folder
71
+ puts nothing in the container while the agent works (no `environment/`; `tests/` arrives after
72
+ the agent is done), and the instruction holds no number, so no agent can read another agent's
73
+ number until that agent posts it.
74
 
75
  ## Reward
76
 
 
90
 
91
  ## Run it with Flock
92
 
93
+ Flock's [`experiments/s3-aggregation/spec.yaml`](https://github.com/huggingface/flock/tree/main/experiments/s3-aggregation)
94
+ runs `agg-p01-n04` in local docker with this dataset next to Flock's checkout (its
95
+ `resources_dir` is `../s3-aggregation/resources` from there), at the revision it pins:
 
 
96
 
97
  ```sh
98
+ hf download HuggingFaceSwarms/s3-aggregation --repo-type dataset --revision <the spec's> --local-dir ../s3-aggregation
99
+ uv run flock launch experiments/s3-aggregation/spec.yaml
 
100
  ```
101
 
102
+ For any other team or place, `flock/team.py` writes the spec from `flock/spec.template.yaml`,
103
+ run from Flock's checkout. **Needs** `HF_TOKEN`, which reads the private dataset (and starts the
104
+ sandboxes and deploys the board's Space), and `HF_INFERENCE_TOKEN`, a fine-grained token with
105
+ only "Make calls to Inference Providers", which goes into the agents' containers. Never the same
106
+ token. Each agent of a team is `agent-001` ... (`naming: consecutive-id`), all one Flock type on
107
+ one worker (`agents_per_worker: N`), so they share that worker's board.
108
+
109
+ ### On HF Sandboxes
110
+
111
+ The controller and the team's one worker run on this machine, each agent in its own HF Sandbox
112
+ (`cpu-basic`) and the board on a Space:
113
+
114
+ ```sh
115
+ DS=../s3-aggregation # this dataset, at the revision team.py pins
116
+ uv run python $DS/flock/team.py --problem 7 --agents 4 --where sandbox --out runs/agg-p07-n04
117
+ BOARD_SPACE=<you>/s3-agg-p07-n04 uv run flock launch runs/agg-p07-n04/spec.yaml
118
+ uv run flock status agg-p07-n04
119
+ uv run python $DS/eval/metrics.py .flock/agg-p07-n04-<time>/ # once the run has ended
120
+ hf repos delete <you>/s3-agg-p07-n04 --repo-type space -y # a new board for every team
121
+ hf buckets delete <you>/s3-agg-p07-n04-bucket # its snapshots
122
+ ```
123
+
124
+ The run ends by itself once its loop is over (4 rounds or 15 minutes) and every agent is idle,
125
+ then Harbor grades each agent's `/app/answer.json` and the board is exported into the run
126
+ directory. The board's Space must be public while the run uses it (the sandboxes hold no Hub
127
+ token), and the instruction has no run tag, so give each team a new Space and delete it, and its
128
+ snapshot bucket, once the run directory has the export.
129
+
130
+ ### On the HF cluster
131
+
132
+ `--where cluster` writes the spec for one Slurm worker running the team in rootless podman
133
+ (hopper-cpu has podman 4.9), with a local board on that worker, new each run, so no Space. The
134
+ run directory goes on the shared disk (Flock's docs/slurm.md "Deploying"): a cluster profile with
135
+ `SLURM_PARTITION=hopper-cpu`, `WORKER_CPUS` and `WORKER_MEM` (at most 2000 MB per CPU there)
136
+ and `VENV`, and a mode-600 secrets file with `HF_TOKEN`, `HF_INFERENCE_TOKEN`, `NAMESPACE` and
137
+ `BUCKET` (a private bucket for the run's state):
138
+
139
+ ```sh
140
+ uv run python $DS/flock/team.py --problem 7 --agents 4 --where cluster --out runs/src/agg-p07-n04
141
+ uv run flock init $PWD/runs/agg-p07-n04 --from runs/src/agg-p07-n04 --profile cluster.env --secrets secrets.env
142
+ export FLOCK_RUN_DIR=$PWD/runs/agg-p07-n04
143
+ uv run flock launch $FLOCK_RUN_DIR/experiment
144
+ uv run flock status agg-p07-n04 # until the loop is done and the agents idle
145
+ uv run flock stop agg-p07-n04 --release # drain: each Trial is graded, then the jobs end
146
+ uv run python $DS/eval/metrics.py $FLOCK_RUN_DIR
147
+ ```
148
+
149
+ A Slurm run doesn't end by itself: `--release` drains its worker, which is when each Trial is
150
+ graded. With Flock's Slurm results (huggingface/flock#122) the worker copies the grading
151
+ and the board export to `<run dir>/results/` (its own files are in the node's `/tmp`), and
152
+ `metrics.py` reads them from there. `flock/sweep/` runs the whole grid this way.
153
+
154
+ ### The board rules
155
+
156
+ The same for every eval run, since they shape how agents talk (`flock/spec.template.yaml`): one
157
+ channel, `#general`; an agent is woken by a mention or a reply in its thread; a post is at most
158
+ 1000 characters, at least 5 s after the agent's previous one, and at most 40 per agent. One
159
+ channel keeps every number in one place, as the paper's broadcast does; waking on mentions and
160
+ threads lets agents talk to each other without a reply to every post; the length, gap and count
161
+ caps bound what a looping agent can flood the board with, well above what the task needs (one
162
+ post per agent). Docker and podman enforce them in each agent's rule proxy. HF Sandboxes have no
163
+ proxy, so there they are not enforced and each Trial records a `message_board.warning` event.
164
+
165
+ ## Metrics
166
+
167
+ `uv run python eval/metrics.py RUN_DIR [RUN_DIR ...] [--out rows.jsonl]` writes one JSON line
168
+ per run directory (one team): a local run's `.flock/<swarm>-<time>/`, or a Slurm run's
169
+ directory. A Slurm run has no local bundle, so there the tokens come from Harbor's Trial results
170
+ (no reasoning split) and `stop_reason`, `cost_usd` and the turns are `null`:
171
+
172
+ | field | |
173
+ | --- | --- |
174
+ | `task`, `agents`, `revision`, `stop_reason`, `duration_s` | the team and how its run ended |
175
+ | `success` | any agent's reward is 1 (`null`: no rewards found) |
176
+ | `rewards` | each agent's reward: its latest Trial's verifier result |
177
+ | `tokens`, `cost_usd` | the team's tokens (input, output, cache, reasoning) and cost |
178
+ | `posts`, `other_posts` | the team's board posts in the run; posts by anyone else |
179
+ | `per_agent` | each agent's reward, tokens, posts and turns |
180
+ | `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) |
181
+ | `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 |
182
+ | `reciprocity` | the fraction of edges whose reverse exists; `null` without edges |
183
+ | `missing` | what the run directory lacks: an agent's reward, the board export |
184
+
185
+ Only messages posted between the run's start and end count. A post that mentions no one adds no
186
+ edge: on a board everyone reads every post, so a broadcast edge (the paper's) would connect
187
+ every pair that posts. s3-maze adds its move-log metrics to the same rows (`EXTRAS`).
188
+
189
  ## Checks
190
 
191
  The checks that need no model, in one command (`uv` installs Harbor 0.25.0):
192
 
193
  ```sh
194
+ uv run check.py # the Trials on HF Sandboxes (HF_TOKEN, twenty cpu-basic sandboxes)
195
  uv run check.py --env docker # the Trials in local docker
196
  uv run check.py --env none # without the Trials
197
+ uv run check.py --env none --run RUN_DIR # also a Flock run of a team (below)
198
  ```
199
 
200
+ 1. **Generator:** `generate.py` reproduces `problems.json`, `tasks/` and
201
+ `resources/numbers.json` byte for byte; another seed gives other problems; 32 problems of 16
202
+ integers in 1..99; the words read back to their numbers; each task's team is its problem's
203
+ first N numbers, and `numbers.json` gives agent `agent-00k` the k-th.
204
  2. **Graders**, run as Harbor runs them (`tests/` copied in after the agent is done, through
205
  any link the agent left): on all 160 tasks the oracle scores 1, and wrong, partial, padded,
206
  unsorted and duplicate-dropping answers score 0. On one task per team size, twelve kinds of
 
213
  `PYTHONPATH`, a `sitecustomize` on `PYTHONPATH`, a `usercustomize` or a `.pth` file in the user
214
  site, and a `dirname` shadowed on the `PATH` that points `expected.json` at the agent's file.
215
  3. **No-cheat, in the files:** a task folder holds only its five files, its instruction is the
216
+ same for every problem of its team size and holds no number, the answer is only in `tests/`
217
+ and `solution/`, and `resources/` holds only the resource, its numbers and the board.
218
+ 4. **No-cheat, the resource:** for every task and agent, `private_number`'s binding is that
219
+ agent's own number in `PRIVATE_NUMBER` and nothing else (no other variable, mount, host or
220
+ metadata, and no teammate's number anywhere in it); a team of the wrong size, an unknown
221
+ task or agent, and unknown options are refused.
222
+ 5. **No-cheat, from inside Trials** of `agg-p01-n16`, with probe agents (no model): sixteen
223
+ probes, one per agent, each with exactly the environment `private_number` binds for it, look
224
+ around the container while "the agent works": every file, every process's environment and
225
+ command line, and the instruction. Each finds its own number only in its environment, and no
226
+ teammate's number, no `tests/` or `solution/` and no file holding the answer anywhere; then it
227
+ writes the answer, the same search finds it (a control), and the task's verifier scores it 1.
228
+ Four more leave a cheat with a wrong answer, and the verifier scores each 0:
229
+ `/app/answer.json` as a symlink to `/tests/expected.json`; `/app` as a symlink into a
230
+ `/tests` they made; a `json.py` that reads any answer as right wherever the verifier may
231
+ start; a `sitecustomize` in site-packages that does the same.
232
+ 6. **No-cheat, a Flock run** (`--run RUN_DIR`, a local run's `.flock/<swarm>-<time>/`): each
233
+ agent's first prompt (the task's instruction and Flock's) holds no number of the team; the
234
+ first tool output in which an agent sees a teammate's number is a board read, after that
235
+ teammate posted it; the first post holding each number is its owner's; and each agent read
236
+ its own number from its environment.
237
 
238
  `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads
239
  `tests/` with the host's file owner, which a sandbox can't take when the host's uid is over
 
246
 
247
  - **Private for now**, so whatever resolves and downloads the task (Flock's worker, which then
248
  uploads it into the sandbox) needs a Hub token that can read it. The sandboxes never do.
249
+ - **The numbers need Flock's resource.** Harbor alone has no per-agent environment: a task run
250
+ without `resources/private_number.py` gives the agent no number to share.
251
  - **The grader can't see the board:** an agent could guess or copy a wrong number and still be
252
  scored only on its file. The board export in the run directory shows what was said.
253
  - **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the
 
260
  - **Board rules** are enforced only where Flock's rule proxy runs (docker, podman); on HF
261
  Sandboxes they are not.
262
  - **Not the paper's setup:** a message board instead of `message`/`read_messages` tools with
263
+ notifications, the number in the environment instead of the prompt, an answer file instead of
264
+ a `####` line, no example message, no token cost in the reward, and N = 1 is a solo control
265
+ rather than a team.
check.py CHANGED
@@ -7,11 +7,12 @@
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, tasks/ and roles/ byte for byte from its
12
- seed; another seed gives other problems; 32 problems of 16 integers in 1..99; the English
13
- words read back to their numbers; each task's team is its problem's first N numbers, and each
14
- role file holds its own slot's number.
15
  2. Graders, run as Harbor runs them (tests/ copied in after the agent is done): on every task,
16
  the oracle (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or
17
  duplicate-dropping answer scores 0. On one task per team size, malformed answers (missing,
@@ -27,12 +28,18 @@
27
  agent's own file.
28
  3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and
29
  solution/; its instruction is the same for every problem of its team size; the answer is only
30
- in tests/ and solution/; the role files live outside tasks/.
31
- 4. No-cheat, from inside Trials (`--env`), on `agg-p01-n16`, with probe agents (no model):
32
- - one looks around the container while "the agent works" and finds no tests/ or solution/
33
- and no file holding the answer, a role line or a hyphenated number word of the team (every
34
- number of the problem); then it writes the answer, the same search finds it (a control),
35
- and the task's own verifier scores it 1;
 
 
 
 
 
 
36
  - the others leave a cheat with a wrong answer: /app/answer.json as a symlink to
37
  /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any
38
  answer as right wherever the verifier may start; a sitecustomize in site-packages that
@@ -40,6 +47,11 @@
40
  `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
41
  uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
42
  over 65535 (some clusters): use flock's `--env flock.harbor.envs:HFSandbox` there.
 
 
 
 
 
43
  """
44
 
45
  import argparse
@@ -47,6 +59,7 @@ import asyncio
47
  import base64
48
  import json
49
  import os
 
50
  import shlex
51
  import shutil
52
  import subprocess
@@ -60,6 +73,8 @@ import generate as g # noqa: E402
60
 
61
  TASK_FILES = {"instruction.md", "task.toml", "tests/test.sh", "tests/expected.json",
62
  "solution/solve.sh"}
 
 
63
  PROBE_TASK = "agg-p01-n16"
64
  failures: list[str] = []
65
 
@@ -72,11 +87,10 @@ def check(ok: bool, what: str) -> None:
72
  def files(root: Path) -> dict[str, bytes]:
73
  """Relative path -> bytes for the generated files under root (not their modes: a download
74
  from the Hub has none, and Harbor runs the scripts with bash)."""
75
- out = {"problems.json": (root / "problems.json").read_bytes()}
76
- for folder in ("tasks", "roles"):
77
- for path in sorted((root / folder).rglob("*")):
78
- if path.is_file():
79
- out[str(path.relative_to(root))] = path.read_bytes()
80
  return out
81
 
82
 
@@ -103,6 +117,7 @@ def check_generator() -> None:
103
  check(all(read_words(g.words(n)) == n for n in range(1, 100))
104
  and len({g.words(n) for n in range(1, 100)}) == 99, "the English words are wrong")
105
  names = set()
 
106
  for p, numbers in enumerate(drawn, 1):
107
  for n in g.SIZES:
108
  name = g.task_name(p, n)
@@ -110,16 +125,14 @@ def check_generator() -> None:
110
  team = numbers[:n]
111
  expected = json.loads((HERE / "tasks" / name / "tests" / "expected.json").read_text())
112
  check(expected == sorted(team), f"{name}: expected.json is not the first {n} sorted")
113
- roles = sorted((HERE / "roles" / name).glob("*"))
114
- check([r.name for r in roles] == [f"slot-{k:02d}.md" for k in range(1, n + 1)],
115
- f"{name}: not one role file per slot")
116
- for slot, (path, number) in enumerate(zip(roles, team, strict=False), 1):
117
- text = path.read_text()
118
- check(text == f"Your private number: {g.words(number)}\n"
119
- and read_words(text.split(": ")[1].strip()) == number,
120
- f"{name}: slot {slot} does not hold its own number")
121
  check({p.name for p in (HERE / "tasks").iterdir()} == names, "tasks/ has other folders")
122
- check({p.name for p in (HERE / "roles").iterdir()} == names, "roles/ has other folders")
123
 
124
 
125
  def grade(task: Path, answer: bytes | None = None, cheat=None) -> int:
@@ -311,23 +324,140 @@ def check_files() -> None:
311
  if p.is_file() and answer in p.read_text()}
312
  check(holders == {"tests/expected.json", "solution/solve.sh"},
313
  f"{task.name}: the answer is in {sorted(holders)}")
314
- check(not any("Your private number:" in (task / f).read_text() for f in TASK_FILES),
315
- f"{task.name}: a role line is in the task folder")
316
  check(all(len(v) == 1 for v in by_size.values()),
317
  "an instruction or task.toml differs between problems of one team size")
 
 
318
 
319
 
320
- PROBE_SH = r"""
321
- mapfile -t secrets < <(printf %s "$1" | base64 -d)
322
- for d in /tests /solution; do [ -e "$d" ] && echo "visible $d"; done
323
- args=(); for s in "${secrets[@]}"; do args+=(-e "$s"); done
324
- search() {
325
- find / -xdev \( -path /proc -o -path /sys -o -path /dev -o -path /logs \) -prune -o -type f \
326
- -size -20M -print0 2>/dev/null | xargs -0 -r grep -IlF "$@" 2>/dev/null
327
- }
328
- search "${args[@]}" | sed 's/^/holds /'
329
- mkdir -p /app && printf %s "$2" > /app/answer.json
330
- search -e "$2" | sed 's/^/control /' # the same search finds the answer once it is written
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  """
332
  # What a cheating agent leaves for the verifier, before the tests arrive
333
  FAKE_JSON_SH = "printf 'def loads(*args, **kwargs):\\n return [1]\\n'"
@@ -350,22 +480,23 @@ try:
350
  from harbor.agents.base import BaseAgent
351
 
352
  class Probe(BaseAgent):
353
- """No model. `mode` answer: looks around the container as an agent could while it
354
- works, writes `probe.json` in its logs dir on the host, then the answer for the
355
- verifier. Any other mode: leaves that cheat (CHEATS) instead."""
 
356
 
357
- def __init__(self, *args, mode="answer", secrets=(), answer="", task_instruction="",
358
  **kwargs):
359
  super().__init__(*args, **kwargs)
360
- self.mode, self.secrets, self.answer = mode, secrets, answer
361
- self.task_instruction = task_instruction
362
 
363
  @staticmethod
364
  def name() -> str:
365
  return "s3-aggregation-probe"
366
 
367
  def version(self) -> str:
368
- return "2"
369
 
370
  async def setup(self, environment) -> None:
371
  pass
@@ -376,26 +507,25 @@ try:
376
  (self.logs_dir / "probe.json").write_text(json.dumps(
377
  {"return_code": result.return_code, "cheat": CHEATS[self.mode]}))
378
  return
379
- # the secrets travel base64-encoded: a copy of the command in the container would
380
- # otherwise hold them
381
- encoded = base64.b64encode("\n".join(self.secrets).encode()).decode()
382
- result = await environment.exec(
383
- f"bash -c {shlex.quote(PROBE_SH)} probe {encoded} {shlex.quote(self.answer)}",
384
- timeout_sec=600)
385
- lines = (result.stdout or "").splitlines()
 
 
386
  (self.logs_dir / "probe.json").write_text(json.dumps({
387
- "return_code": result.return_code,
388
- "visible": [x.split(" ", 1)[1] for x in lines if x.startswith("visible ")],
389
- "holds": [x.split(" ", 1)[1] for x in lines if x.startswith("holds ")],
390
- "control": [x.split(" ", 1)[1] for x in lines if x.startswith("control ")],
391
- "instruction_is_the_task_text":
392
- instruction.strip() == self.task_instruction.strip(),
393
  }, indent=1))
394
  except ImportError: # `--env none` needs no Harbor
395
  Probe = None
396
 
397
 
398
- async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict) -> tuple[dict | None, dict]:
 
399
  """One Trial of PROBE_TASK with the probe in `mode`: (its probe.json, rewards and error)."""
400
  from harbor.models.trial.config import (
401
  AgentConfig,
@@ -410,7 +540,7 @@ async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict) -> tuple[dict
410
  if ":" in env else
411
  EnvironmentConfig(type=env, kwargs=sandbox if env == "hf-sandbox" else {}))
412
  config = TrialConfig(
413
- task=TaskConfig(path=HERE / "tasks" / PROBE_TASK), trial_name=f"probe-{mode}",
414
  trials_dir=jobs, environment=environment,
415
  agent=AgentConfig(import_path="__main__:Probe", kwargs={"mode": mode, **kwargs}))
416
  result = await (await Trial.create(config)).run()
@@ -422,28 +552,49 @@ async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict) -> tuple[dict
422
 
423
 
424
  async def check_trials(env: str, jobs: Path) -> dict:
425
- task, roles = HERE / "tasks" / PROBE_TASK, HERE / "roles" / PROBE_TASK
 
426
  answer = (task / "tests" / "expected.json").read_text().strip()
427
- lines = [p.read_text().strip() for p in sorted(roles.glob("slot-*.md"))]
428
- hyphenated = sorted({w for line in lines if "-" in (w := line.split(": ")[1])})
429
- secrets = [answer, answer.replace(" ", ""), "Your private number:", *lines, *hyphenated]
 
 
 
 
 
 
 
 
430
  runs = await asyncio.gather(
431
- run_trial(env, jobs, "answer", {"secrets": secrets, "answer": answer,
432
- "task_instruction": (task / "instruction.md").read_text()}),
433
- *(run_trial(env, jobs, mode, {}) for mode in CHEATS))
434
- (probe, graded), *cheated = runs
435
- check(probe is not None and probe["return_code"] == 0,
436
- f"Trial: the probe did not run ({graded['error']})")
437
- if probe is not None:
438
- check(not probe["visible"], f"Trial: visible while the agent works: {probe['visible']}")
439
- check(not probe["holds"], f"Trial: files hold the team's numbers: {probe['holds']}")
440
- check("/app/answer.json" in probe["control"],
441
- f"Trial: the search did not find the written answer ({probe['control']})")
442
- check(probe["instruction_is_the_task_text"], "Trial: the instruction is not the task's")
443
- check(graded["rewards"] == {"reward": 1.0},
444
- f"Trial: the verifier gave the answer {graded['rewards']} ({graded['error']})")
445
- report = {"answer": {"probe": probe, **graded, "searched_for": len(secrets)}}
446
- for mode, (left, result) in zip(CHEATS, cheated, strict=True):
 
 
 
 
 
 
 
 
 
 
 
 
447
  check(left is not None and left["return_code"] == 0, f"Trial: cheat {mode} not left")
448
  check(result["rewards"] == {"reward": 0.0},
449
  f"Trial: cheat {mode} gave {result['rewards']} ({result['error']})")
@@ -451,12 +602,76 @@ async def check_trials(env: str, jobs: Path) -> dict:
451
  return report
452
 
453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
  def main() -> int:
455
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
456
  parser.add_argument("--env", default="hf-sandbox",
457
  help="Harbor environment type or import path for the Trials; none: skip")
458
  parser.add_argument("--jobs-dir", type=Path, default=None,
459
  help="keep the Trials' files here (default: a temporary directory)")
 
 
460
  args = parser.parse_args()
461
  check_generator()
462
  print(f"1. generator: {len(failures)} failures")
@@ -466,14 +681,22 @@ def main() -> int:
466
  before = len(failures)
467
  check_files()
468
  print(f"3. no-cheat (files): {len(failures) - before} failures")
 
 
 
469
  if args.env != "none":
470
  before = len(failures)
471
  with tempfile.TemporaryDirectory() as d:
472
  jobs = args.jobs_dir or Path(d)
473
  jobs.mkdir(parents=True, exist_ok=True)
474
  report = asyncio.run(check_trials(args.env, jobs))
475
- print(f"4. no-cheat (Trials on {args.env}, {PROBE_TASK}): {len(failures) - before} "
476
  f"failures; {json.dumps(report)}")
 
 
 
 
 
477
  for failure in failures:
478
  print("FAIL:", failure)
479
  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
+ uv run check.py --run RUN_DIR # also a Flock run of a team (group 6)
11
 
12
+ 1. Generator: generate.py reproduces problems.json, tasks/ and resources/numbers.json byte for
13
+ byte from its seed; another seed gives other problems; 32 problems of 16 integers in 1..99;
14
+ the English words read back to their numbers; each task's team is its problem's first N
15
+ numbers, and numbers.json gives agent-00k the k-th.
16
  2. Graders, run as Harbor runs them (tests/ copied in after the agent is done): on every task,
17
  the oracle (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or
18
  duplicate-dropping answer scores 0. On one task per team size, malformed answers (missing,
 
28
  agent's own file.
29
  3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and
30
  solution/; its instruction is the same for every problem of its team size; the answer is only
31
+ in tests/ and solution/; resources/ holds only private_number.py, numbers.json and the board.
32
+ 4. No-cheat, the resource: for every task and agent, private_number binds that agent's own
33
+ number as PRIVATE_NUMBER and nothing else, with no teammate's number in the binding or the
34
+ metadata, and exports nothing; a team of the wrong size, an unknown or missing task, an
35
+ unknown option and an agent off the team are refused.
36
+ 5. No-cheat, from inside Trials (`--env`), on `agg-p01-n16`, with probe agents (no model):
37
+ - one per agent, with exactly the environment private_number binds for it (as Flock's Pi
38
+ runs with it), looks around the container while "the agent works": no tests/ or solution/,
39
+ no file holding the answer or a teammate's hyphenated number word, no process whose
40
+ environment or command line holds a teammate's number, no number in the instruction, and
41
+ its own number in its environment (a control); then it writes the answer, the same search
42
+ finds it (a control), and the task's own verifier scores it 1;
43
  - the others leave a cheat with a wrong answer: /app/answer.json as a symlink to
44
  /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any
45
  answer as right wherever the verifier may start; a sitecustomize in site-packages that
 
47
  `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
48
  uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
49
  over 65535 (some clusters): use flock's `--env flock.harbor.envs:HFSandbox` there.
50
+ 6. No-cheat, a Flock run (`--run`, a local run's directory with its agents' event streams and
51
+ the board export): no system prompt or first prompt holds a number of the team; the first
52
+ output in which an agent sees a teammate's number is a board read, or a later prompt (a
53
+ wake-up quoting the board); the first post holding each number is its owner's; and each
54
+ agent read its own number outside the board.
55
  """
56
 
57
  import argparse
 
59
  import base64
60
  import json
61
  import os
62
+ import re
63
  import shlex
64
  import shutil
65
  import subprocess
 
73
 
74
  TASK_FILES = {"instruction.md", "task.toml", "tests/test.sh", "tests/expected.json",
75
  "solution/solve.sh"}
76
+ NUMBERS_JSON = "resources/numbers.json"
77
+ RESOURCE_FILES = {"private_number.py", "numbers.json", "message_board.py"}
78
  PROBE_TASK = "agg-p01-n16"
79
  failures: list[str] = []
80
 
 
87
  def files(root: Path) -> dict[str, bytes]:
88
  """Relative path -> bytes for the generated files under root (not their modes: a download
89
  from the Hub has none, and Harbor runs the scripts with bash)."""
90
+ out = {name: (root / name).read_bytes() for name in ("problems.json", NUMBERS_JSON)}
91
+ for path in sorted((root / "tasks").rglob("*")):
92
+ if path.is_file():
93
+ out[str(path.relative_to(root))] = path.read_bytes()
 
94
  return out
95
 
96
 
 
117
  check(all(read_words(g.words(n)) == n for n in range(1, 100))
118
  and len({g.words(n) for n in range(1, 100)}) == 99, "the English words are wrong")
119
  names = set()
120
+ held = json.loads((HERE / NUMBERS_JSON).read_text())
121
  for p, numbers in enumerate(drawn, 1):
122
  for n in g.SIZES:
123
  name = g.task_name(p, n)
 
125
  team = numbers[:n]
126
  expected = json.loads((HERE / "tasks" / name / "tests" / "expected.json").read_text())
127
  check(expected == sorted(team), f"{name}: expected.json is not the first {n} sorted")
128
+ agents = held.get(name, {})
129
+ check(list(agents) == [f"agent-{k:03d}" for k in range(1, n + 1)],
130
+ f"{name}: numbers.json does not name agent-001 .. agent-{n:03d}")
131
+ for slot, (agent, number) in enumerate(zip(agents, team, strict=False), 1):
132
+ check(read_words(agents[agent]) == number,
133
+ f"{name}: {agent} does not hold slot {slot}'s number")
 
 
134
  check({p.name for p in (HERE / "tasks").iterdir()} == names, "tasks/ has other folders")
135
+ check(set(held) == names, "numbers.json has other teams")
136
 
137
 
138
  def grade(task: Path, answer: bytes | None = None, cheat=None) -> int:
 
324
  if p.is_file() and answer in p.read_text()}
325
  check(holders == {"tests/expected.json", "solution/solve.sh"},
326
  f"{task.name}: the answer is in {sorted(holders)}")
 
 
327
  check(all(len(v) == 1 for v in by_size.values()),
328
  "an instruction or task.toml differs between problems of one team size")
329
+ listed = {p.name for p in (HERE / "resources").iterdir() if p.name != "__pycache__"}
330
+ check(listed == RESOURCE_FILES, f"resources/ holds {sorted(listed ^ RESOURCE_FILES)}")
331
 
332
 
333
+ def holds(text: str, words) -> set[str]:
334
+ """The number words found in `text` as whole words ("seven" is not in "seventy-seven")."""
335
+ return {w for w in words if re.search(rf"(?<![A-Za-z-]){re.escape(w)}(?![A-Za-z-])", text)}
336
+
337
+
338
+ def private_number():
339
+ """resources/private_number.py, as Flock's worker loads it (by path)."""
340
+ import importlib.util
341
+
342
+ spec = importlib.util.spec_from_file_location("_s3_private_number",
343
+ HERE / "resources" / "private_number.py")
344
+ module = importlib.util.module_from_spec(spec)
345
+ spec.loader.exec_module(module)
346
+ return module
347
+
348
+
349
+ def check_resource() -> int:
350
+ """private_number binds each agent's own number and nothing else, for every task and
351
+ agent; returns how many bindings it checked."""
352
+ module, held = private_number(), json.loads((HERE / NUMBERS_JSON).read_text())
353
+ checked = 0
354
+ with tempfile.TemporaryDirectory() as d:
355
+ for task, agents in held.items():
356
+ resource = module.Resource({"team": task}, state_dir=Path(d) / task,
357
+ agents=list(agents), secrets=[])
358
+
359
+ async def lifecycle(resource=resource, d=d, task=task):
360
+ await resource.start()
361
+ exported = await resource.export(Path(d))
362
+ await resource.stop()
363
+ return exported
364
+
365
+ check(asyncio.run(lifecycle()) == {} and not any(Path(d).iterdir()),
366
+ f"{task}: the resource exports something")
367
+ check(not holds(json.dumps(resource.metadata), set(agents.values())),
368
+ f"{task}: the resource's metadata holds a number")
369
+ for agent, own in agents.items():
370
+ binding = resource.bind(agent)
371
+ checked += 1
372
+ check(binding == {"env": {"PRIVATE_NUMBER": own}},
373
+ f"{task}: {agent}'s binding is {binding}")
374
+ others = {w for w in agents.values() if w != own}
375
+ check(not holds(json.dumps(binding), others),
376
+ f"{task}: {agent}'s binding holds a teammate's number")
377
+ refused = {
378
+ "a team of the wrong size": ({"team": "agg-p01-n08"}, [f"agent-{k:03d}" for k in (1, 2)]),
379
+ "an unknown task": ({"team": "agg-p99-n04"}, ["agent-001"]),
380
+ "no task": ({}, ["agent-001"]),
381
+ "an unknown option": ({"team": "agg-p01-n01", "numbers": [1]}, ["agent-001"]),
382
+ }
383
+ for what, (options, agents) in refused.items():
384
+ try:
385
+ module.Resource(options, state_dir=None, agents=agents, secrets=[])
386
+ check(False, f"the resource takes {what}")
387
+ except ValueError:
388
+ pass
389
+ resource = module.Resource({"team": "agg-p01-n02"}, state_dir=None,
390
+ agents=["agent-001", "agent-002"], secrets=[])
391
+ try:
392
+ resource.bind("agent-003")
393
+ check(False, "the resource binds an agent that isn't on the team")
394
+ except ValueError:
395
+ pass
396
+ return checked
397
+
398
+
399
+ # Runs in the container as `python3 -c PROBE_PY <base64 config>`, so it holds no number word
400
+ # itself: its own command line is searched too. In files it looks for the teammates' hyphenated
401
+ # number words (a bare single-digit word is in many system files) and the answer.
402
+ PROBE_PY = r"""
403
+ import base64, json, os, re, sys
404
+
405
+ cfg = json.loads(base64.b64decode(sys.argv[1]))
406
+ own, others, answer = cfg["own"], cfg["others"], cfg["answer"]
407
+ needles = [w for w in others if "-" in w] + [answer, answer.replace(" ", "")]
408
+
409
+
410
+ def whole(word, text):
411
+ return re.search(r"(?<![A-Za-z-])" + re.escape(word) + r"(?![A-Za-z-])", text)
412
+
413
+
414
+ def search(found_in):
415
+ found = []
416
+ for top, dirs, names in os.walk("/"):
417
+ if top == "/":
418
+ dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev", "logs")]
419
+ for name in names:
420
+ path = os.path.join(top, name)
421
+ try:
422
+ if os.path.islink(path) or not os.path.isfile(path):
423
+ continue
424
+ if os.path.getsize(path) > 20 << 20:
425
+ continue
426
+ with open(path, "rb") as stream:
427
+ text = stream.read().decode("utf-8", "ignore")
428
+ except OSError:
429
+ continue
430
+ if any(x in text for x in found_in):
431
+ found.append(path)
432
+ return found
433
+
434
+
435
+ out = {"visible": [d for d in ("/tests", "/solution") if os.path.exists(d)],
436
+ "files": search(needles), "env": [], "cmdline": [], "own_env": [], "processes": 0}
437
+ for pid in os.listdir("/proc"):
438
+ if not pid.isdigit():
439
+ continue
440
+ try:
441
+ with open(f"/proc/{pid}/environ", "rb") as stream:
442
+ env = stream.read().decode("utf-8", "ignore").split("\0")
443
+ with open(f"/proc/{pid}/cmdline", "rb") as stream:
444
+ cmd = stream.read().decode("utf-8", "ignore").replace("\0", " ")
445
+ except OSError:
446
+ continue
447
+ out["processes"] += 1
448
+ for entry in env:
449
+ key, _, value = entry.partition("=")
450
+ if any(whole(w, value) for w in others):
451
+ out["env"].append(f"{pid}:{key}")
452
+ if value == own:
453
+ out["own_env"].append(f"{pid}:{key}")
454
+ if any(whole(w, cmd) for w in others):
455
+ out["cmdline"].append(f"{pid}:{cmd[:80]}")
456
+ os.makedirs("/app", exist_ok=True)
457
+ with open("/app/answer.json", "w") as stream:
458
+ stream.write(answer)
459
+ out["control"] = search([answer]) # the same search finds the answer once it is written
460
+ print("PROBE " + json.dumps(out))
461
  """
462
  # What a cheating agent leaves for the verifier, before the tests arrive
463
  FAKE_JSON_SH = "printf 'def loads(*args, **kwargs):\\n return [1]\\n'"
 
480
  from harbor.agents.base import BaseAgent
481
 
482
  class Probe(BaseAgent):
483
+ """No model. `mode` answer: with exactly the environment `private_number` binds for
484
+ its agent (`env`, as Flock's Pi runs with it), looks around the container as that agent
485
+ could while it works, writes `probe.json` in its logs dir on the host, then the answer
486
+ for the verifier. Any other mode: leaves that cheat (CHEATS) instead."""
487
 
488
+ def __init__(self, *args, mode="answer", env=None, own="", others=(), answer="",
489
  **kwargs):
490
  super().__init__(*args, **kwargs)
491
+ self.mode, self.bound, self.answer = mode, env or {}, answer
492
+ self.own, self.others = own, list(others)
493
 
494
  @staticmethod
495
  def name() -> str:
496
  return "s3-aggregation-probe"
497
 
498
  def version(self) -> str:
499
+ return "3"
500
 
501
  async def setup(self, environment) -> None:
502
  pass
 
507
  (self.logs_dir / "probe.json").write_text(json.dumps(
508
  {"return_code": result.return_code, "cheat": CHEATS[self.mode]}))
509
  return
510
+ # the teammates' numbers travel base64-encoded: a copy of the command in the
511
+ # container would otherwise hold them
512
+ encoded = base64.b64encode(json.dumps(
513
+ {"own": self.own, "others": self.others, "answer": self.answer}).encode()).decode()
514
+ result = await environment.exec(f"python3 -c {shlex.quote(PROBE_PY)} {encoded}",
515
+ env=self.bound, timeout_sec=600)
516
+ line = next((x for x in (result.stdout or "").splitlines()
517
+ if x.startswith("PROBE ")), None)
518
+ found = json.loads(line.removeprefix("PROBE ")) if line else {}
519
  (self.logs_dir / "probe.json").write_text(json.dumps({
520
+ "return_code": result.return_code, **found,
521
+ "instruction_holds": sorted(holds(instruction, [self.own, *self.others])),
 
 
 
 
522
  }, indent=1))
523
  except ImportError: # `--env none` needs no Harbor
524
  Probe = None
525
 
526
 
527
+ async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict,
528
+ name: str = "") -> tuple[dict | None, dict]:
529
  """One Trial of PROBE_TASK with the probe in `mode`: (its probe.json, rewards and error)."""
530
  from harbor.models.trial.config import (
531
  AgentConfig,
 
540
  if ":" in env else
541
  EnvironmentConfig(type=env, kwargs=sandbox if env == "hf-sandbox" else {}))
542
  config = TrialConfig(
543
+ task=TaskConfig(path=HERE / "tasks" / PROBE_TASK), trial_name=f"probe-{name or mode}",
544
  trials_dir=jobs, environment=environment,
545
  agent=AgentConfig(import_path="__main__:Probe", kwargs={"mode": mode, **kwargs}))
546
  result = await (await Trial.create(config)).run()
 
552
 
553
 
554
  async def check_trials(env: str, jobs: Path) -> dict:
555
+ task = HERE / "tasks" / PROBE_TASK
556
+ team = json.loads((HERE / NUMBERS_JSON).read_text())[PROBE_TASK]
557
  answer = (task / "tests" / "expected.json").read_text().strip()
558
+ resource = private_number().Resource({"team": PROBE_TASK}, state_dir=None,
559
+ agents=list(team), secrets=[])
560
+ probes = {agent: {"env": resource.bind(agent)["env"], "own": own, "answer": answer,
561
+ "others": sorted({w for w in team.values() if w != own})}
562
+ for agent, own in team.items()}
563
+ gate = asyncio.Semaphore(10) # sandboxes at once
564
+
565
+ async def one(mode, kwargs, name=""):
566
+ async with gate:
567
+ return await run_trial(env, jobs, mode, kwargs, name)
568
+
569
  runs = await asyncio.gather(
570
+ *(one("answer", kwargs, agent) for agent, kwargs in probes.items()),
571
+ *(one(mode, {}) for mode in CHEATS))
572
+ report = {}
573
+ for (agent, kwargs), (probe, graded) in zip(probes.items(), runs[:len(probes)], strict=True):
574
+ what = f"Trial {agent}"
575
+ ran = probe is not None and probe.get("return_code") == 0 and "files" in probe
576
+ check(ran, f"{what}: the probe did not run ({graded['error']})")
577
+ if ran:
578
+ check(not probe["visible"], f"{what}: visible while the agent works: "
579
+ f"{probe['visible']}")
580
+ check(not probe["files"], f"{what}: files hold a teammate's number or the answer: "
581
+ f"{probe['files']}")
582
+ check(not probe["env"], f"{what}: a process's environment holds a teammate's "
583
+ f"number: {probe['env']}")
584
+ check(not probe["cmdline"], f"{what}: a command line holds a teammate's number: "
585
+ f"{probe['cmdline']}")
586
+ check(not probe["instruction_holds"],
587
+ f"{what}: the instruction holds {probe['instruction_holds']}")
588
+ check(any(x.endswith(":PRIVATE_NUMBER") for x in probe["own_env"]),
589
+ f"{what}: its own number is not in its environment ({probe['own_env']})")
590
+ check("/app/answer.json" in probe["control"],
591
+ f"{what}: the search did not find the written answer ({probe['control']})")
592
+ check(graded["rewards"] == {"reward": 1.0},
593
+ f"{what}: the verifier gave the answer {graded['rewards']} ({graded['error']})")
594
+ report[agent] = {"own_env": probe and probe.get("own_env"),
595
+ "processes": probe and probe.get("processes"),
596
+ "teammates": len(kwargs["others"]), **graded}
597
+ for mode, (left, result) in zip(CHEATS, runs[len(probes):], strict=True):
598
  check(left is not None and left["return_code"] == 0, f"Trial: cheat {mode} not left")
599
  check(result["rewards"] == {"reward": 0.0},
600
  f"Trial: cheat {mode} gave {result['rewards']} ({result['error']})")
 
602
  return report
603
 
604
 
605
+ def texts(message: dict) -> str:
606
+ return "\n".join(part.get("text", "") for part in message.get("content") or []
607
+ if isinstance(part, dict))
608
+
609
+
610
+ def check_run(run: Path) -> dict:
611
+ """A Flock run of one team (a local run's `.flock/<swarm>-<time>/`): no prompt Flock gave an
612
+ agent holds a number; the first output in which an agent sees a teammate's number is a board
613
+ read (or a wake-up that quotes the board), and the first post holding each number is its
614
+ owner's; each agent read its own number from its environment."""
615
+ spec = json.loads((run / "run.json").read_text())["spec"]
616
+ harbor = next(t["harbor"] for t in spec["types"].values() if t.get("harbor"))
617
+ task = harbor["config"]["task"]["selector"]
618
+ team = json.loads((HERE / NUMBERS_JSON).read_text())[task]
619
+ words = set(team.values())
620
+ boards = sorted(run.rglob("resources/message_board/board.jsonl"))
621
+ check(len(boards) == 1, f"run {run.name}: {len(boards)} board exports")
622
+ posts = sorted((json.loads(x)["message"] for b in boards[:1]
623
+ for x in b.read_text().splitlines() if x.strip()),
624
+ key=lambda m: m["created_at"])
625
+ first = {}
626
+ for post in posts:
627
+ for word in holds(post["body"], words):
628
+ first.setdefault(word, post["sender"]["external_id"])
629
+ for word, who in first.items():
630
+ check(team.get(who) == word, f"run {run.name}: {word} was first posted by {who}")
631
+ report = {"task": task, "posts": len(posts), "first_posts": first}
632
+ for agent, own in team.items():
633
+ path = run / "agents" / "_sessions" / f"{agent}.jsonl"
634
+ if not path.is_file():
635
+ check(False, f"run {run.name}: no event stream for {agent}")
636
+ continue
637
+ others, seen, calls, prompts, read_own = words - {own}, set(), {}, 0, False
638
+ for line in path.read_text().splitlines():
639
+ event = json.loads(line) if line.strip() else {}
640
+ message = event.get("message") or {}
641
+ if event.get("type") != "message":
642
+ continue
643
+ role, text = message.get("role"), texts(message)
644
+ if role == "assistant":
645
+ for part in message.get("content") or []:
646
+ if isinstance(part, dict) and part.get("type") == "toolCall":
647
+ calls[part.get("id")] = json.dumps(part.get("arguments") or {})
648
+ elif role in ("system", "user"):
649
+ if role == "system" or prompts == 0: # what Flock and the task tell the agent
650
+ check(not holds(text, words),
651
+ f"run {agent}: its {role} prompt holds {sorted(holds(text, words))}")
652
+ else: # a later prompt may quote the board (a wake-up on a mention)
653
+ seen |= holds(text, others)
654
+ prompts += role == "user"
655
+ elif role == "toolResult":
656
+ command = calls.get(message.get("toolCallId"), "")
657
+ new = holds(text, others) - seen
658
+ check(not new or "message_board" in command,
659
+ f"run {agent}: first saw {sorted(new)} in the output of {command[:120]}")
660
+ seen |= new
661
+ read_own |= own in holds(text, {own}) and "message_board" not in command
662
+ check(read_own, f"run {agent}: never read its own number")
663
+ report[agent] = {"saw": len(seen), "read_own": read_own}
664
+ return report
665
+
666
+
667
  def main() -> int:
668
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
669
  parser.add_argument("--env", default="hf-sandbox",
670
  help="Harbor environment type or import path for the Trials; none: skip")
671
  parser.add_argument("--jobs-dir", type=Path, default=None,
672
  help="keep the Trials' files here (default: a temporary directory)")
673
+ parser.add_argument("--run", type=Path, action="append", default=[],
674
+ help="also check a Flock run of a team (a local run's directory)")
675
  args = parser.parse_args()
676
  check_generator()
677
  print(f"1. generator: {len(failures)} failures")
 
681
  before = len(failures)
682
  check_files()
683
  print(f"3. no-cheat (files): {len(failures) - before} failures")
684
+ before = len(failures)
685
+ bindings = check_resource()
686
+ print(f"4. no-cheat (resource): {len(failures) - before} failures; {bindings} bindings")
687
  if args.env != "none":
688
  before = len(failures)
689
  with tempfile.TemporaryDirectory() as d:
690
  jobs = args.jobs_dir or Path(d)
691
  jobs.mkdir(parents=True, exist_ok=True)
692
  report = asyncio.run(check_trials(args.env, jobs))
693
+ print(f"5. no-cheat (Trials on {args.env}, {PROBE_TASK}): {len(failures) - before} "
694
  f"failures; {json.dumps(report)}")
695
+ for run in args.run:
696
+ before = len(failures)
697
+ report = check_run(run)
698
+ print(f"6. no-cheat (Flock run {run.name}): {len(failures) - before} failures; "
699
+ f"{json.dumps(report)}")
700
  for failure in failures:
701
  print("FAIL:", failure)
702
  print("all checks passed" if not failures else f"{len(failures)} checks failed")
eval/metrics.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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), so a row never
17
+ 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 team and the task come from
21
+ its `experiment/spec.yaml`, each agent's tokens from its Trials' results (no reasoning split),
22
+ and the run's span from its Trials. The board may hold earlier runs' messages (a reused Space):
23
+ only those posted within the run's span count. `EXTRAS` takes per-environment metrics (s3-maze:
24
+ moves per agent and room overlap, from the move logs its verifier copies next to the reward).
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import re
30
+ import sys
31
+ from collections import Counter
32
+ from collections.abc import Callable
33
+ from datetime import datetime
34
+ from pathlib import Path
35
+
36
+ import yaml
37
+
38
+ TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning")
39
+
40
+
41
+ def load_json(path: Path):
42
+ return json.loads(path.read_text(encoding="utf-8"))
43
+
44
+
45
+ def epoch(value) -> float:
46
+ return float(value) if isinstance(value, int | float) else datetime.fromisoformat(
47
+ value).timestamp()
48
+
49
+
50
+ def bundle(run_dir: Path) -> dict | None:
51
+ """A local run's run.json; None for a Slurm run (its controller's run.json, in the bucket,
52
+ holds neither the spec nor the agents)."""
53
+ path = run_dir / "run.json"
54
+ doc = load_json(path) if path.is_file() else {}
55
+ return doc if "spec" in doc and "agents" in doc else None
56
+
57
+
58
+ def all_trials(run_dir: Path) -> dict[str, list[Path]]:
59
+ """Each agent's Trial directories, oldest first: `<agent>/trials/<swarm>-<agent>-t<N>/`
60
+ (a local run's agents/_harbor/, a Slurm run's results/<swarm>/), one per Trial name."""
61
+ found: dict[str, dict[str, tuple[int, Path]]] = {}
62
+ for trial in run_dir.rglob("trials/*"):
63
+ agent = trial.parent.parent.name
64
+ m = re.fullmatch(rf"(?:.+-)?{re.escape(agent)}-t(\d+)", trial.name)
65
+ if m and trial.is_dir():
66
+ found.setdefault(agent, {}).setdefault(trial.name, (int(m[1]), trial))
67
+ return {a: [p for _, p in sorted(t.values())] for a, t in sorted(found.items())}
68
+
69
+
70
+ def results(trials: list[Path]) -> list[dict]:
71
+ return [load_json(t / "result.json") for t in trials if (t / "result.json").is_file()]
72
+
73
+
74
+ def reward(trials: list[Path]) -> float | None:
75
+ """The reward of the agent's latest Trial that has one."""
76
+ for trial in reversed(trials):
77
+ result = trial / "result.json"
78
+ rewards = ((load_json(result).get("verifier_result") or {}).get("rewards")
79
+ if result.is_file() else None)
80
+ if rewards and "reward" in rewards:
81
+ return float(rewards["reward"])
82
+ text = trial / "verifier" / "reward.txt"
83
+ if text.is_file() and not text.is_symlink() and text.read_text().strip():
84
+ return float(text.read_text().strip())
85
+ return None
86
+
87
+
88
+ def bundle_tokens(agent: dict) -> dict[str, int]:
89
+ usage = dict.fromkeys(TOKEN_FIELDS, 0)
90
+ for by_model in (agent.get("tokens") or {}).values():
91
+ for key in TOKEN_FIELDS:
92
+ usage[key] += int(by_model.get(key) or 0)
93
+ return usage
94
+
95
+
96
+ def trial_tokens(trials: list[Path]) -> dict[str, int]:
97
+ """Harbor's counts: its input includes the cached tokens."""
98
+ usage = dict.fromkeys(TOKEN_FIELDS, 0)
99
+ for result in results(trials):
100
+ agent = result.get("agent_result") or {}
101
+ cached = int(agent.get("n_cache_tokens") or 0)
102
+ usage["input"] += int(agent.get("n_input_tokens") or 0) - cached
103
+ usage["cache_read"] += cached
104
+ usage["output"] += int(agent.get("n_output_tokens") or 0)
105
+ return usage
106
+
107
+
108
+ def board(run_dir: Path, start: float, end: float) -> tuple[list[dict], dict[int, dict], bool]:
109
+ """(the run's messages, oldest first, channels by id, whether an export was found)."""
110
+ messages, channels, found = {}, {}, False
111
+ for export in run_dir.rglob("resources/message_board/board.jsonl"):
112
+ found = True
113
+ listing = export.with_name("channels.json")
114
+ for channel in load_json(listing) if listing.is_file() else []:
115
+ channels[channel["id"]] = channel
116
+ for line in export.read_text(encoding="utf-8").splitlines():
117
+ if line.strip():
118
+ record = json.loads(line)
119
+ message = record["message"] | {"channel_id": record["channel_id"]}
120
+ if start <= epoch(message["created_at"]) <= end:
121
+ messages[message["id"]] = message
122
+ return sorted(messages.values(), key=lambda m: m["id"]), channels, found
123
+
124
+
125
+ def sender(message: dict) -> str | None:
126
+ return (message.get("sender") or {}).get("external_id")
127
+
128
+
129
+ def edges(messages: list[dict], channels: dict[int, dict], team: list[str]) -> set[tuple]:
130
+ """(sender, receiver) for each teammate a message mentions or is sent to directly."""
131
+ members = set(team)
132
+ out = set()
133
+ for message in messages:
134
+ source = sender(message)
135
+ if source not in members:
136
+ continue
137
+ targets = {m.get("external_id") for m in message.get("mentions") or []}
138
+ channel = channels.get(message["channel_id"]) or {}
139
+ if channel.get("kind") in ("dm", "private"):
140
+ inside = {m.get("external_id") for m in channel.get("members") or []} & members
141
+ if len(inside) == 2 and source in inside: # a DM, or a private channel of the two
142
+ targets |= inside
143
+ out |= {(source, target) for target in targets & members if target != source}
144
+ return out
145
+
146
+
147
+ def centralization(graph: set[tuple], team: list[str]) -> float | None:
148
+ """Appendix M: sum over agents of (k* - k_j) / (N - 1)^2, k_j agent j's in-degree and k*
149
+ the largest: 0 when everyone receives from as many teammates, 1 when one agent receives
150
+ from everyone and no one else from anyone. None for a team of one."""
151
+ n = len(team)
152
+ if n < 2:
153
+ return None
154
+ degree = Counter(target for _, target in graph)
155
+ k = [degree[a] for a in team]
156
+ return sum(max(k) - kj for kj in k) / (n - 1) ** 2
157
+
158
+
159
+ def reciprocity(graph: set[tuple]) -> float | None:
160
+ """Appendix M: the fraction of edges whose reverse edge exists. None without edges."""
161
+ return sum((b, a) in graph for a, b in graph) / len(graph) if graph else None
162
+
163
+
164
+ # Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields.
165
+ # s3-maze adds moves per agent and room overlap, (V - U) / V, from its move logs here.
166
+ EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = []
167
+
168
+
169
+ def local_run(run: dict) -> dict:
170
+ """What a local bundle says about the run."""
171
+ harbor = next((t.get("harbor") or {} for t in run["spec"]["types"].values()), {})
172
+ task = (harbor.get("config") or {}).get("task") or {}
173
+ agents = sorted(run["agents"], key=lambda a: a["name"])
174
+ return {"swarm": run.get("swarm"), "task": task, "team": [a["name"] for a in agents],
175
+ "start": epoch(run["started_at"]), "end": epoch(run["ended_at"]),
176
+ "stop_reason": run.get("stop_reason"), "duration_s": run.get("duration_s"),
177
+ "cost_usd": (run.get("totals") or {}).get("cost_usd"),
178
+ "tokens": {a["name"]: bundle_tokens(a) for a in agents},
179
+ "turns": {a["name"]: a.get("turns_completed") for a in agents}}
180
+
181
+
182
+ def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict:
183
+ """What a Slurm run's directory says: its spec (`flock init` copies the experiment) and the
184
+ Trials the workers kept."""
185
+ path = run_dir / "experiment" / "spec.yaml"
186
+ spec = yaml.safe_load(path.read_text()) if path.is_file() else {}
187
+ agents = spec.get("agents") or {}
188
+ if spec.get("naming") == "consecutive-id" and isinstance(agents.get("count"), int):
189
+ team = [f"agent-{k:03d}" for k in range(1, agents["count"] + 1)]
190
+ else:
191
+ team = list(trials)
192
+ times = [(epoch(r["started_at"]), epoch(r["finished_at"]))
193
+ for ts in trials.values() for r in results(ts)
194
+ if r.get("started_at") and r.get("finished_at")]
195
+ start, end = (min(t[0] for t in times), max(t[1] for t in times)) if times else (0, 0)
196
+ names = {r.get("task_name") for ts in trials.values() for r in results(ts)}
197
+ task = spec.get("task") or {"selector": next((n.split("/")[-1] for n in names if n), None)}
198
+ swarm = next((t.name.removesuffix(f"-{a}-t{t.name.rsplit('-t', 1)[1]}")
199
+ for a, ts in trials.items() for t in ts), spec.get("name"))
200
+ return {"swarm": swarm, "task": task, "team": team, "start": start, "end": end,
201
+ "stop_reason": None, "duration_s": round(end - start, 1) if times else None,
202
+ "cost_usd": None, "tokens": {a: trial_tokens(trials.get(a, [])) for a in team},
203
+ "turns": dict.fromkeys(team)}
204
+
205
+
206
+ def row(run_dir: Path) -> dict:
207
+ trials = all_trials(run_dir)
208
+ run = bundle(run_dir)
209
+ info = local_run(run) if run is not None else slurm_run(run_dir, trials)
210
+ team = info["team"]
211
+ messages, channels, exported = board(run_dir, info["start"], info["end"])
212
+ posts = Counter(sender(m) for m in messages)
213
+ graph = edges(messages, channels, team)
214
+ per_agent, missing = {}, []
215
+ for name in team:
216
+ value = reward(trials.get(name, []))
217
+ if value is None:
218
+ missing.append(f"reward: {name}")
219
+ per_agent[name] = {"reward": value, "tokens": info["tokens"][name],
220
+ "posts": posts[name], "turns": info["turns"][name]}
221
+ if not exported:
222
+ missing.append("board export")
223
+ rewards = [a["reward"] for a in per_agent.values() if a["reward"] is not None]
224
+ task = info["task"]
225
+ out = {
226
+ "run": run_dir.name,
227
+ "swarm": info["swarm"],
228
+ "task": task.get("selector"),
229
+ "dataset": task.get("repo"),
230
+ "revision": task.get("revision"),
231
+ "agents": len(team),
232
+ "stop_reason": info["stop_reason"],
233
+ "duration_s": info["duration_s"],
234
+ "success": any(r == 1 for r in rewards) if rewards else None,
235
+ "rewards": {name: a["reward"] for name, a in per_agent.items()},
236
+ "tokens": {key: sum(a["tokens"][key] for a in per_agent.values())
237
+ for key in TOKEN_FIELDS},
238
+ "cost_usd": info["cost_usd"],
239
+ "posts": sum(posts[name] for name in team),
240
+ "other_posts": sum(n for who, n in posts.items() if who not in team),
241
+ "per_agent": per_agent,
242
+ "edges": sorted([a, b] for a, b in graph),
243
+ "centralization": centralization(graph, team),
244
+ "reciprocity": reciprocity(graph),
245
+ "missing": missing,
246
+ }
247
+ for extra in EXTRAS:
248
+ out |= extra(run_dir, team, trials)
249
+ return out
250
+
251
+
252
+ def main(argv=None) -> int:
253
+ parser = argparse.ArgumentParser(description="One row per team (JSON lines) from s³ runs.")
254
+ parser.add_argument("run_dirs", nargs="+", type=Path)
255
+ parser.add_argument("--out", type=Path, help="append the rows here (default: stdout)")
256
+ args = parser.parse_args(argv)
257
+ rows = [json.dumps(row(d)) for d in args.run_dirs]
258
+ if args.out:
259
+ with args.out.open("a", encoding="utf-8") as f:
260
+ f.write("".join(r + "\n" for r in rows))
261
+ else:
262
+ print("\n".join(rows))
263
+ return 0
264
+
265
+
266
+ if __name__ == "__main__":
267
+ sys.exit(main())
flock/spec.template.yaml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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), this dataset's
3
+ # revision (REVISION) and resources folder (RESOURCES), 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-001, ...: resources/numbers.json's names
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 # team.py: agg-pPP-nNN
15
+ revision: REVISION # team.py: --revision, default the Hub's head
16
+ agents:
17
+ count: 1 # team.py: N
18
+ resources_dir: RESOURCES # team.py: this checkout's resources/
19
+ resources:
20
+ # Each agent's own number in its environment (PRIVATE_NUMBER), and no one else's.
21
+ private_number:
22
+ team: TEAM
23
+ # The board rules: identical for every eval run, since they shape how agents talk.
24
+ # Enforced on docker and podman (each agent's rule proxy); on HF Sandboxes there is no proxy,
25
+ # so they are not enforced and each Trial records a message_board.warning event.
26
+ message_board:
27
+ channels: [general]
28
+ wake: [mention, thread]
29
+ rules:
30
+ max_len: 1000
31
+ min_post_gap: 5s
32
+ max_posts: 40
33
+ workers:
34
+ agents_per_worker: 1 # team.py: N, the whole team on one worker and board
35
+ turn_timeout: 10m
36
+ loop:
37
+ prompt: Continue the task until it is complete, then stop.
38
+ every: turn_end
39
+ while:
40
+ until: 15m
41
+ max_rounds: 4
42
+ limits:
43
+ run_timeout_seconds: 1200
44
+ agent_max_turns: 60
45
+
46
+ # Where the team runs: team.py merges one of these into the spec (--where).
47
+ where:
48
+ # Local docker, with the controller, the one worker and the board on this machine.
49
+ docker:
50
+ environment:
51
+ backend: docker
52
+ # HF Sandboxes (cpu-basic), with the controller and the one worker on this machine and the
53
+ # board on a Space. Give each team a new Space and delete it afterwards: the instruction has no
54
+ # run tag, so an earlier team's posts on a reused board would read as this team's.
55
+ sandbox:
56
+ namespace: ${SANDBOX_NAMESPACE:-} # bills the sandboxes; unset: HF_TOKEN's account
57
+ environment:
58
+ backend: hf-sandbox
59
+ resources:
60
+ message_board:
61
+ space_id: ${BOARD_SPACE:-s3-TEAM} # bare name: HF_TOKEN's account
62
+ private: false # a private Space's gate needs HF_TOKEN in every sandbox
63
+ # The HF cluster: a Slurm worker running the team in rootless podman, with a local board on
64
+ # that worker (a new one each run). Results reach <run dir>/results/ (Flock's docs/slurm.md).
65
+ cluster:
66
+ namespace: ${NAMESPACE}
67
+ bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name>
68
+ compute:
69
+ kind: slurm
70
+ partition: ${SLURM_PARTITION:-} # the cluster profile's
71
+ cpus: ${WORKER_CPUS:-16}
72
+ mem: ${WORKER_MEM:-30G} # at most 2000 MB per CPU on hopper-cpu
73
+ time: '3:00:00'
74
+ environment:
75
+ backend: podman
flock/sweep/README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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) |
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 Flock's checkout (with its Slurm results, huggingface/flock#122, so each Trial's grading
22
+ reaches the run directory), with this dataset downloaded on the shared disk at the revision
23
+ the teams pin (`DS` below), since the workers read `registries.conf` from it. Two model servers,
24
+ one GPU each: one B200 is saturated by about 50 agents at a time (the 27B grid needs about 70M
25
+ prompt and 2M generated tokens), and a job's time limit is 3 hours.
26
+
27
+ ```sh
28
+ hf download HuggingFaceSwarms/s3-aggregation --repo-type dataset --revision <sha> --local-dir $DS
29
+ sbatch -p hopper-b200 -o .flock/s3-sweep/vllm-%j.log $DS/flock/sweep/serve-vllm.sbatch
30
+ sbatch -p hopper-b200 --export=ALL,PORT=8001 -o .flock/s3-sweep/vllm-%j.log $DS/flock/sweep/serve-vllm.sbatch
31
+ # each log ends with: serving Qwen/Qwen3.5-27B at http://<node address>:<port>/v1
32
+ uv run python $DS/flock/sweep/sweep.py --urls http://<node 1>:8000/v1,http://<node 2>:8001/v1 \
33
+ --revision <sha> --parallel 12 --bucket <you>/s3-aggregation-grid \
34
+ --dataset HuggingFaceSwarms/s3-aggregation-results --prefix grid
35
+ scancel -n s3-sweep-vllm
36
+ ```
37
+
38
+ The 2B grid is the same with `--export=ALL,MODEL=Qwen/Qwen3.5-2B` for the server, and
39
+ `--model Qwen/Qwen3.5-2B --tag q2b-` and its own bucket and `--prefix` for the driver. Its
40
+ agents run far longer, so more teams are in flight at once: `--max-worker-cpus 8` keeps their
41
+ workers small enough to be scheduled, except at N = 16, whose 2B teams need 16 CPUs (30 GB) and
42
+ run from a second driver (`--agents 16`) on the same root. Then plot both:
43
+ `plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>`.
44
+
45
+ Each team is team.py's cluster spec (`--where cluster`) with the model on the servers' URLs
46
+ (each agent calls one, by rendezvous hashing): `compute: slurm`, one worker on hopper-cpu
47
+ running the team in rootless podman with a local board, sized to the team (a CPU per agent, at
48
+ least 4). The board rules, loop and limits are the template's at every N. sweep.py inits and
49
+ launches a team, waits until its loop is done and its agents are idle, releases it
50
+ (`flock stop --release`: each Trial is graded as the worker drains, and the results land in the
51
+ run directory), and appends metrics.py's row with the wall time. The run state goes to a
52
+ private bucket (a new one per grid: a swarm's name is used once in a bucket), the run
53
+ directories (spec, results, logs; never `run.env`) to the private dataset, and plot.py runs at
54
+ the end.
55
+
56
+ **A run counts only when it is complete**: one worker incarnation (until flock#121 is fixed, a
57
+ relaunched or preempted worker overwrites results), its controller kept, every agent's reward
58
+ and the board export. hopper-cpu is spot capacity, so reclaims take workers and controllers
59
+ mid-run, and a missing reward means the verifier never ran. A run that doesn't count goes to
60
+ `rows-discarded.jsonl` and the team runs again as `<task>-rK` (up to 5 times); its row records
61
+ the reruns.
62
+
63
+ **Resuming.** The same command resumes: a team with a row is skipped, a team a stopped driver
64
+ launched is adopted (waited for, released and scored, or scored from what it left when its
65
+ controller is gone), and one that never launched runs again. Stopping the driver to add a server
66
+ is safe: in-flight teams keep running and are adopted.
67
+
68
+ ## How it differs from the paper's Figure 5
69
+
70
+ | | s³ (Figure 5, top row) | here |
71
+ | --- | --- | --- |
72
+ | 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 |
73
+ | 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 |
74
+ | Messages | to one teammate or broadcast | posts on a board every agent reads; private channels possible |
75
+ | Private number | in the agent's prompt | in its environment (`PRIVATE_NUMBER`, from `resources/private_number.py`), read with a shell command |
76
+ | Names | sampled from `agent_1`..`agent_64`, teammates in shuffled order | `agent-001`..`agent-00N`, in order |
77
+ | 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 |
78
+ | 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 |
79
+ | 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 |
80
+ | 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 |
81
+ | Intervals | mean ± SE across six seeds | 95% Wilson intervals across problems |
82
+ | 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 |
flock/sweep/failures.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
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 `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
+ """
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_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
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_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":
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 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")
129
+ print("\n".join(lines))
130
+ return 0
131
+
132
+
133
+ if __name__ == "__main__":
134
+ raise SystemExit(main())
flock/sweep/plot.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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³
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 flock: 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())
flock/sweep/registries.conf ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
flock/sweep/serve-vllm.sbatch ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+ srun --overlap --container-image="$IMAGE" --no-container-mount-home \
18
+ --container-mounts="/scratch/$USER/hf:/hf" --container-env=HF_HOME \
19
+ vllm serve "$MODEL" --port "$PORT" \
20
+ --enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser qwen3 &
21
+ until curl -sf -o /dev/null "localhost:$PORT/v1/models"; do
22
+ sleep 10
23
+ kill -0 $! 2>/dev/null || { echo "vLLM exited during startup"; exit 1; }
24
+ done
25
+ echo "serving $MODEL at http://$(hostname -I | awk '{print $1}'):$PORT/v1"
26
+ wait
flock/sweep/setaside.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 controller's node was reclaimed (spot) mid-run;
9
+ - the task image couldn't be pulled (Docker Hub's unauthenticated limit), so the Trials never
10
+ started;
11
+ - the verifier timed out (Harbor's 60 s) on a loaded worker;
12
+ - the run was cancelled before its Trials were graded (the driver stopped and its in-flight
13
+ teams cancelled, e.g. to switch the workers to the image mirror).
14
+ """
15
+
16
+ import json
17
+ import re
18
+ import sys
19
+ from collections import Counter
20
+ from pathlib import Path
21
+
22
+
23
+ def reason(row: dict, run_dir: Path) -> str:
24
+ logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*")
25
+ if p.is_file()} if (run_dir / "logs").is_dir() else {}
26
+ workers = " ".join(v for k, v in logs.items() if "-agent-w" in k)
27
+ controllers = " ".join(v for k, v in logs.items() if k.startswith("flock-ctl-"))
28
+ if (row.get("incarnations") or 0) > 1:
29
+ if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers):
30
+ return "worker relaunched after running out of memory (flock#121's case)"
31
+ return "worker relaunched after a node failure (flock#121's case)"
32
+ if "DUE TO NODE FAILURE" in controllers or row.get("outcome") == "controller lost":
33
+ return "controller's node reclaimed (spot)"
34
+ if "toomanyrequests" in workers:
35
+ return "task image not pulled (Docker Hub limit): Trials never started"
36
+ if any("VerifierTimeoutError" in p.read_text(errors="replace")
37
+ for p in run_dir.glob("results/*/agent-*/trials/*/result.json")):
38
+ return "verifier timed out (60 s) on a loaded worker"
39
+ return "cancelled before grading (driver stopped, in-flight teams cancelled)"
40
+
41
+
42
+ def main(root: Path) -> int:
43
+ attempts = {}
44
+ for line in (root / "rows-discarded.jsonl").read_text().splitlines():
45
+ row = json.loads(line)
46
+ seen = attempts.setdefault(row["run"], row) # the driver that watched it knew most
47
+ seen["incarnations"] = max(seen.get("incarnations") or 0, row.get("incarnations") or 0)
48
+ if row.get("outcome") == "controller lost":
49
+ seen["outcome"] = row["outcome"]
50
+ kept = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines()]
51
+ reasons = Counter(reason(r, root / "runs" / run) for run, r in attempts.items())
52
+ rerun = sum(r.get("reruns", 0) > 0 for r in kept)
53
+ head = (f"Attempts set aside: {len(attempts)} (rows-discarded.jsonl); "
54
+ f"teams that needed a rerun: {rerun} of {len(kept)}")
55
+ lines = [head, ""]
56
+ lines += [f"- {why}: {k}" for why, k in reasons.most_common()]
57
+ (root / "setaside.md").write_text("\n".join(lines) + "\n")
58
+ print("\n".join(lines))
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main(Path(sys.argv[1])))
flock/sweep/sweep.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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). Per team: `flock init` (a worker sized to
11
+ N), `flock launch`, wait until its loop is done and its agents are idle, `flock stop --release`
12
+ (each Trial is graded as the worker drains; the results land in the run directory), then
13
+ eval/metrics.py's row plus the wall time goes to `<root>/rows.jsonl`. Until flock#121
14
+ is fixed, a team must run on one worker incarnation (a relaunch or a preemption overwrites
15
+ results); and a spot reclaim may take its controller, or leave rewards unverified. A run that
16
+ doesn't count (why_invalid) runs again as `<task>-rK` (its row: `reruns`). A team that
17
+ has a row is skipped, so the same command resumes. At the end plot.py writes the figure, CSV
18
+ and table, and with --dataset each run directory (spec, results, logs; never run.env) goes to
19
+ that private dataset under `<prefix>/<task>/`.
20
+
21
+ Needs HF_TOKEN (or `hf auth login`): the workers clone the private task dataset and sync the
22
+ private state bucket with it. The agents get no Hub token; the vLLM server takes no key.
23
+ """
24
+
25
+ import argparse
26
+ import importlib.util
27
+ import json
28
+ import os
29
+ import re
30
+ import shutil
31
+ import subprocess
32
+ import sys
33
+ import threading
34
+ import time
35
+ from concurrent.futures import ThreadPoolExecutor
36
+ from datetime import UTC, datetime
37
+ from pathlib import Path
38
+
39
+ import yaml
40
+ from huggingface_hub import HfApi, get_token
41
+
42
+ HERE = Path(__file__).resolve().parent
43
+ REPO = Path.cwd() # Flock's checkout
44
+ MODEL = "Qwen/Qwen3.5-27B"
45
+ SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")
46
+ lock, init_lock = threading.Lock(), threading.Semaphore(4)
47
+ LOST, GONE = "controller lost", "no controller left"
48
+
49
+
50
+ def load(name: str, path: Path):
51
+ spec = importlib.util.spec_from_file_location(name, path)
52
+ module = importlib.util.module_from_spec(spec)
53
+ spec.loader.exec_module(module)
54
+ return module
55
+
56
+
57
+ team = load("team", HERE.parent / "team.py")
58
+ metrics = load("metrics", HERE.parents[1] / "eval" / "metrics.py")
59
+
60
+
61
+ def say(*parts) -> None:
62
+ with lock:
63
+ print(datetime.now(UTC).strftime("%H:%M:%S"), *parts, flush=True)
64
+
65
+
66
+ def numbers(text: str) -> list[int]:
67
+ """`1-32` or `1,3,7` -> the numbers."""
68
+ out = []
69
+ for part in text.split(","):
70
+ a, _, b = part.partition("-")
71
+ out += range(int(a), int(b or a) + 1)
72
+ return out
73
+
74
+
75
+ def flock(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess:
76
+ env = {**os.environ, "FLOCK_RUN_DIR": str(run_dir)}
77
+ env.pop("VIRTUAL_ENV", None)
78
+ return subprocess.run([str(Path(sys.executable).with_name("flock")), *args], cwd=REPO,
79
+ env=env, capture_output=True, text=True, timeout=timeout, check=False)
80
+
81
+
82
+ def write_experiment(src: Path, problem: int, n: int, name: str, urls: list[str],
83
+ model: str, revision: str) -> None:
84
+ """team.py's cluster spec at the dataset `revision`, with the sweep's model on its servers,
85
+ as swarm `name`."""
86
+ team.main(["--problem", str(problem), "--agents", str(n), "--where", "cluster",
87
+ "--revision", revision,
88
+ "--out", str(src)])
89
+ spec = yaml.safe_load((src / "spec.yaml").read_text())
90
+ spec["name"] = name
91
+ spec["model"] = model
92
+ spec["inference"] = {"urls": urls} # no key: the servers take none
93
+ (src / "spec.yaml").write_text(
94
+ f"# {spec['task']['selector']} for the scaling sweep (sweep.py): team.py's cluster spec "
95
+ f"with {model} on the sweep's servers.\n" + yaml.safe_dump(spec, sort_keys=False))
96
+
97
+
98
+ def profile(root: Path, n: int, most: int = 16) -> Path:
99
+ """A worker sized to the team: a CPU per agent (at least 4), 1900 MB per CPU (hopper-cpu
100
+ allows 2000); its podman pulls Docker Hub images through a mirror (registries.conf)."""
101
+ cpus = max(4, min(n, most)) # `most`: a big job can queue past the loop's until
102
+ path = root / "profiles" / f"n{n:02d}.env"
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ path.write_text(f"SLURM_PARTITION=hopper-cpu\nWORKER_CPUS={cpus}\nWORKER_MEM={cpus * 1900}M\n"
105
+ f"SLURM_MAX_MEM_PER_CPU_MB=2000\nVENV={REPO / '.venv'}\n"
106
+ f"CONTAINERS_REGISTRIES_CONF={HERE / 'registries.conf'}\n")
107
+ return path
108
+
109
+
110
+ def controller_state(name: str) -> str:
111
+ """The Slurm state of the run's controller job (`flock-ctl-<run>`), '' when it has none."""
112
+ out = subprocess.run(["squeue", "-h", "-n", f"flock-ctl-{name}", "-o", "%T"],
113
+ capture_output=True, text=True, check=False).stdout.split()
114
+ return out[0] if out else ""
115
+
116
+
117
+ def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
118
+ """Poll `flock status` until the loop is done and every agent is idle: 'done', or why not.
119
+ A controller that stops answering and isn't running (a spot reclaim requeued it, or it is
120
+ gone) is LOST."""
121
+ deadline, unanswered = time.monotonic() + timeout, 0
122
+ while time.monotonic() < deadline:
123
+ status = flock(run_dir, "status", task, timeout=120)
124
+ text = status.stdout
125
+ unanswered = unanswered + 1 if status.returncode != 0 else 0
126
+ if unanswered >= 3 and controller_state(task) != "RUNNING":
127
+ return LOST
128
+ if re.search(r"crashloop|launch_refused", text):
129
+ return "worker failed: " + " ".join(text.split())[:300]
130
+ if re.search(r"^loop agent: done", text, re.MULTILINE) and re.search(
131
+ rf"^agent .*\bidle:{n}\b", text, re.MULTILINE):
132
+ return "done"
133
+ time.sleep(20)
134
+ return f"not done after {timeout:.0f} s"
135
+
136
+
137
+ def attempt(args, root: Path, secrets: Path, problem: int, n: int, name: str) -> dict | None:
138
+ """One run of a team as swarm `name`: its row, or None when it could not start."""
139
+ run_dir, src = root / "runs" / name, root / "src" / name
140
+ if run_dir.exists() and (any((run_dir / "launch").glob("*.env"))
141
+ or (run_dir / "hosts" / "controller.host").exists()):
142
+ # a previous driver launched it and stopped before its row: finish it from here, or,
143
+ # with its controller gone (released, cancelled or reclaimed), score what it left
144
+ alive = bool(controller_state(name))
145
+ say(name, "adopting the run a previous driver launched" + ("" if alive else
146
+ " (no controller left)"))
147
+ return finish(args, run_dir, name, problem, n, (run_dir / "cluster.env").stat().st_mtime,
148
+ None if alive else GONE)
149
+ if run_dir.exists():
150
+ shutil.rmtree(run_dir) # init failed before: nothing ran
151
+ started = time.time()
152
+ write_experiment(src, problem, n, name, args.urls, args.model, args.revision)
153
+ log = root / "logs" / f"{name}-init.log"
154
+ log.parent.mkdir(parents=True, exist_ok=True)
155
+ for tries in range(3):
156
+ with init_lock: # a few at a time: many at once race on the bucket's write check
157
+ init = flock(run_dir, "init", str(run_dir), "--from", str(src), "--profile",
158
+ str(profile(root, n, args.max_worker_cpus)), "--secrets", str(secrets))
159
+ log.write_text(init.stdout + init.stderr)
160
+ if init.returncode == 0:
161
+ break
162
+ time.sleep(10 * (tries + 1))
163
+ else:
164
+ failed = [x for x in init.stdout.splitlines() if x.startswith("FAIL")]
165
+ say(name, "init failed 3 times:", failed or init.stdout[-300:], "(log:", log, ")")
166
+ return None
167
+ say(name, "launching")
168
+ launch = flock(run_dir, "launch", str(run_dir / "experiment"))
169
+ if launch.returncode != 0:
170
+ say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:])
171
+ return finish(args, run_dir, name, problem, n, started, "launch")
172
+ return finish(args, run_dir, name, problem, n, started)
173
+
174
+
175
+ def finish(args, run_dir: Path, name: str, problem: int, n: int, started: float,
176
+ why: str | None = None) -> dict:
177
+ """Wait for a launched team, release it (its Trials are graded) and make its row."""
178
+ why = why or wait_done(run_dir, name, n, args.team_timeout)
179
+ if why == LOST: # nothing to release: end its jobs, and the team runs again
180
+ say(name, "controller lost (spot reclaim?): cancelling its jobs")
181
+ for job in (f"flock-ctl-{name}", f"{name}-agent-w0000"):
182
+ subprocess.run(["scancel", "-n", job], check=False)
183
+ release = subprocess.CompletedProcess([], 1)
184
+ elif why == GONE: # its rewards and export are on disk, or it doesn't count
185
+ release = subprocess.CompletedProcess([], 1)
186
+ else:
187
+ say(name, "loop:", why, "- releasing")
188
+ release = flock(run_dir, "stop", name, "--release")
189
+ ended = time.time()
190
+ return metrics.row(run_dir) | {
191
+ "problem": problem, "wall_s": round(ended - started, 1), "outcome": why,
192
+ "released": release.returncode == 0,
193
+ # each launch of the worker slot writes one env file: more than one is a relaunch or a
194
+ # preemption, whose results a later incarnation overwrites (flock#121)
195
+ "incarnations": len(list((run_dir / "launch").glob("*.env"))),
196
+ "started_at": datetime.fromtimestamp(started, UTC).isoformat()}
197
+
198
+
199
+ def why_invalid(row: dict) -> str:
200
+ """Why a team's run doesn't count ('' when it does): a model result needs the run on one
201
+ worker incarnation (flock#121), its controller kept, every agent's reward and the board export.
202
+ A missing reward means the verifier never ran: the infrastructure failed, not the team."""
203
+ return "; ".join(why for why, bad in (
204
+ (f"{row.get('incarnations')} worker incarnations", row.get("incarnations") != 1),
205
+ (LOST, row.get("outcome") == LOST),
206
+ (f"missing {', '.join(row['missing'])}"[:120], bool(row["missing"]))) if bad)
207
+
208
+
209
+ def valid(row: dict) -> bool:
210
+ return not why_invalid(row)
211
+
212
+
213
+ def run_team(args, root: Path, secrets: Path, problem: int, n: int) -> dict | None:
214
+ """A team, run again (as `<task>-rK`) until it runs on one worker incarnation (flock#121)."""
215
+ task = f"{args.tag}agg-p{problem:02d}-n{n:02d}"
216
+ for reruns in range(args.max_reruns + 1):
217
+ row = attempt(args, root, secrets, problem, n, task if reruns == 0 else f"{task}-r{reruns}")
218
+ if row is None:
219
+ return None
220
+ row["reruns"] = reruns
221
+ if valid(row):
222
+ break
223
+ say(task, f"run doesn't count ({why_invalid(row)}): running it again")
224
+ with lock, (root / "rows-discarded.jsonl").open("a") as f:
225
+ f.write(json.dumps(row) + "\n")
226
+ with lock, (root / "rows.jsonl").open("a") as f:
227
+ f.write(json.dumps(row) + "\n")
228
+ say(task, f"success={row['success']} rewards={list(row['rewards'].values())} "
229
+ f"posts={row['posts']} wall={row['wall_s']} s reruns={row['reruns']} "
230
+ f"incarnations={row['incarnations']} missing={row['missing']}")
231
+ return row
232
+
233
+
234
+ def upload(root: Path, dataset: str, prefix: str) -> None:
235
+ """Each run directory's spec, results and logs, and the rows, to a private dataset; never
236
+ run.env, and nothing that holds a Hub token."""
237
+ api = HfApi()
238
+ api.create_repo(dataset, repo_type="dataset", private=True, exist_ok=True)
239
+ if not api.dataset_info(dataset).private:
240
+ raise SystemExit(f"{dataset} is public: refusing to upload")
241
+ allow = ["*.jsonl", "*.csv", "*.md", "*.png", "runs/*/experiment/**", "runs/*/results/**",
242
+ "runs/*/logs/**"]
243
+ leaks = [str(p) for p in (root / "runs").rglob("*") if p.is_file()
244
+ and not p.name.endswith(".env") and SECRET.search(p.read_text(errors="ignore"))]
245
+ if leaks:
246
+ raise SystemExit(f"refusing to upload: Hub tokens in {leaks[:5]}")
247
+ api.upload_folder(repo_id=dataset, repo_type="dataset", folder_path=root,
248
+ path_in_repo=prefix, allow_patterns=allow,
249
+ commit_message=f"s3-aggregation sweep: {prefix}")
250
+ say("uploaded", root, "to", f"{dataset}/{prefix}")
251
+
252
+
253
+ def main(argv=None) -> int:
254
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
255
+ parser.add_argument("--urls", required=True, help="the model servers, comma-separated")
256
+ parser.add_argument("--model", default=MODEL)
257
+ parser.add_argument("--revision", help="the dataset revision every team pins (default: its "
258
+ "head; this checkout's resources/ must be that revision's)")
259
+ parser.add_argument("--problems", default="1-32")
260
+ parser.add_argument("--agents", default="1,2,4,8,16")
261
+ parser.add_argument("--parallel", type=int, default=8, help="teams at once")
262
+ parser.add_argument("--team-timeout", type=float, default=2400, help="s until a release")
263
+ parser.add_argument("--max-reruns", type=int, default=5,
264
+ help="runs again of a team whose run doesn't count (why_invalid)")
265
+ parser.add_argument("--root", type=Path, default=REPO / ".flock" / "s3-sweep")
266
+ parser.add_argument("--bucket", default="lewtun/s3-aggregation-sweep",
267
+ help="private bucket for the runs' state (a new one per root: a "
268
+ "swarm's name is used once in a bucket)")
269
+ parser.add_argument("--namespace", default="lewtun")
270
+ parser.add_argument("--dataset", help="private dataset for the run directories")
271
+ parser.add_argument("--prefix", default="grid", help="folder in the dataset")
272
+ parser.add_argument("--max-worker-cpus", type=int, default=16,
273
+ help="cap a team's worker (a busy partition can hold a 16-CPU job past "
274
+ "the loop's 15 minutes: its run then doesn't count)")
275
+ parser.add_argument("--tag", default="",
276
+ help="put before every run and swarm name (e.g. q2b-): two grids at once "
277
+ "then never share a Slurm job name")
278
+ args = parser.parse_args(argv)
279
+ args.urls = args.urls.split(",")
280
+ args.revision = team.pinned(args.revision)
281
+ root = args.root.resolve()
282
+ root.mkdir(parents=True, exist_ok=True)
283
+ api = HfApi()
284
+ api.create_bucket(args.bucket, private=True, exist_ok=True)
285
+ if not api.bucket_info(args.bucket).private:
286
+ raise SystemExit(f"bucket {args.bucket} is public: refusing")
287
+ token = os.environ.get("HF_TOKEN") or get_token()
288
+ secrets = root / f"secrets-{os.getpid()}.env" # per driver: two may share a root
289
+ old = os.umask(0o077)
290
+ secrets.write_text(f"HF_TOKEN={token}\nNAMESPACE={args.namespace}\n"
291
+ f"BUCKET=hf://buckets/{args.bucket}\n")
292
+ os.umask(old)
293
+ rows_file = root / "rows.jsonl"
294
+ rows = [json.loads(x) for x in rows_file.read_text().splitlines()] if rows_file.exists() else []
295
+ if bad := [r for r in rows if not valid(r)]: # an earlier driver kept them: run them again
296
+ with (root / "rows-discarded.jsonl").open("a") as f:
297
+ f.write("".join(json.dumps(r) + "\n" for r in bad))
298
+ rows_file.write_text("".join(json.dumps(r) + "\n" for r in rows if valid(r)))
299
+ say(f"{len(bad)} rows that don't count moved to rows-discarded.jsonl")
300
+ done = {(r["problem"], r["agents"]) for r in rows if valid(r)}
301
+ teams = [(p, n) for p in numbers(args.problems) for n in numbers(args.agents)
302
+ if (p, n) not in done]
303
+ say(f"{len(teams)} teams to run ({len(done)} done), {args.parallel} at once, on {args.urls}")
304
+ try:
305
+ with ThreadPoolExecutor(args.parallel) as pool:
306
+ list(pool.map(lambda t: run_team(args, root, secrets, *t), teams))
307
+ finally:
308
+ secrets.unlink(missing_ok=True)
309
+ subprocess.run(["uv", "run", str(HERE / "plot.py"), str(root)], check=False) # matplotlib
310
+ if args.dataset:
311
+ upload(root, args.dataset, args.prefix)
312
+ return 0
313
+
314
+
315
+ if __name__ == "__main__":
316
+ sys.exit(main())
flock/sweep/waits.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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])))
flock/team.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 task `agg-p07-n04` at `--revision` (default: the dataset's head on the Hub), 4 agents
7
+ (agent-001 .. agent-004, one worker and board), and this checkout's `resources/` as the spec's
8
+ `resources_dir`, whose `private_number` gives each agent its own number. The local
9
+ `resources/numbers.json` must be the revision's, which this checks. `--where` picks the
10
+ template's `where:` block: local docker, HF Sandboxes with a Space board, or the HF cluster with
11
+ a local board. The dataset is private for now: HF_TOKEN must read it.
12
+ """
13
+
14
+ import argparse
15
+ import copy
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import yaml
20
+ from huggingface_hub import HfApi, hf_hub_download
21
+
22
+ from flock.models import load_spec_yaml
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ DATASET = "HuggingFaceSwarms/s3-aggregation"
26
+ RESOURCES = HERE.parent / "resources"
27
+ PROBLEMS, SIZES = range(1, 33), (1, 2, 4, 8, 16)
28
+
29
+
30
+ def merge(base: dict, extra: dict) -> dict:
31
+ out = dict(base)
32
+ for key, value in extra.items():
33
+ both = isinstance(value, dict) and isinstance(out.get(key), dict)
34
+ out[key] = merge(out[key], value) if both else value
35
+ return out
36
+
37
+
38
+ def fill(value, names: dict[str, str]):
39
+ if isinstance(value, dict):
40
+ return {k: fill(v, names) for k, v in value.items()}
41
+ if isinstance(value, list):
42
+ return [fill(v, names) for v in value]
43
+ if isinstance(value, str):
44
+ for placeholder, text in names.items():
45
+ value = value.replace(placeholder, text)
46
+ return value
47
+
48
+
49
+ def team_spec(template: dict, problem: int, agents: int, where: str,
50
+ revision: str) -> tuple[str, dict]:
51
+ """(the task's name, the team's spec) from the template."""
52
+ template = copy.deepcopy(template)
53
+ places = template.pop("where")
54
+ task = f"agg-p{problem:02d}-n{agents:02d}"
55
+ spec = fill(merge(template, places[where]),
56
+ {"TEAM": task, "REVISION": revision, "RESOURCES": str(RESOURCES)})
57
+ spec["agents"] = {"count": agents}
58
+ spec["workers"]["agents_per_worker"] = agents
59
+ return task, spec
60
+
61
+
62
+ def pinned(revision: str | None) -> str:
63
+ """The revision as a commit, whose resources/numbers.json must be this checkout's."""
64
+ sha = HfApi().dataset_info(DATASET, revision=revision).sha
65
+ remote = Path(hf_hub_download(DATASET, "resources/numbers.json", repo_type="dataset",
66
+ revision=sha))
67
+ if remote.read_bytes() != (RESOURCES / "numbers.json").read_bytes():
68
+ raise SystemExit(f"{RESOURCES / 'numbers.json'} is not {DATASET}@{sha[:7]}'s: download "
69
+ "that revision, or pass the --revision of this checkout")
70
+ return sha
71
+
72
+
73
+ def main(argv=None) -> int:
74
+ parser = argparse.ArgumentParser(description="Write one s3-aggregation team's Flock spec.")
75
+ parser.add_argument("--problem", type=int, required=True, choices=PROBLEMS)
76
+ parser.add_argument("--agents", type=int, required=True, choices=SIZES)
77
+ parser.add_argument("--where", choices=("docker", "sandbox", "cluster"), default="sandbox")
78
+ parser.add_argument("--revision", help="the dataset revision to pin (default: its head)")
79
+ parser.add_argument("--out", type=Path, help="default: out/<task> next to this script")
80
+ args = parser.parse_args(argv)
81
+ template = load_spec_yaml((HERE / "spec.template.yaml").read_text())
82
+ task, spec = team_spec(template, args.problem, args.agents, args.where,
83
+ pinned(args.revision))
84
+ out = args.out or HERE / "out" / task
85
+ out.mkdir(parents=True, exist_ok=True)
86
+ header = (f"# {task} ({args.where}), written by {DATASET}'s flock/team.py from "
87
+ "spec.template.yaml: edit the template, not this file.\n")
88
+ (out / "spec.yaml").write_text(header + yaml.safe_dump(spec, sort_keys=False, width=100))
89
+ print(out / "spec.yaml")
90
+ return 0
91
+
92
+
93
+ if __name__ == "__main__":
94
+ sys.exit(main())
generate.py CHANGED
@@ -1,11 +1,14 @@
1
  """Regenerate s3-aggregation from its seed: `python generate.py` (Python 3.10+, no dependencies).
2
 
3
- Writes `problems.json`, `tasks/` and `roles/` next to this file, replacing what is there:
 
4
  - 32 problems, each 16 integers drawn uniformly from 1 to 99 (repeats allowed), from SEED;
5
  - one task per problem and team size N in SIZES, `agg-pPP-nNN`, whose team holds the problem's
6
  first N numbers;
7
- - one role file per agent of each task, `roles/<task>/slot-NN.md`, outside the task folders, so
8
- an agent's container never holds another agent's number.
 
 
9
 
10
  check.py checks that this reproduces the committed files byte for byte.
11
  """
@@ -21,6 +24,7 @@ NUMBERS = 16 # per problem; a team of N holds the first N
21
  SIZES = (1, 2, 4, 8, 16)
22
  LOW, HIGH = 1, 99
23
  IMAGE = "python:3.12-slim" # public and prebuilt: HF Sandboxes need one, docker and podman too
 
24
 
25
  ONES = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
26
  "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
@@ -49,13 +53,18 @@ def task_name(problem: int, n: int) -> str:
49
  return f"agg-p{problem:02d}-n{n:02d}"
50
 
51
 
 
 
 
 
 
52
  def instruction(n: int) -> str:
53
  if n == 1:
54
- return """# Sort the team's private numbers
55
 
56
  You are the only agent on this team, solving a private-information number sorting task. You
57
- hold one private integer from 1 to 99, written in English words. It is in your instructions,
58
- under "Your private number".
59
 
60
  Write `/app/answer.json` (create `/app` if needed): a JSON array holding your number's numeric
61
  value, as digits. Then stop.
@@ -63,9 +72,9 @@ value, as digits. Then stop.
63
  return f"""# Sort the team's private numbers
64
 
65
  You are on a team of {n} agents solving a private-information number sorting task. Each agent
66
- holds one private integer from 1 to 99, written in English words. Yours is in your instructions,
67
- under "Your private number". You know only your own number, and the others don't know it unless
68
- you tell them.
69
 
70
  The team must find all {n} numbers and list their numeric values in ascending order. Keep equal
71
  numbers from different agents as separate entries: each agent's number appears once in the list,
@@ -103,7 +112,7 @@ timeout_sec = 1800
103
  [environment]
104
  # Prebuilt and public, with no Dockerfile: HF Sandboxes need one, and docker and podman use it
105
  # too. Nothing task-specific is in the container: each agent's number reaches it only through
106
- # its own instructions (the flock role file), and tests/ arrive only when the agent is done.
107
  docker_image = "{IMAGE}"
108
  cpus = 1
109
  memory_mb = 1024
@@ -214,19 +223,22 @@ echo '{json.dumps(answer)}' > "$answer"
214
  """
215
 
216
 
217
- def role(number: int) -> str:
218
- return f"Your private number: {words(number)}\n"
219
-
220
-
221
  def write(path: Path, text: str, mode: int = 0o644) -> None:
222
  path.parent.mkdir(parents=True, exist_ok=True)
223
  path.write_text(text, encoding="utf-8")
224
  path.chmod(mode)
225
 
226
 
 
 
 
 
 
 
 
 
227
  def generate(root: Path = HERE, seed: int = SEED) -> None:
228
- for folder in ("tasks", "roles"):
229
- shutil.rmtree(root / folder, ignore_errors=True)
230
  drawn = problems(seed)
231
  rows = ",\n".join(f' "p{i:02d}": {json.dumps(numbers)}' for i, numbers in enumerate(drawn, 1))
232
  write(root / "problems.json", f'{{"seed": {seed}, "problems": {{\n{rows}\n}}}}\n')
@@ -239,8 +251,7 @@ def generate(root: Path = HERE, seed: int = SEED) -> None:
239
  write(task / "tests" / "test.sh", TEST_SH, 0o755)
240
  write(task / "tests" / "expected.json", json.dumps(sorted(team)) + "\n")
241
  write(task / "solution" / "solve.sh", solve_sh(sorted(team)), 0o755)
242
- for slot, number in enumerate(team, 1):
243
- write(root / "roles" / name / f"slot-{slot:02d}.md", role(number))
244
 
245
 
246
  if __name__ == "__main__":
 
1
  """Regenerate s3-aggregation from its seed: `python generate.py` (Python 3.10+, no dependencies).
2
 
3
+ Writes `problems.json`, `tasks/` and `resources/numbers.json` next to this file, replacing what
4
+ is there:
5
  - 32 problems, each 16 integers drawn uniformly from 1 to 99 (repeats allowed), from SEED;
6
  - one task per problem and team size N in SIZES, `agg-pPP-nNN`, whose team holds the problem's
7
  first N numbers;
8
+ - `resources/numbers.json`: each task's agents (Flock's `naming: consecutive-id`, agent-001 ...)
9
+ and the number each holds, in words. Flock's worker reads it through
10
+ `resources/private_number.py`, which puts only an agent's own number in its environment, so
11
+ no task folder, instruction or container holds another agent's number.
12
 
13
  check.py checks that this reproduces the committed files byte for byte.
14
  """
 
24
  SIZES = (1, 2, 4, 8, 16)
25
  LOW, HIGH = 1, 99
26
  IMAGE = "python:3.12-slim" # public and prebuilt: HF Sandboxes need one, docker and podman too
27
+ ENV = "PRIVATE_NUMBER" # where an agent finds its own number (resources/private_number.py)
28
 
29
  ONES = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
30
  "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
 
53
  return f"agg-p{problem:02d}-n{n:02d}"
54
 
55
 
56
+ def agent_name(slot: int) -> str:
57
+ """Flock's `naming: consecutive-id`: the slot's agent, from 1."""
58
+ return f"agent-{slot:03d}"
59
+
60
+
61
  def instruction(n: int) -> str:
62
  if n == 1:
63
+ return f"""# Sort the team's private numbers
64
 
65
  You are the only agent on this team, solving a private-information number sorting task. You
66
+ hold one private integer from 1 to 99, written in English words. It is in your environment,
67
+ in the variable `{ENV}`: run `echo ${ENV}` to read it.
68
 
69
  Write `/app/answer.json` (create `/app` if needed): a JSON array holding your number's numeric
70
  value, as digits. Then stop.
 
72
  return f"""# Sort the team's private numbers
73
 
74
  You are on a team of {n} agents solving a private-information number sorting task. Each agent
75
+ holds one private integer from 1 to 99, written in English words. Yours is in your environment,
76
+ in the variable `{ENV}`: run `echo ${ENV}` to read it. You know only your own
77
+ number, and the others don't know it unless you tell them.
78
 
79
  The team must find all {n} numbers and list their numeric values in ascending order. Keep equal
80
  numbers from different agents as separate entries: each agent's number appears once in the list,
 
112
  [environment]
113
  # Prebuilt and public, with no Dockerfile: HF Sandboxes need one, and docker and podman use it
114
  # too. Nothing task-specific is in the container: each agent's number reaches it only through
115
+ # its own environment (resources/private_number.py), and tests/ arrive only when the agent is done.
116
  docker_image = "{IMAGE}"
117
  cpus = 1
118
  memory_mb = 1024
 
223
  """
224
 
225
 
 
 
 
 
226
  def write(path: Path, text: str, mode: int = 0o644) -> None:
227
  path.parent.mkdir(parents=True, exist_ok=True)
228
  path.write_text(text, encoding="utf-8")
229
  path.chmod(mode)
230
 
231
 
232
+ def numbers_json(drawn: list[list[int]]) -> str:
233
+ """Each task's agents and their numbers in words: one line per task."""
234
+ teams = {task_name(p, n): {agent_name(k): words(x) for k, x in enumerate(numbers[:n], 1)}
235
+ for p, numbers in enumerate(drawn, 1) for n in SIZES}
236
+ rows = ",\n".join(f" {json.dumps(task)}: {json.dumps(team)}" for task, team in teams.items())
237
+ return f"{{\n{rows}\n}}\n"
238
+
239
+
240
  def generate(root: Path = HERE, seed: int = SEED) -> None:
241
+ shutil.rmtree(root / "tasks", ignore_errors=True)
 
242
  drawn = problems(seed)
243
  rows = ",\n".join(f' "p{i:02d}": {json.dumps(numbers)}' for i, numbers in enumerate(drawn, 1))
244
  write(root / "problems.json", f'{{"seed": {seed}, "problems": {{\n{rows}\n}}}}\n')
 
251
  write(task / "tests" / "test.sh", TEST_SH, 0o755)
252
  write(task / "tests" / "expected.json", json.dumps(sorted(team)) + "\n")
253
  write(task / "solution" / "solve.sh", solve_sh(sorted(team)), 0o755)
254
+ write(root / "resources" / "numbers.json", numbers_json(drawn))
 
255
 
256
 
257
  if __name__ == "__main__":
resources/message_board.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Flock's own message board, unchanged. A spec's `resources_dir` replaces Flock's built-in
2
+ resources folder, so this folder brings the board along: the module Flock ships, imported from
3
+ the Flock that runs the worker."""
4
+
5
+ from flock.harbor.builtin.resources.message_board import Options, Resource # noqa: F401
resources/numbers.json ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "agg-p01-n01": {"agent-001": "thirty-seven"},
3
+ "agg-p01-n02": {"agent-001": "thirty-seven", "agent-002": "twenty-six"},
4
+ "agg-p01-n04": {"agent-001": "thirty-seven", "agent-002": "twenty-six", "agent-003": "fifteen", "agent-004": "sixty-nine"},
5
+ "agg-p01-n08": {"agent-001": "thirty-seven", "agent-002": "twenty-six", "agent-003": "fifteen", "agent-004": "sixty-nine", "agent-005": "fifteen", "agent-006": "forty-three", "agent-007": "ninety-seven", "agent-008": "seventy-one"},
6
+ "agg-p01-n16": {"agent-001": "thirty-seven", "agent-002": "twenty-six", "agent-003": "fifteen", "agent-004": "sixty-nine", "agent-005": "fifteen", "agent-006": "forty-three", "agent-007": "ninety-seven", "agent-008": "seventy-one", "agent-009": "thirty-eight", "agent-010": "eighty-seven", "agent-011": "eighty-two", "agent-012": "thirty-seven", "agent-013": "eighty-eight", "agent-014": "forty-four", "agent-015": "sixty-two", "agent-016": "eight"},
7
+ "agg-p02-n01": {"agent-001": "seventy-one"},
8
+ "agg-p02-n02": {"agent-001": "seventy-one", "agent-002": "seventy-one"},
9
+ "agg-p02-n04": {"agent-001": "seventy-one", "agent-002": "seventy-one", "agent-003": "nineteen", "agent-004": "twenty"},
10
+ "agg-p02-n08": {"agent-001": "seventy-one", "agent-002": "seventy-one", "agent-003": "nineteen", "agent-004": "twenty", "agent-005": "six", "agent-006": "thirty-seven", "agent-007": "twenty-three", "agent-008": "sixty-three"},
11
+ "agg-p02-n16": {"agent-001": "seventy-one", "agent-002": "seventy-one", "agent-003": "nineteen", "agent-004": "twenty", "agent-005": "six", "agent-006": "thirty-seven", "agent-007": "twenty-three", "agent-008": "sixty-three", "agent-009": "ninety-five", "agent-010": "seventy-six", "agent-011": "thirty-two", "agent-012": "twenty-two", "agent-013": "twenty-four", "agent-014": "nineteen", "agent-015": "sixty-eight", "agent-016": "twenty-eight"},
12
+ "agg-p03-n01": {"agent-001": "nineteen"},
13
+ "agg-p03-n02": {"agent-001": "nineteen", "agent-002": "eighty-one"},
14
+ "agg-p03-n04": {"agent-001": "nineteen", "agent-002": "eighty-one", "agent-003": "eighty-nine", "agent-004": "fifty-five"},
15
+ "agg-p03-n08": {"agent-001": "nineteen", "agent-002": "eighty-one", "agent-003": "eighty-nine", "agent-004": "fifty-five", "agent-005": "two", "agent-006": "ninety-two", "agent-007": "twenty-six", "agent-008": "sixty-eight"},
16
+ "agg-p03-n16": {"agent-001": "nineteen", "agent-002": "eighty-one", "agent-003": "eighty-nine", "agent-004": "fifty-five", "agent-005": "two", "agent-006": "ninety-two", "agent-007": "twenty-six", "agent-008": "sixty-eight", "agent-009": "forty-three", "agent-010": "seventy-eight", "agent-011": "thirty-two", "agent-012": "eighty-three", "agent-013": "ninety-two", "agent-014": "thirty-six", "agent-015": "seventy-seven", "agent-016": "thirty"},
17
+ "agg-p04-n01": {"agent-001": "thirty-three"},
18
+ "agg-p04-n02": {"agent-001": "thirty-three", "agent-002": "fifty-three"},
19
+ "agg-p04-n04": {"agent-001": "thirty-three", "agent-002": "fifty-three", "agent-003": "forty-eight", "agent-004": "seventy-one"},
20
+ "agg-p04-n08": {"agent-001": "thirty-three", "agent-002": "fifty-three", "agent-003": "forty-eight", "agent-004": "seventy-one", "agent-005": "twenty-five", "agent-006": "sixty-two", "agent-007": "eighty-seven", "agent-008": "ninety"},
21
+ "agg-p04-n16": {"agent-001": "thirty-three", "agent-002": "fifty-three", "agent-003": "forty-eight", "agent-004": "seventy-one", "agent-005": "twenty-five", "agent-006": "sixty-two", "agent-007": "eighty-seven", "agent-008": "ninety", "agent-009": "forty-four", "agent-010": "twenty-four", "agent-011": "ninety-seven", "agent-012": "seventy-seven", "agent-013": "seventy-nine", "agent-014": "fifty-two", "agent-015": "ninety-five", "agent-016": "seventy-four"},
22
+ "agg-p05-n01": {"agent-001": "eighty-seven"},
23
+ "agg-p05-n02": {"agent-001": "eighty-seven", "agent-002": "ninety-three"},
24
+ "agg-p05-n04": {"agent-001": "eighty-seven", "agent-002": "ninety-three", "agent-003": "ninety-six", "agent-004": "fifty-seven"},
25
+ "agg-p05-n08": {"agent-001": "eighty-seven", "agent-002": "ninety-three", "agent-003": "ninety-six", "agent-004": "fifty-seven", "agent-005": "forty", "agent-006": "twenty-five", "agent-007": "sixty-eight", "agent-008": "eighty-four"},
26
+ "agg-p05-n16": {"agent-001": "eighty-seven", "agent-002": "ninety-three", "agent-003": "ninety-six", "agent-004": "fifty-seven", "agent-005": "forty", "agent-006": "twenty-five", "agent-007": "sixty-eight", "agent-008": "eighty-four", "agent-009": "eighteen", "agent-010": "seventy-nine", "agent-011": "forty-three", "agent-012": "sixty-six", "agent-013": "thirty-three", "agent-014": "seventy-one", "agent-015": "seventy", "agent-016": "eighty-two"},
27
+ "agg-p06-n01": {"agent-001": "seventy-six"},
28
+ "agg-p06-n02": {"agent-001": "seventy-six", "agent-002": "twenty-three"},
29
+ "agg-p06-n04": {"agent-001": "seventy-six", "agent-002": "twenty-three", "agent-003": "eight", "agent-004": "eighty-five"},
30
+ "agg-p06-n08": {"agent-001": "seventy-six", "agent-002": "twenty-three", "agent-003": "eight", "agent-004": "eighty-five", "agent-005": "eleven", "agent-006": "fifty-four", "agent-007": "seventy-eight", "agent-008": "thirty-five"},
31
+ "agg-p06-n16": {"agent-001": "seventy-six", "agent-002": "twenty-three", "agent-003": "eight", "agent-004": "eighty-five", "agent-005": "eleven", "agent-006": "fifty-four", "agent-007": "seventy-eight", "agent-008": "thirty-five", "agent-009": "four", "agent-010": "five", "agent-011": "eighteen", "agent-012": "seven", "agent-013": "sixty-six", "agent-014": "thirty-eight", "agent-015": "fifty-four", "agent-016": "eighty-nine"},
32
+ "agg-p07-n01": {"agent-001": "forty-nine"},
33
+ "agg-p07-n02": {"agent-001": "forty-nine", "agent-002": "thirty-six"},
34
+ "agg-p07-n04": {"agent-001": "forty-nine", "agent-002": "thirty-six", "agent-003": "thirty-eight", "agent-004": "forty-eight"},
35
+ "agg-p07-n08": {"agent-001": "forty-nine", "agent-002": "thirty-six", "agent-003": "thirty-eight", "agent-004": "forty-eight", "agent-005": "fifty-four", "agent-006": "twenty-two", "agent-007": "eighty-eight", "agent-008": "eight"},
36
+ "agg-p07-n16": {"agent-001": "forty-nine", "agent-002": "thirty-six", "agent-003": "thirty-eight", "agent-004": "forty-eight", "agent-005": "fifty-four", "agent-006": "twenty-two", "agent-007": "eighty-eight", "agent-008": "eight", "agent-009": "sixty-six", "agent-010": "twenty-five", "agent-011": "sixteen", "agent-012": "seventy-eight", "agent-013": "nine", "agent-014": "forty-two", "agent-015": "eighty-six", "agent-016": "two"},
37
+ "agg-p08-n01": {"agent-001": "thirty-seven"},
38
+ "agg-p08-n02": {"agent-001": "thirty-seven", "agent-002": "seventy-one"},
39
+ "agg-p08-n04": {"agent-001": "thirty-seven", "agent-002": "seventy-one", "agent-003": "eighty-eight", "agent-004": "forty-four"},
40
+ "agg-p08-n08": {"agent-001": "thirty-seven", "agent-002": "seventy-one", "agent-003": "eighty-eight", "agent-004": "forty-four", "agent-005": "sixty-six", "agent-006": "sixty-eight", "agent-007": "twenty-four", "agent-008": "thirty-five"},
41
+ "agg-p08-n16": {"agent-001": "thirty-seven", "agent-002": "seventy-one", "agent-003": "eighty-eight", "agent-004": "forty-four", "agent-005": "sixty-six", "agent-006": "sixty-eight", "agent-007": "twenty-four", "agent-008": "thirty-five", "agent-009": "fifty-six", "agent-010": "seventy", "agent-011": "seventy-six", "agent-012": "seventy", "agent-013": "sixty-four", "agent-014": "ninety-two", "agent-015": "eighty-four", "agent-016": "twenty-three"},
42
+ "agg-p09-n01": {"agent-001": "forty"},
43
+ "agg-p09-n02": {"agent-001": "forty", "agent-002": "sixty-seven"},
44
+ "agg-p09-n04": {"agent-001": "forty", "agent-002": "sixty-seven", "agent-003": "sixty-five", "agent-004": "forty-three"},
45
+ "agg-p09-n08": {"agent-001": "forty", "agent-002": "sixty-seven", "agent-003": "sixty-five", "agent-004": "forty-three", "agent-005": "sixty", "agent-006": "sixty-six", "agent-007": "fourteen", "agent-008": "eighteen"},
46
+ "agg-p09-n16": {"agent-001": "forty", "agent-002": "sixty-seven", "agent-003": "sixty-five", "agent-004": "forty-three", "agent-005": "sixty", "agent-006": "sixty-six", "agent-007": "fourteen", "agent-008": "eighteen", "agent-009": "eighty-eight", "agent-010": "eighty-one", "agent-011": "eight", "agent-012": "twenty", "agent-013": "fourteen", "agent-014": "sixty-eight", "agent-015": "thirty-one", "agent-016": "sixty-three"},
47
+ "agg-p10-n01": {"agent-001": "sixty-nine"},
48
+ "agg-p10-n02": {"agent-001": "sixty-nine", "agent-002": "five"},
49
+ "agg-p10-n04": {"agent-001": "sixty-nine", "agent-002": "five", "agent-003": "nineteen", "agent-004": "twelve"},
50
+ "agg-p10-n08": {"agent-001": "sixty-nine", "agent-002": "five", "agent-003": "nineteen", "agent-004": "twelve", "agent-005": "seventy-nine", "agent-006": "fifty-one", "agent-007": "sixty-three", "agent-008": "thirty-two"},
51
+ "agg-p10-n16": {"agent-001": "sixty-nine", "agent-002": "five", "agent-003": "nineteen", "agent-004": "twelve", "agent-005": "seventy-nine", "agent-006": "fifty-one", "agent-007": "sixty-three", "agent-008": "thirty-two", "agent-009": "ninety-six", "agent-010": "twenty-five", "agent-011": "four", "agent-012": "fifty-six", "agent-013": "twelve", "agent-014": "eighty-six", "agent-015": "fifty-eight", "agent-016": "seventy-five"},
52
+ "agg-p11-n01": {"agent-001": "twelve"},
53
+ "agg-p11-n02": {"agent-001": "twelve", "agent-002": "ninety-eight"},
54
+ "agg-p11-n04": {"agent-001": "twelve", "agent-002": "ninety-eight", "agent-003": "seventy-five", "agent-004": "seventy-eight"},
55
+ "agg-p11-n08": {"agent-001": "twelve", "agent-002": "ninety-eight", "agent-003": "seventy-five", "agent-004": "seventy-eight", "agent-005": "sixty-seven", "agent-006": "eighty-four", "agent-007": "twenty-five", "agent-008": "eleven"},
56
+ "agg-p11-n16": {"agent-001": "twelve", "agent-002": "ninety-eight", "agent-003": "seventy-five", "agent-004": "seventy-eight", "agent-005": "sixty-seven", "agent-006": "eighty-four", "agent-007": "twenty-five", "agent-008": "eleven", "agent-009": "forty", "agent-010": "twenty-three", "agent-011": "ninety-four", "agent-012": "seventy-four", "agent-013": "sixteen", "agent-014": "four", "agent-015": "seventy-four", "agent-016": "forty-two"},
57
+ "agg-p12-n01": {"agent-001": "two"},
58
+ "agg-p12-n02": {"agent-001": "two", "agent-002": "fifty"},
59
+ "agg-p12-n04": {"agent-001": "two", "agent-002": "fifty", "agent-003": "ninety-five", "agent-004": "twelve"},
60
+ "agg-p12-n08": {"agent-001": "two", "agent-002": "fifty", "agent-003": "ninety-five", "agent-004": "twelve", "agent-005": "ninety-nine", "agent-006": "thirty", "agent-007": "fifteen", "agent-008": "thirty-one"},
61
+ "agg-p12-n16": {"agent-001": "two", "agent-002": "fifty", "agent-003": "ninety-five", "agent-004": "twelve", "agent-005": "ninety-nine", "agent-006": "thirty", "agent-007": "fifteen", "agent-008": "thirty-one", "agent-009": "forty-five", "agent-010": "forty-four", "agent-011": "thirty-one", "agent-012": "thirty-three", "agent-013": "twenty-four", "agent-014": "ninety-five", "agent-015": "seventy-nine", "agent-016": "eleven"},
62
+ "agg-p13-n01": {"agent-001": "forty-two"},
63
+ "agg-p13-n02": {"agent-001": "forty-two", "agent-002": "seventy-eight"},
64
+ "agg-p13-n04": {"agent-001": "forty-two", "agent-002": "seventy-eight", "agent-003": "forty-eight", "agent-004": "sixty-one"},
65
+ "agg-p13-n08": {"agent-001": "forty-two", "agent-002": "seventy-eight", "agent-003": "forty-eight", "agent-004": "sixty-one", "agent-005": "forty-seven", "agent-006": "fifty-six", "agent-007": "two", "agent-008": "two"},
66
+ "agg-p13-n16": {"agent-001": "forty-two", "agent-002": "seventy-eight", "agent-003": "forty-eight", "agent-004": "sixty-one", "agent-005": "forty-seven", "agent-006": "fifty-six", "agent-007": "two", "agent-008": "two", "agent-009": "twenty-three", "agent-010": "eighty-two", "agent-011": "sixty-two", "agent-012": "twenty-five", "agent-013": "eighty-five", "agent-014": "sixty-eight", "agent-015": "sixty", "agent-016": "ninety-three"},
67
+ "agg-p14-n01": {"agent-001": "eighty-four"},
68
+ "agg-p14-n02": {"agent-001": "eighty-four", "agent-002": "twenty-nine"},
69
+ "agg-p14-n04": {"agent-001": "eighty-four", "agent-002": "twenty-nine", "agent-003": "fifty-three", "agent-004": "forty-nine"},
70
+ "agg-p14-n08": {"agent-001": "eighty-four", "agent-002": "twenty-nine", "agent-003": "fifty-three", "agent-004": "forty-nine", "agent-005": "forty-four", "agent-006": "twenty-five", "agent-007": "fifty-nine", "agent-008": "thirty-nine"},
71
+ "agg-p14-n16": {"agent-001": "eighty-four", "agent-002": "twenty-nine", "agent-003": "fifty-three", "agent-004": "forty-nine", "agent-005": "forty-four", "agent-006": "twenty-five", "agent-007": "fifty-nine", "agent-008": "thirty-nine", "agent-009": "ninety-six", "agent-010": "seventy-two", "agent-011": "seventy-eight", "agent-012": "one", "agent-013": "thirty-seven", "agent-014": "fifty-one", "agent-015": "forty-five", "agent-016": "eleven"},
72
+ "agg-p15-n01": {"agent-001": "thirty-seven"},
73
+ "agg-p15-n02": {"agent-001": "thirty-seven", "agent-002": "twenty-nine"},
74
+ "agg-p15-n04": {"agent-001": "thirty-seven", "agent-002": "twenty-nine", "agent-003": "fifty-seven", "agent-004": "eighteen"},
75
+ "agg-p15-n08": {"agent-001": "thirty-seven", "agent-002": "twenty-nine", "agent-003": "fifty-seven", "agent-004": "eighteen", "agent-005": "forty-nine", "agent-006": "seventy-nine", "agent-007": "fifty", "agent-008": "sixty-two"},
76
+ "agg-p15-n16": {"agent-001": "thirty-seven", "agent-002": "twenty-nine", "agent-003": "fifty-seven", "agent-004": "eighteen", "agent-005": "forty-nine", "agent-006": "seventy-nine", "agent-007": "fifty", "agent-008": "sixty-two", "agent-009": "fifty-three", "agent-010": "thirty", "agent-011": "forty-three", "agent-012": "thirty", "agent-013": "seventy-eight", "agent-014": "eighty-two", "agent-015": "twenty-seven", "agent-016": "forty"},
77
+ "agg-p16-n01": {"agent-001": "thirty-eight"},
78
+ "agg-p16-n02": {"agent-001": "thirty-eight", "agent-002": "sixty-three"},
79
+ "agg-p16-n04": {"agent-001": "thirty-eight", "agent-002": "sixty-three", "agent-003": "thirty", "agent-004": "sixty-three"},
80
+ "agg-p16-n08": {"agent-001": "thirty-eight", "agent-002": "sixty-three", "agent-003": "thirty", "agent-004": "sixty-three", "agent-005": "fifty-one", "agent-006": "seventy-eight", "agent-007": "fifty-eight", "agent-008": "eighty-one"},
81
+ "agg-p16-n16": {"agent-001": "thirty-eight", "agent-002": "sixty-three", "agent-003": "thirty", "agent-004": "sixty-three", "agent-005": "fifty-one", "agent-006": "seventy-eight", "agent-007": "fifty-eight", "agent-008": "eighty-one", "agent-009": "two", "agent-010": "eighteen", "agent-011": "eighty-eight", "agent-012": "ten", "agent-013": "fifty-eight", "agent-014": "thirty-five", "agent-015": "ninety-two", "agent-016": "sixteen"},
82
+ "agg-p17-n01": {"agent-001": "forty"},
83
+ "agg-p17-n02": {"agent-001": "forty", "agent-002": "ten"},
84
+ "agg-p17-n04": {"agent-001": "forty", "agent-002": "ten", "agent-003": "ninety-five", "agent-004": "thirty-one"},
85
+ "agg-p17-n08": {"agent-001": "forty", "agent-002": "ten", "agent-003": "ninety-five", "agent-004": "thirty-one", "agent-005": "ninety-nine", "agent-006": "seventy-seven", "agent-007": "ninety", "agent-008": "seventy"},
86
+ "agg-p17-n16": {"agent-001": "forty", "agent-002": "ten", "agent-003": "ninety-five", "agent-004": "thirty-one", "agent-005": "ninety-nine", "agent-006": "seventy-seven", "agent-007": "ninety", "agent-008": "seventy", "agent-009": "forty-three", "agent-010": "two", "agent-011": "seventy-eight", "agent-012": "thirty-four", "agent-013": "seventy-six", "agent-014": "thirty-eight", "agent-015": "seventy", "agent-016": "forty"},
87
+ "agg-p18-n01": {"agent-001": "seventy-two"},
88
+ "agg-p18-n02": {"agent-001": "seventy-two", "agent-002": "sixteen"},
89
+ "agg-p18-n04": {"agent-001": "seventy-two", "agent-002": "sixteen", "agent-003": "eighty-four", "agent-004": "eighty-six"},
90
+ "agg-p18-n08": {"agent-001": "seventy-two", "agent-002": "sixteen", "agent-003": "eighty-four", "agent-004": "eighty-six", "agent-005": "one", "agent-006": "fifty-nine", "agent-007": "two", "agent-008": "fifty-nine"},
91
+ "agg-p18-n16": {"agent-001": "seventy-two", "agent-002": "sixteen", "agent-003": "eighty-four", "agent-004": "eighty-six", "agent-005": "one", "agent-006": "fifty-nine", "agent-007": "two", "agent-008": "fifty-nine", "agent-009": "forty-seven", "agent-010": "forty-three", "agent-011": "eighty-three", "agent-012": "sixty-six", "agent-013": "seven", "agent-014": "forty-two", "agent-015": "seventy-four", "agent-016": "seventy-nine"},
92
+ "agg-p19-n01": {"agent-001": "thirty-seven"},
93
+ "agg-p19-n02": {"agent-001": "thirty-seven", "agent-002": "forty-one"},
94
+ "agg-p19-n04": {"agent-001": "thirty-seven", "agent-002": "forty-one", "agent-003": "sixty-two", "agent-004": "eighty-eight"},
95
+ "agg-p19-n08": {"agent-001": "thirty-seven", "agent-002": "forty-one", "agent-003": "sixty-two", "agent-004": "eighty-eight", "agent-005": "thirty-four", "agent-006": "ten", "agent-007": "sixty-nine", "agent-008": "sixty-five"},
96
+ "agg-p19-n16": {"agent-001": "thirty-seven", "agent-002": "forty-one", "agent-003": "sixty-two", "agent-004": "eighty-eight", "agent-005": "thirty-four", "agent-006": "ten", "agent-007": "sixty-nine", "agent-008": "sixty-five", "agent-009": "twenty-nine", "agent-010": "eighty-one", "agent-011": "thirty-five", "agent-012": "seventy-one", "agent-013": "eighty-seven", "agent-014": "ninety-eight", "agent-015": "twenty-two", "agent-016": "sixty-seven"},
97
+ "agg-p20-n01": {"agent-001": "forty-four"},
98
+ "agg-p20-n02": {"agent-001": "forty-four", "agent-002": "seventy-three"},
99
+ "agg-p20-n04": {"agent-001": "forty-four", "agent-002": "seventy-three", "agent-003": "forty-five", "agent-004": "seventy-four"},
100
+ "agg-p20-n08": {"agent-001": "forty-four", "agent-002": "seventy-three", "agent-003": "forty-five", "agent-004": "seventy-four", "agent-005": "ninety-seven", "agent-006": "eighty-one", "agent-007": "seventy-three", "agent-008": "fifty-eight"},
101
+ "agg-p20-n16": {"agent-001": "forty-four", "agent-002": "seventy-three", "agent-003": "forty-five", "agent-004": "seventy-four", "agent-005": "ninety-seven", "agent-006": "eighty-one", "agent-007": "seventy-three", "agent-008": "fifty-eight", "agent-009": "sixty-five", "agent-010": "sixty-eight", "agent-011": "thirty-one", "agent-012": "five", "agent-013": "sixty-one", "agent-014": "forty-nine", "agent-015": "ninety-six", "agent-016": "twenty-nine"},
102
+ "agg-p21-n01": {"agent-001": "fifty-seven"},
103
+ "agg-p21-n02": {"agent-001": "fifty-seven", "agent-002": "thirty-four"},
104
+ "agg-p21-n04": {"agent-001": "fifty-seven", "agent-002": "thirty-four", "agent-003": "seventy-one", "agent-004": "sixty-eight"},
105
+ "agg-p21-n08": {"agent-001": "fifty-seven", "agent-002": "thirty-four", "agent-003": "seventy-one", "agent-004": "sixty-eight", "agent-005": "nineteen", "agent-006": "eighty-two", "agent-007": "seventy-three", "agent-008": "ninety-nine"},
106
+ "agg-p21-n16": {"agent-001": "fifty-seven", "agent-002": "thirty-four", "agent-003": "seventy-one", "agent-004": "sixty-eight", "agent-005": "nineteen", "agent-006": "eighty-two", "agent-007": "seventy-three", "agent-008": "ninety-nine", "agent-009": "eighteen", "agent-010": "seventy-two", "agent-011": "thirty-nine", "agent-012": "sixteen", "agent-013": "seventy-six", "agent-014": "fifty", "agent-015": "sixty-four", "agent-016": "forty-three"},
107
+ "agg-p22-n01": {"agent-001": "four"},
108
+ "agg-p22-n02": {"agent-001": "four", "agent-002": "forty-one"},
109
+ "agg-p22-n04": {"agent-001": "four", "agent-002": "forty-one", "agent-003": "eighty-nine", "agent-004": "seventy-one"},
110
+ "agg-p22-n08": {"agent-001": "four", "agent-002": "forty-one", "agent-003": "eighty-nine", "agent-004": "seventy-one", "agent-005": "five", "agent-006": "twenty-three", "agent-007": "twenty-seven", "agent-008": "fifteen"},
111
+ "agg-p22-n16": {"agent-001": "four", "agent-002": "forty-one", "agent-003": "eighty-nine", "agent-004": "seventy-one", "agent-005": "five", "agent-006": "twenty-three", "agent-007": "twenty-seven", "agent-008": "fifteen", "agent-009": "thirty-one", "agent-010": "seventy-four", "agent-011": "ten", "agent-012": "eight", "agent-013": "twenty-two", "agent-014": "eighty-eight", "agent-015": "seventy-six", "agent-016": "seventy-seven"},
112
+ "agg-p23-n01": {"agent-001": "twenty"},
113
+ "agg-p23-n02": {"agent-001": "twenty", "agent-002": "fifty-five"},
114
+ "agg-p23-n04": {"agent-001": "twenty", "agent-002": "fifty-five", "agent-003": "forty-five", "agent-004": "one"},
115
+ "agg-p23-n08": {"agent-001": "twenty", "agent-002": "fifty-five", "agent-003": "forty-five", "agent-004": "one", "agent-005": "eighty-four", "agent-006": "eighty-one", "agent-007": "thirty", "agent-008": "seventy-nine"},
116
+ "agg-p23-n16": {"agent-001": "twenty", "agent-002": "fifty-five", "agent-003": "forty-five", "agent-004": "one", "agent-005": "eighty-four", "agent-006": "eighty-one", "agent-007": "thirty", "agent-008": "seventy-nine", "agent-009": "fifty-one", "agent-010": "seven", "agent-011": "sixteen", "agent-012": "sixty-nine", "agent-013": "fifty-two", "agent-014": "three", "agent-015": "ninety-six", "agent-016": "thirty-five"},
117
+ "agg-p24-n01": {"agent-001": "ninety-five"},
118
+ "agg-p24-n02": {"agent-001": "ninety-five", "agent-002": "eighty-two"},
119
+ "agg-p24-n04": {"agent-001": "ninety-five", "agent-002": "eighty-two", "agent-003": "five", "agent-004": "fifty"},
120
+ "agg-p24-n08": {"agent-001": "ninety-five", "agent-002": "eighty-two", "agent-003": "five", "agent-004": "fifty", "agent-005": "ninety-five", "agent-006": "thirty-eight", "agent-007": "eighty-seven", "agent-008": "eighty-nine"},
121
+ "agg-p24-n16": {"agent-001": "ninety-five", "agent-002": "eighty-two", "agent-003": "five", "agent-004": "fifty", "agent-005": "ninety-five", "agent-006": "thirty-eight", "agent-007": "eighty-seven", "agent-008": "eighty-nine", "agent-009": "thirty-nine", "agent-010": "thirty-seven", "agent-011": "sixty-seven", "agent-012": "ten", "agent-013": "eighty-seven", "agent-014": "ninety-two", "agent-015": "thirty-nine", "agent-016": "ninety-two"},
122
+ "agg-p25-n01": {"agent-001": "thirty-three"},
123
+ "agg-p25-n02": {"agent-001": "thirty-three", "agent-002": "twenty-two"},
124
+ "agg-p25-n04": {"agent-001": "thirty-three", "agent-002": "twenty-two", "agent-003": "eighteen", "agent-004": "eighty-eight"},
125
+ "agg-p25-n08": {"agent-001": "thirty-three", "agent-002": "twenty-two", "agent-003": "eighteen", "agent-004": "eighty-eight", "agent-005": "forty-six", "agent-006": "seventy-three", "agent-007": "two", "agent-008": "six"},
126
+ "agg-p25-n16": {"agent-001": "thirty-three", "agent-002": "twenty-two", "agent-003": "eighteen", "agent-004": "eighty-eight", "agent-005": "forty-six", "agent-006": "seventy-three", "agent-007": "two", "agent-008": "six", "agent-009": "twenty-one", "agent-010": "nineteen", "agent-011": "six", "agent-012": "three", "agent-013": "twenty-one", "agent-014": "seventy-three", "agent-015": "fifty-seven", "agent-016": "twenty-one"},
127
+ "agg-p26-n01": {"agent-001": "twenty-one"},
128
+ "agg-p26-n02": {"agent-001": "twenty-one", "agent-002": "twenty"},
129
+ "agg-p26-n04": {"agent-001": "twenty-one", "agent-002": "twenty", "agent-003": "four", "agent-004": "one"},
130
+ "agg-p26-n08": {"agent-001": "twenty-one", "agent-002": "twenty", "agent-003": "four", "agent-004": "one", "agent-005": "thirty-six", "agent-006": "twelve", "agent-007": "thirty-seven", "agent-008": "sixty-six"},
131
+ "agg-p26-n16": {"agent-001": "twenty-one", "agent-002": "twenty", "agent-003": "four", "agent-004": "one", "agent-005": "thirty-six", "agent-006": "twelve", "agent-007": "thirty-seven", "agent-008": "sixty-six", "agent-009": "forty-seven", "agent-010": "two", "agent-011": "ninety-seven", "agent-012": "seventy-seven", "agent-013": "twenty-eight", "agent-014": "seventy-five", "agent-015": "twenty-two", "agent-016": "ninety-four"},
132
+ "agg-p27-n01": {"agent-001": "ninety-nine"},
133
+ "agg-p27-n02": {"agent-001": "ninety-nine", "agent-002": "seventy-four"},
134
+ "agg-p27-n04": {"agent-001": "ninety-nine", "agent-002": "seventy-four", "agent-003": "eighty-six", "agent-004": "fifteen"},
135
+ "agg-p27-n08": {"agent-001": "ninety-nine", "agent-002": "seventy-four", "agent-003": "eighty-six", "agent-004": "fifteen", "agent-005": "fourteen", "agent-006": "ninety-five", "agent-007": "eighty-three", "agent-008": "forty-seven"},
136
+ "agg-p27-n16": {"agent-001": "ninety-nine", "agent-002": "seventy-four", "agent-003": "eighty-six", "agent-004": "fifteen", "agent-005": "fourteen", "agent-006": "ninety-five", "agent-007": "eighty-three", "agent-008": "forty-seven", "agent-009": "ninety-six", "agent-010": "fifty-six", "agent-011": "twelve", "agent-012": "eighty-eight", "agent-013": "sixty", "agent-014": "seven", "agent-015": "eighty-four", "agent-016": "six"},
137
+ "agg-p28-n01": {"agent-001": "fifty-eight"},
138
+ "agg-p28-n02": {"agent-001": "fifty-eight", "agent-002": "thirty-eight"},
139
+ "agg-p28-n04": {"agent-001": "fifty-eight", "agent-002": "thirty-eight", "agent-003": "sixty-seven", "agent-004": "seventy"},
140
+ "agg-p28-n08": {"agent-001": "fifty-eight", "agent-002": "thirty-eight", "agent-003": "sixty-seven", "agent-004": "seventy", "agent-005": "thirty-three", "agent-006": "twelve", "agent-007": "seventy-seven", "agent-008": "ninety-three"},
141
+ "agg-p28-n16": {"agent-001": "fifty-eight", "agent-002": "thirty-eight", "agent-003": "sixty-seven", "agent-004": "seventy", "agent-005": "thirty-three", "agent-006": "twelve", "agent-007": "seventy-seven", "agent-008": "ninety-three", "agent-009": "seven", "agent-010": "twenty-four", "agent-011": "fifty-three", "agent-012": "ninety-four", "agent-013": "eight", "agent-014": "ninety-two", "agent-015": "fifteen", "agent-016": "sixty-three"},
142
+ "agg-p29-n01": {"agent-001": "twenty-three"},
143
+ "agg-p29-n02": {"agent-001": "twenty-three", "agent-002": "twenty-two"},
144
+ "agg-p29-n04": {"agent-001": "twenty-three", "agent-002": "twenty-two", "agent-003": "forty-five", "agent-004": "eighty-two"},
145
+ "agg-p29-n08": {"agent-001": "twenty-three", "agent-002": "twenty-two", "agent-003": "forty-five", "agent-004": "eighty-two", "agent-005": "ninety-two", "agent-006": "eighty-nine", "agent-007": "thirty-eight", "agent-008": "fifty-six"},
146
+ "agg-p29-n16": {"agent-001": "twenty-three", "agent-002": "twenty-two", "agent-003": "forty-five", "agent-004": "eighty-two", "agent-005": "ninety-two", "agent-006": "eighty-nine", "agent-007": "thirty-eight", "agent-008": "fifty-six", "agent-009": "forty-three", "agent-010": "twelve", "agent-011": "sixty-three", "agent-012": "eighty-four", "agent-013": "seventy-six", "agent-014": "sixty-eight", "agent-015": "six", "agent-016": "twelve"},
147
+ "agg-p30-n01": {"agent-001": "twenty-one"},
148
+ "agg-p30-n02": {"agent-001": "twenty-one", "agent-002": "sixty-five"},
149
+ "agg-p30-n04": {"agent-001": "twenty-one", "agent-002": "sixty-five", "agent-003": "seventy-four", "agent-004": "seventy-four"},
150
+ "agg-p30-n08": {"agent-001": "twenty-one", "agent-002": "sixty-five", "agent-003": "seventy-four", "agent-004": "seventy-four", "agent-005": "forty-three", "agent-006": "forty-one", "agent-007": "fifty-three", "agent-008": "eighty-seven"},
151
+ "agg-p30-n16": {"agent-001": "twenty-one", "agent-002": "sixty-five", "agent-003": "seventy-four", "agent-004": "seventy-four", "agent-005": "forty-three", "agent-006": "forty-one", "agent-007": "fifty-three", "agent-008": "eighty-seven", "agent-009": "forty-three", "agent-010": "eighty-nine", "agent-011": "forty-three", "agent-012": "sixty-one", "agent-013": "sixty-five", "agent-014": "three", "agent-015": "ninety-seven", "agent-016": "thirty-six"},
152
+ "agg-p31-n01": {"agent-001": "twenty-five"},
153
+ "agg-p31-n02": {"agent-001": "twenty-five", "agent-002": "twenty-three"},
154
+ "agg-p31-n04": {"agent-001": "twenty-five", "agent-002": "twenty-three", "agent-003": "four", "agent-004": "thirty-six"},
155
+ "agg-p31-n08": {"agent-001": "twenty-five", "agent-002": "twenty-three", "agent-003": "four", "agent-004": "thirty-six", "agent-005": "eighty-two", "agent-006": "twenty-eight", "agent-007": "fifty-one", "agent-008": "three"},
156
+ "agg-p31-n16": {"agent-001": "twenty-five", "agent-002": "twenty-three", "agent-003": "four", "agent-004": "thirty-six", "agent-005": "eighty-two", "agent-006": "twenty-eight", "agent-007": "fifty-one", "agent-008": "three", "agent-009": "two", "agent-010": "thirty-nine", "agent-011": "twenty-seven", "agent-012": "fifty", "agent-013": "sixteen", "agent-014": "seventy-six", "agent-015": "sixty-three", "agent-016": "fourteen"},
157
+ "agg-p32-n01": {"agent-001": "sixty-five"},
158
+ "agg-p32-n02": {"agent-001": "sixty-five", "agent-002": "eighty"},
159
+ "agg-p32-n04": {"agent-001": "sixty-five", "agent-002": "eighty", "agent-003": "eighty-five", "agent-004": "forty-three"},
160
+ "agg-p32-n08": {"agent-001": "sixty-five", "agent-002": "eighty", "agent-003": "eighty-five", "agent-004": "forty-three", "agent-005": "eighty-six", "agent-006": "sixty-one", "agent-007": "fifty-eight", "agent-008": "eighty-nine"},
161
+ "agg-p32-n16": {"agent-001": "sixty-five", "agent-002": "eighty", "agent-003": "eighty-five", "agent-004": "forty-three", "agent-005": "eighty-six", "agent-006": "sixty-one", "agent-007": "fifty-eight", "agent-008": "eighty-nine", "agent-009": "sixty-five", "agent-010": "seventy-six", "agent-011": "thirty-one", "agent-012": "sixty-seven", "agent-013": "eight", "agent-014": "ninety-one", "agent-015": "ninety-one", "agent-016": "forty-two"}
162
+ }
resources/private_number.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Each agent's own private number, and only its own, in its environment as PRIVATE_NUMBER.
2
+
3
+ A Flock resource (the `Resource` interface of flock/harbor/resources.py). Point the spec's
4
+ `resources_dir` at this folder and name the team:
5
+
6
+ resources_dir: <this dataset>/resources
7
+ resources:
8
+ private_number:
9
+ team: agg-p01-n04
10
+
11
+ Flock's worker loads this module and `numbers.json` next to it, and binds each agent's Trial:
12
+ `bind("agent-002")` gives agent-002's container `PRIVATE_NUMBER=twenty-six` and nothing else.
13
+ The module and the file stay on the worker: they are not in the tool bundle, the task folder or
14
+ any container, so no agent can read another agent's number. The team's agents are Flock's
15
+ `naming: consecutive-id` (agent-001 ...), `agents.count` of them.
16
+ """
17
+
18
+ import asyncio
19
+ import json
20
+ from pathlib import Path
21
+
22
+ NUMBERS = Path(__file__).with_name("numbers.json")
23
+ ENV = "PRIVATE_NUMBER"
24
+
25
+
26
+ class Resource:
27
+ def __init__(self, options, *, state_dir, agents, secrets):
28
+ options = dict(options or {})
29
+ team = options.pop("team", None)
30
+ if options:
31
+ raise ValueError(f"private_number: unknown options {sorted(options)} (only `team`)")
32
+ teams = json.loads(NUMBERS.read_text(encoding="utf-8"))
33
+ if team not in teams:
34
+ raise ValueError(f"private_number.team: {team!r} is not a task of this dataset, "
35
+ "e.g. agg-p01-n04")
36
+ self.numbers = teams[team]
37
+ if set(agents) != self.numbers.keys(): # the type's whole roster
38
+ raise ValueError(f"private_number: {team}'s agents are {sorted(self.numbers)}, not "
39
+ f"{sorted(agents)}: run it with naming: consecutive-id and "
40
+ f"agents.count: {len(self.numbers)}")
41
+ self.metadata = {"team": team}
42
+
43
+ async def start(self):
44
+ pass
45
+
46
+ def bind(self, name):
47
+ if name not in self.numbers:
48
+ raise ValueError(f"private_number: no number for {name}")
49
+ return {"env": {ENV: self.numbers[name]}}
50
+
51
+ async def wait(self):
52
+ await asyncio.Event().wait()
53
+
54
+ async def export(self, directory):
55
+ return {}
56
+
57
+ async def stop(self):
58
+ pass
roles/agg-p01-n01/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n02/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n02/slot-02.md DELETED
@@ -1 +0,0 @@
1
- Your private number: twenty-six
 
 
roles/agg-p01-n04/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n04/slot-02.md DELETED
@@ -1 +0,0 @@
1
- Your private number: twenty-six
 
 
roles/agg-p01-n04/slot-03.md DELETED
@@ -1 +0,0 @@
1
- Your private number: fifteen
 
 
roles/agg-p01-n04/slot-04.md DELETED
@@ -1 +0,0 @@
1
- Your private number: sixty-nine
 
 
roles/agg-p01-n08/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n08/slot-02.md DELETED
@@ -1 +0,0 @@
1
- Your private number: twenty-six
 
 
roles/agg-p01-n08/slot-03.md DELETED
@@ -1 +0,0 @@
1
- Your private number: fifteen
 
 
roles/agg-p01-n08/slot-04.md DELETED
@@ -1 +0,0 @@
1
- Your private number: sixty-nine
 
 
roles/agg-p01-n08/slot-05.md DELETED
@@ -1 +0,0 @@
1
- Your private number: fifteen
 
 
roles/agg-p01-n08/slot-06.md DELETED
@@ -1 +0,0 @@
1
- Your private number: forty-three
 
 
roles/agg-p01-n08/slot-07.md DELETED
@@ -1 +0,0 @@
1
- Your private number: ninety-seven
 
 
roles/agg-p01-n08/slot-08.md DELETED
@@ -1 +0,0 @@
1
- Your private number: seventy-one
 
 
roles/agg-p01-n16/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n16/slot-02.md DELETED
@@ -1 +0,0 @@
1
- Your private number: twenty-six
 
 
roles/agg-p01-n16/slot-03.md DELETED
@@ -1 +0,0 @@
1
- Your private number: fifteen
 
 
roles/agg-p01-n16/slot-04.md DELETED
@@ -1 +0,0 @@
1
- Your private number: sixty-nine
 
 
roles/agg-p01-n16/slot-05.md DELETED
@@ -1 +0,0 @@
1
- Your private number: fifteen
 
 
roles/agg-p01-n16/slot-06.md DELETED
@@ -1 +0,0 @@
1
- Your private number: forty-three
 
 
roles/agg-p01-n16/slot-07.md DELETED
@@ -1 +0,0 @@
1
- Your private number: ninety-seven
 
 
roles/agg-p01-n16/slot-08.md DELETED
@@ -1 +0,0 @@
1
- Your private number: seventy-one
 
 
roles/agg-p01-n16/slot-09.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-eight
 
 
roles/agg-p01-n16/slot-10.md DELETED
@@ -1 +0,0 @@
1
- Your private number: eighty-seven
 
 
roles/agg-p01-n16/slot-11.md DELETED
@@ -1 +0,0 @@
1
- Your private number: eighty-two
 
 
roles/agg-p01-n16/slot-12.md DELETED
@@ -1 +0,0 @@
1
- Your private number: thirty-seven
 
 
roles/agg-p01-n16/slot-13.md DELETED
@@ -1 +0,0 @@
1
- Your private number: eighty-eight
 
 
roles/agg-p01-n16/slot-14.md DELETED
@@ -1 +0,0 @@
1
- Your private number: forty-four
 
 
roles/agg-p01-n16/slot-15.md DELETED
@@ -1 +0,0 @@
1
- Your private number: sixty-two
 
 
roles/agg-p01-n16/slot-16.md DELETED
@@ -1 +0,0 @@
1
- Your private number: eight
 
 
roles/agg-p02-n01/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: seventy-one
 
 
roles/agg-p02-n02/slot-01.md DELETED
@@ -1 +0,0 @@
1
- Your private number: seventy-one