Agent Manager commited on
Commit ·
3421ea2
1
Parent(s): a97bebd
Rename flock integration to legion
Browse files- README.md +42 -43
- budget.py +2 -2
- check.py +8 -8
- eval/metrics.py +7 -7
- generate.py +1 -1
- {flock → legion}/registries.conf +0 -0
- {flock → legion}/spec.template.yaml +1 -1
- {flock → legion}/sweep/README.md +13 -13
- {flock → legion}/sweep/health-log.sh +0 -0
- {flock → legion}/sweep/plot.py +2 -2
- {flock → legion}/sweep/serve-vllm.sbatch +1 -1
- {flock → legion}/sweep/setaside.py +5 -5
- {flock → legion}/sweep/sweep.py +32 -32
- {flock → legion}/team.md +0 -0
- {flock → legion}/team.py +5 -5
README.md
CHANGED
|
@@ -19,9 +19,9 @@ A [Harbor](https://harborframework.com) environment that measures whether a swar
|
|
| 19 |
for one agent's move budget, so sharing what each one has explored lets a team search it in
|
| 20 |
time. It adapts the parallel-exploration task of
|
| 21 |
[s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615)
|
| 22 |
-
([scalingswarms.com](https://scalingswarms.com)) to [
|
| 23 |
swarms, whose agents talk over a shared message board. It isn't a replication of the paper: the
|
| 24 |
-
agents are Pi with
|
| 25 |
[s3-aggregation](https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation), needs
|
| 26 |
communication instead.
|
| 27 |
|
|
@@ -67,16 +67,16 @@ tasks/maze-tNN/
|
|
| 67 |
environment/docker-compose.yaml main (the agent) and maze, on an internal network only main reaches
|
| 68 |
environment/agent/ main's image: its Dockerfile and the `maze` command, nothing else
|
| 69 |
environment/maze/ the service's image: tree.json (private), engine.py, service.py,
|
| 70 |
-
success.py (
|
| 71 |
tests/ the grader's own image: test.sh, grade.py, expected.json
|
| 72 |
solution/solve.sh an oracle that walks the shortest path with `maze move`
|
| 73 |
template/ the files every task shares (generate.py copies them)
|
| 74 |
-
|
| 75 |
-
spec.template.yaml what every team's
|
| 76 |
team.py writes one team's spec (the HF cluster, or local docker)
|
| 77 |
registries.conf podman pulls Docker Hub images through mirror.gcr.io
|
| 78 |
sweep/ the scaling sweep (every tree at N = 1..16, one model per grid): its README
|
| 79 |
-
eval/metrics.py one row per team from
|
| 80 |
generate.py writes tasks/ from its seed (115)
|
| 81 |
budget.py the move-budget table below, from the service's own engine
|
| 82 |
check.py the checks that need no model
|
|
@@ -114,17 +114,17 @@ doesn't count), it writes 0 before it checks anything, never writes through a li
|
|
| 114 |
Python runs isolated (`python3 -I -S`). It keeps copies of `moves.jsonl` and `final.json` in
|
| 115 |
`/logs/verifier/` for the metrics.
|
| 116 |
|
| 117 |
-
**Stop on success.**
|
| 118 |
(`python3 -I -S /app/success.py`, run in the maze service, never in the agent's container)
|
| 119 |
ends the run when the first agent gets out: the check is read-only and prints
|
| 120 |
`{"success": <the exit was reached>, "evidence": {"exit_reached", "moves", "reached_at"}}`
|
| 121 |
-
from the service's state.
|
| 122 |
releases the workers and grades each agent's Trial.
|
| 123 |
|
| 124 |
## The move budget
|
| 125 |
|
| 126 |
Simulated with the service's own engine (`template/environment/maze/engine.py`: every move
|
| 127 |
-
goes through the same `Walk` the service holds), without
|
| 128 |
`python budget.py` over the 32 trees, for N agents and a per-agent budget:
|
| 129 |
|
| 130 |
- **(a)** one agent, depth-first: the first door it hasn't been through, in the listed order,
|
|
@@ -186,31 +186,31 @@ habits of 1, 0.8, 0.5 and 0 (`--habit 0`: independent random orders), and at N =
|
|
| 186 |
(c) is what sharing explored branches can buy. The budget is in every task's tree, grader,
|
| 187 |
instruction and `task.toml` (`move_budget`).
|
| 188 |
|
| 189 |
-
## Run it with
|
| 190 |
|
| 191 |
-
The maze needs a second container per agent, so it runs where
|
| 192 |
podman. On the HF cluster: `compute: slurm`, one worker on **hopper-cpu** running the whole
|
| 193 |
team in rootless podman with `podman-compose` (hopper-cpu has podman 4.9.3; the B200 nodes'
|
| 194 |
-
podman 3.4.4 can't create
|
| 195 |
-
each run.
|
| 196 |
-
runs one team (`TREE`, default `maze-t01`, and `N`, default 4) at the revision it pins;
|
| 197 |
-
`docs/tasks.md` ("s3-maze") has the commands. For any other team, `
|
| 198 |
-
spec from `
|
| 199 |
|
| 200 |
```sh
|
| 201 |
DS=/fsx/$USER/s3-maze # this dataset on the shared disk (the workers read registries.conf)
|
| 202 |
hf download HuggingFaceSwarms/s3-maze --repo-type dataset --revision <sha> --local-dir $DS
|
| 203 |
-
uv run python $DS/
|
| 204 |
-
uv run
|
| 205 |
-
export
|
| 206 |
-
uv run
|
| 207 |
-
uv run
|
| 208 |
-
uv run
|
| 209 |
-
uv run python $DS/eval/metrics.py $
|
| 210 |
```
|
| 211 |
|
| 212 |
**Needs:** a cluster profile with `SLURM_PARTITION=hopper-cpu`, `SLURM_MAX_MEM_PER_CPU_MB=2000`,
|
| 213 |
-
`VENV` (
|
| 214 |
(Docker Hub's pull limit hits the cluster's shared address hard); and a mode-600 secrets file
|
| 215 |
with `HF_TOKEN` (reads this private dataset and the run's bucket), `HF_INFERENCE_TOKEN` (a
|
| 216 |
fine-grained token with only "Make calls to Inference Providers", which goes into the agents'
|
|
@@ -218,22 +218,22 @@ containers: never the same token), `NAMESPACE` and `BUCKET` (a private bucket fo
|
|
| 218 |
state). The worker gets a CPU per agent and two more, at 1900 MB per CPU. hopper-cpu
|
| 219 |
autoscales: a scale-up from 0 can take about 15 minutes.
|
| 220 |
|
| 221 |
-
With stop on success, the run ends when the first agent reaches the exit:
|
| 222 |
Trial as it releases the worker, and the worker copies the grading (with the move logs) and the
|
| 223 |
-
board export to `<run dir>/results/` (
|
| 224 |
them. A run that nobody wins ends its loop after 45 minutes or 6 rounds, and doesn't end by
|
| 225 |
-
itself on Slurm: `
|
| 226 |
|
| 227 |
### The board rules
|
| 228 |
|
| 229 |
-
The same for every eval run, since they shape how agents talk (`
|
| 230 |
one channel, `#general`, and no more (`max_channels: 1`); an agent is woken by a mention or a
|
| 231 |
reply in its thread; a post is at most 1000 characters, at least 5 s after the agent's previous
|
| 232 |
one, and at most 40 per agent. Podman enforces them in each agent's rule proxy.
|
| 233 |
|
| 234 |
### The protocol hint
|
| 235 |
|
| 236 |
-
`team.py --hint` adds `
|
| 237 |
agent's instructions: "Before you go through a door, read the board and post which door you are
|
| 238 |
taking; pick one no teammate has claimed; post when a branch is a dead end." Without it, the
|
| 239 |
team gets the neutral instructions.
|
|
@@ -282,9 +282,9 @@ uv run check.py --env podman # all of them (on the HF cluster: a hopper-cpu
|
|
| 282 |
uv run check.py --env none # without the Trials
|
| 283 |
```
|
| 284 |
|
| 285 |
-
On the HF cluster, from
|
| 286 |
`srun -p hopper-cpu -c 8 --mem=15G bash -c 'source scripts/slurm/podman-node.sh &&
|
| 287 |
-
CONTAINERS_REGISTRIES_CONF=$DS/
|
| 288 |
podman_node_cleanup'`.
|
| 289 |
|
| 290 |
1. **Generator:** `generate.py` reproduces `tasks/` byte for byte, and another seed gives other
|
|
@@ -323,14 +323,14 @@ podman_node_cleanup'`.
|
|
| 323 |
the exit is named only in the service's `tree.json`, `tests/expected.json` and
|
| 324 |
`solution/solve.sh`; no folder beside `tasks/` holds a tree.
|
| 325 |
5. **Metrics** (`eval/metrics.py`) on Slurm run directories made of the service's real exports
|
| 326 |
-
and the grader's real grades, with
|
| 327 |
`${N:-4}`): with no env files the row's task is `maze-t01` and its team four agents;
|
| 328 |
`run.env` (over `cluster.env`) sets another tree and team size; a team with one agent's
|
| 329 |
results gone keeps that agent and flags its reward and move log as missing; and the row
|
| 330 |
flags Trials of another task than the spec selects (a `run.env` gone) and of an agent the
|
| 331 |
spec didn't plan.
|
| 332 |
6. **Trials** (`--env podman` or `docker`, on `maze-t01`, with agents that need no model):
|
| 333 |
-
- a walker runs
|
| 334 |
with `maze move`, runs it again (true), and scores 1, with the move log and the export in
|
| 335 |
its verifier's folder;
|
| 336 |
- Harbor's oracle agent (`solution/solve.sh`) scores 1;
|
|
@@ -341,18 +341,17 @@ podman_node_cleanup'`.
|
|
| 341 |
`/logs/artifacts` and `/logs/verifier`, a `reward.txt` of 1, a `json.py` and a
|
| 342 |
`sitecustomize`, makes three moves short of the exit, and scores 0.
|
| 343 |
|
| 344 |
-
Last run on a hopper-cpu node (podman 4.9.3),
|
| 345 |
-
passed.
|
| 346 |
|
| 347 |
## Dummy run
|
| 348 |
|
| 349 |
-
One team, `maze-t01` with N = 4, from
|
| 350 |
`0f1fe651`, whose `tasks/` are this revision's) on the HF cluster on 2026-11-17:
|
| 351 |
`Qwen/Qwen3.8-27B` on the HF router (deepinfra), one hopper-cpu worker of 6 CPUs running the
|
| 352 |
four Trials in rootless podman, and a local board.
|
| 353 |
|
| 354 |
- **The team found the exit.** agent-003 reached it after 154 moves, 10 min 22 s after the
|
| 355 |
-
Trials started.
|
| 356 |
agents and released the worker; every Trial was graded within a minute and the worker ended,
|
| 357 |
at 11:50 UTC. Only agent-003 scored 1.
|
| 358 |
- **They split the tree on the board** without being told to: agents posted the corridors they
|
|
@@ -371,21 +370,21 @@ four Trials in rootless podman, and a local board.
|
|
| 371 |
- **HF Sandboxes can't run it:** each agent's Trial is two containers (the agent's and its maze
|
| 372 |
service), and HF Sandboxes run one container per Trial. It needs multi-container support
|
| 373 |
there, as AgentEscapeBench does. Until then it runs on docker or podman (the HF cluster).
|
| 374 |
-
- **Private for now**, so whatever resolves and downloads the task (
|
| 375 |
-
`
|
| 376 |
-
- **A new Trial starts a new maze.** If an agent's Trial fails and
|
| 377 |
worker is relaunched), that agent gets a fresh copy of the maze at the start, with a fresh
|
| 378 |
budget, while its Pi session remembers the old walk. `metrics.py` counts moves over all of an
|
| 379 |
agent's Trials, and its reward is its latest Trial's.
|
| 380 |
-
- **The first exit ends the run, not the episode at once:**
|
| 381 |
other agents may move for up to about 30 s more before their turns are interrupted.
|
| 382 |
- **The grader trusts the maze service.** The agent reaches it only through `maze look` and
|
| 383 |
`maze move` (an internal network, two routes, bodies up to 4 KiB); an agent that could reach
|
| 384 |
the service any other way could forge its record. The service runs without capabilities, with
|
| 385 |
a pids and memory limit, so flooding it only hurts the agent's own maze.
|
| 386 |
- **The move log's `agent`** is the Trial's compose project (`<swarm>-<agent>-tN`), which names
|
| 387 |
-
the
|
| 388 |
- **Not the paper's setup:** a per-agent move budget instead of a token allowance (looking and
|
| 389 |
refused moves are free), a message board instead of `message`/`read_messages` tools with
|
| 390 |
-
notifications,
|
| 391 |
observation, and N = 1 is a solo control.
|
|
|
|
| 19 |
for one agent's move budget, so sharing what each one has explored lets a team search it in
|
| 20 |
time. It adapts the parallel-exploration task of
|
| 21 |
[s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615)
|
| 22 |
+
([scalingswarms.com](https://scalingswarms.com)) to [Legion](https://github.com/huggingface/legion)
|
| 23 |
swarms, whose agents talk over a shared message board. It isn't a replication of the paper: the
|
| 24 |
+
agents are Pi with Legion's board, and the board is what we measure. Its companion,
|
| 25 |
[s3-aggregation](https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation), needs
|
| 26 |
communication instead.
|
| 27 |
|
|
|
|
| 67 |
environment/docker-compose.yaml main (the agent) and maze, on an internal network only main reaches
|
| 68 |
environment/agent/ main's image: its Dockerfile and the `maze` command, nothing else
|
| 69 |
environment/maze/ the service's image: tree.json (private), engine.py, service.py,
|
| 70 |
+
success.py (Legion's success check), export.py (the collect hook)
|
| 71 |
tests/ the grader's own image: test.sh, grade.py, expected.json
|
| 72 |
solution/solve.sh an oracle that walks the shortest path with `maze move`
|
| 73 |
template/ the files every task shares (generate.py copies them)
|
| 74 |
+
legion/
|
| 75 |
+
spec.template.yaml what every team's Legion run shares: model, board rules, loop, limits
|
| 76 |
team.py writes one team's spec (the HF cluster, or local docker)
|
| 77 |
registries.conf podman pulls Docker Hub images through mirror.gcr.io
|
| 78 |
sweep/ the scaling sweep (every tree at N = 1..16, one model per grid): its README
|
| 79 |
+
eval/metrics.py one row per team from Legion run directories
|
| 80 |
generate.py writes tasks/ from its seed (115)
|
| 81 |
budget.py the move-budget table below, from the service's own engine
|
| 82 |
check.py the checks that need no model
|
|
|
|
| 114 |
Python runs isolated (`python3 -I -S`). It keeps copies of `moves.jsonl` and `final.json` in
|
| 115 |
`/logs/verifier/` for the metrics.
|
| 116 |
|
| 117 |
+
**Stop on success.** Legion's `stop_on_success` with the service's `success_check`
|
| 118 |
(`python3 -I -S /app/success.py`, run in the maze service, never in the agent's container)
|
| 119 |
ends the run when the first agent gets out: the check is read-only and prints
|
| 120 |
`{"success": <the exit was reached>, "evidence": {"exit_reached", "moves", "reached_at"}}`
|
| 121 |
+
from the service's state. Legion polls it every 30 s per agent, then interrupts the turns,
|
| 122 |
releases the workers and grades each agent's Trial.
|
| 123 |
|
| 124 |
## The move budget
|
| 125 |
|
| 126 |
Simulated with the service's own engine (`template/environment/maze/engine.py`: every move
|
| 127 |
+
goes through the same `Walk` the service holds), without Legion or containers:
|
| 128 |
`python budget.py` over the 32 trees, for N agents and a per-agent budget:
|
| 129 |
|
| 130 |
- **(a)** one agent, depth-first: the first door it hasn't been through, in the listed order,
|
|
|
|
| 186 |
(c) is what sharing explored branches can buy. The budget is in every task's tree, grader,
|
| 187 |
instruction and `task.toml` (`move_budget`).
|
| 188 |
|
| 189 |
+
## Run it with Legion on the HF cluster
|
| 190 |
|
| 191 |
+
The maze needs a second container per agent, so it runs where Legion runs Trials in docker or
|
| 192 |
podman. On the HF cluster: `compute: slurm`, one worker on **hopper-cpu** running the whole
|
| 193 |
team in rootless podman with `podman-compose` (hopper-cpu has podman 4.9.3; the B200 nodes'
|
| 194 |
+
podman 3.4.4 can't create Legion's per-agent networks), and a local board on that worker, new
|
| 195 |
+
each run. Legion's [`experiments/s3-maze/spec.yaml`](https://github.com/huggingface/legion/tree/main/experiments/s3-maze)
|
| 196 |
+
runs one team (`TREE`, default `maze-t01`, and `N`, default 4) at the revision it pins; Legion's
|
| 197 |
+
`docs/tasks.md` ("s3-maze") has the commands. For any other team, `legion/team.py` writes the
|
| 198 |
+
spec from `legion/spec.template.yaml`, run from Legion's checkout:
|
| 199 |
|
| 200 |
```sh
|
| 201 |
DS=/fsx/$USER/s3-maze # this dataset on the shared disk (the workers read registries.conf)
|
| 202 |
hf download HuggingFaceSwarms/s3-maze --repo-type dataset --revision <sha> --local-dir $DS
|
| 203 |
+
uv run python $DS/legion/team.py --tree 7 --agents 4 --out runs/src/maze-t07-n04
|
| 204 |
+
uv run legion init $PWD/runs/maze-t07-n04 --from runs/src/maze-t07-n04 --profile cluster.env --secrets secrets.env
|
| 205 |
+
export LEGION_RUN_DIR=$PWD/runs/maze-t07-n04
|
| 206 |
+
uv run legion launch $LEGION_RUN_DIR/experiment
|
| 207 |
+
uv run legion status maze-t07-n04 # STOPPED ON SUCCESS once an agent gets out
|
| 208 |
+
uv run legion stop maze-t07-n04 --release # ends the controller (and a run nobody won)
|
| 209 |
+
uv run python $DS/eval/metrics.py $LEGION_RUN_DIR
|
| 210 |
```
|
| 211 |
|
| 212 |
**Needs:** a cluster profile with `SLURM_PARTITION=hopper-cpu`, `SLURM_MAX_MEM_PER_CPU_MB=2000`,
|
| 213 |
+
`VENV` (Legion's venv on the shared disk) and `CONTAINERS_REGISTRIES_CONF=$DS/legion/registries.conf`
|
| 214 |
(Docker Hub's pull limit hits the cluster's shared address hard); and a mode-600 secrets file
|
| 215 |
with `HF_TOKEN` (reads this private dataset and the run's bucket), `HF_INFERENCE_TOKEN` (a
|
| 216 |
fine-grained token with only "Make calls to Inference Providers", which goes into the agents'
|
|
|
|
| 218 |
state). The worker gets a CPU per agent and two more, at 1900 MB per CPU. hopper-cpu
|
| 219 |
autoscales: a scale-up from 0 can take about 15 minutes.
|
| 220 |
|
| 221 |
+
With stop on success, the run ends when the first agent reaches the exit: Legion grades every
|
| 222 |
Trial as it releases the worker, and the worker copies the grading (with the move logs) and the
|
| 223 |
+
board export to `<run dir>/results/` (Legion's `LEGION_RESULTS_DIR`), where `metrics.py` reads
|
| 224 |
them. A run that nobody wins ends its loop after 45 minutes or 6 rounds, and doesn't end by
|
| 225 |
+
itself on Slurm: `legion stop --release` drains the worker, which is when its Trials are graded.
|
| 226 |
|
| 227 |
### The board rules
|
| 228 |
|
| 229 |
+
The same for every eval run, since they shape how agents talk (`legion/spec.template.yaml`):
|
| 230 |
one channel, `#general`, and no more (`max_channels: 1`); an agent is woken by a mention or a
|
| 231 |
reply in its thread; a post is at most 1000 characters, at least 5 s after the agent's previous
|
| 232 |
one, and at most 40 per agent. Podman enforces them in each agent's rule proxy.
|
| 233 |
|
| 234 |
### The protocol hint
|
| 235 |
|
| 236 |
+
`team.py --hint` adds `legion/team.md` as the team's `team_file`, which Legion appends to each
|
| 237 |
agent's instructions: "Before you go through a door, read the board and post which door you are
|
| 238 |
taking; pick one no teammate has claimed; post when a branch is a dead end." Without it, the
|
| 239 |
team gets the neutral instructions.
|
|
|
|
| 282 |
uv run check.py --env none # without the Trials
|
| 283 |
```
|
| 284 |
|
| 285 |
+
On the HF cluster, from Legion's checkout, with rootless podman set up as a worker has it:
|
| 286 |
`srun -p hopper-cpu -c 8 --mem=15G bash -c 'source scripts/slurm/podman-node.sh &&
|
| 287 |
+
CONTAINERS_REGISTRIES_CONF=$DS/legion/registries.conf .venv/bin/python $DS/check.py --env podman;
|
| 288 |
podman_node_cleanup'`.
|
| 289 |
|
| 290 |
1. **Generator:** `generate.py` reproduces `tasks/` byte for byte, and another seed gives other
|
|
|
|
| 323 |
the exit is named only in the service's `tree.json`, `tests/expected.json` and
|
| 324 |
`solution/solve.sh`; no folder beside `tasks/` holds a tree.
|
| 325 |
5. **Metrics** (`eval/metrics.py`) on Slurm run directories made of the service's real exports
|
| 326 |
+
and the grader's real grades, with Legion's example spec (`${TREE:-maze-t01}`,
|
| 327 |
`${N:-4}`): with no env files the row's task is `maze-t01` and its team four agents;
|
| 328 |
`run.env` (over `cluster.env`) sets another tree and team size; a team with one agent's
|
| 329 |
results gone keeps that agent and flags its reward and move log as missing; and the row
|
| 330 |
flags Trials of another task than the spec selects (a `run.env` gone) and of an agent the
|
| 331 |
spec didn't plan.
|
| 332 |
6. **Trials** (`--env podman` or `docker`, on `maze-t01`, with agents that need no model):
|
| 333 |
+
- a walker runs Legion's success check in the maze service (false), walks the shortest path
|
| 334 |
with `maze move`, runs it again (true), and scores 1, with the move log and the export in
|
| 335 |
its verifier's folder;
|
| 336 |
- Harbor's oracle agent (`solution/solve.sh`) scores 1;
|
|
|
|
| 341 |
`/logs/artifacts` and `/logs/verifier`, a `reward.txt` of 1, a `json.py` and a
|
| 342 |
`sitecustomize`, makes three moves short of the exit, and scores 0.
|
| 343 |
|
| 344 |
+
Last run on a hopper-cpu node (podman 4.9.3), before the Legion rename: all checks passed.
|
|
|
|
| 345 |
|
| 346 |
## Dummy run
|
| 347 |
|
| 348 |
+
One team, `maze-t01` with N = 4, from the pre-rename `experiments/s3-maze/spec.yaml` (dataset revision
|
| 349 |
`0f1fe651`, whose `tasks/` are this revision's) on the HF cluster on 2026-11-17:
|
| 350 |
`Qwen/Qwen3.8-27B` on the HF router (deepinfra), one hopper-cpu worker of 6 CPUs running the
|
| 351 |
four Trials in rootless podman, and a local board.
|
| 352 |
|
| 353 |
- **The team found the exit.** agent-003 reached it after 154 moves, 10 min 22 s after the
|
| 354 |
+
Trials started. Legion's success check saw it 27 s later, held the run, interrupted the other
|
| 355 |
agents and released the worker; every Trial was graded within a minute and the worker ended,
|
| 356 |
at 11:50 UTC. Only agent-003 scored 1.
|
| 357 |
- **They split the tree on the board** without being told to: agents posted the corridors they
|
|
|
|
| 370 |
- **HF Sandboxes can't run it:** each agent's Trial is two containers (the agent's and its maze
|
| 371 |
service), and HF Sandboxes run one container per Trial. It needs multi-container support
|
| 372 |
there, as AgentEscapeBench does. Until then it runs on docker or podman (the HF cluster).
|
| 373 |
+
- **Private for now**, so whatever resolves and downloads the task (Legion's worker, and
|
| 374 |
+
`legion init`/`launch`) needs a Hub token that can read it. The agents' containers never do.
|
| 375 |
+
- **A new Trial starts a new maze.** If an agent's Trial fails and Legion starts another (or a
|
| 376 |
worker is relaunched), that agent gets a fresh copy of the maze at the start, with a fresh
|
| 377 |
budget, while its Pi session remembers the old walk. `metrics.py` counts moves over all of an
|
| 378 |
agent's Trials, and its reward is its latest Trial's.
|
| 379 |
+
- **The first exit ends the run, not the episode at once:** Legion checks every 30 s, so the
|
| 380 |
other agents may move for up to about 30 s more before their turns are interrupted.
|
| 381 |
- **The grader trusts the maze service.** The agent reaches it only through `maze look` and
|
| 382 |
`maze move` (an internal network, two routes, bodies up to 4 KiB); an agent that could reach
|
| 383 |
the service any other way could forge its record. The service runs without capabilities, with
|
| 384 |
a pids and memory limit, so flooding it only hurts the agent's own maze.
|
| 385 |
- **The move log's `agent`** is the Trial's compose project (`<swarm>-<agent>-tN`), which names
|
| 386 |
+
the Legion agent; `metrics.py` attributes moves by the Trial's folder instead.
|
| 387 |
- **Not the paper's setup:** a per-agent move budget instead of a token allowance (looking and
|
| 388 |
refused moves are free), a message board instead of `message`/`read_messages` tools with
|
| 389 |
+
notifications, Legion's loop prompting again at each turn's end, the moves left in every
|
| 390 |
observation, and N = 1 is a solo control.
|
budget.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
-
"""The move budget (huggingface/
|
| 2 |
(Python 3.10+, no dependencies).
|
| 3 |
|
| 4 |
Simulates searches on the 32 trees in tasks/ with the maze service's own engine
|
| 5 |
(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses what
|
| 6 |
-
the service refuses), without
|
| 7 |
by team size N and per-agent move budget, as the Markdown table in README.md:
|
| 8 |
|
| 9 |
- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the
|
|
|
|
| 1 |
+
"""The move budget (huggingface/legion#115, section 6): `python budget.py [--draws 200]`
|
| 2 |
(Python 3.10+, no dependencies).
|
| 3 |
|
| 4 |
Simulates searches on the 32 trees in tasks/ with the maze service's own engine
|
| 5 |
(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses what
|
| 6 |
+
the service refuses), without Legion or containers, and prints the success rate of each strategy
|
| 7 |
by team size N and per-agent move budget, as the Markdown table in README.md:
|
| 8 |
|
| 9 |
- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the
|
check.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# requires-python = ">=3.12"
|
| 3 |
# dependencies = ["harbor==0.25.0", "pyyaml"]
|
| 4 |
# ///
|
| 5 |
-
"""s3-maze's checks that need no model (huggingface/
|
| 6 |
|
| 7 |
uv run check.py --env podman # all of them; the Trials in rootless podman (README: "Checks")
|
| 8 |
uv run check.py --env docker # the Trials in local docker
|
|
@@ -27,7 +27,7 @@
|
|
| 27 |
no answer names a room other than the current one and its doors (or what the agent asked
|
| 28 |
for); the exit is named only once the agent stands in it. The move log has one record per
|
| 29 |
move request, refused ones included, each with agent, from, to and time, and its accepted
|
| 30 |
-
moves are the walk. success.py (
|
| 31 |
and true after, and false for a missing or linked state file; export.py writes the service's
|
| 32 |
record for the grader; a restarted service resumes the walk. The `maze` command prints the
|
| 33 |
service's JSON and exits 0, 1 for a refused move, 2 for a usage error.
|
|
@@ -51,13 +51,13 @@
|
|
| 51 |
5. Metrics (eval/metrics.py) on Slurm run directories made of real exports and grades, with
|
| 52 |
the example spec's `${TREE:-maze-t01}` and `${N:-4}`: with no env files the row's task is
|
| 53 |
maze-t01 and its team four agents; `run.env` (over `cluster.env`) sets another tree and team
|
| 54 |
-
size, also with comments after quoted and unquoted values (read as
|
| 55 |
with one agent's results gone keeps that agent and flags its reward and move
|
| 56 |
log as missing; and the row flags Trials of another task than the spec selects (a `run.env`
|
| 57 |
gone) and of an agent the spec didn't plan, and a winning move log whose last line was cut
|
| 58 |
off.
|
| 59 |
6. Trials (`--env`), on maze-t01, with agents that need no model:
|
| 60 |
-
- a walker checks
|
| 61 |
with `maze move`, checks it again (true), and scores 1; the verifier's folder then holds
|
| 62 |
the move log and the export;
|
| 63 |
- Harbor's oracle agent (solution/solve.sh) scores 1;
|
|
@@ -681,7 +681,7 @@ def check_files() -> None:
|
|
| 681 |
check(holders == {"environment/maze/tree.json", "tests/expected.json",
|
| 682 |
"solution/solve.sh"}, f"{task.name}: the exit is named in {holders}")
|
| 683 |
beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {
|
| 684 |
-
"tasks", "template", "
|
| 685 |
check(not beside, f"folders beside tasks/: {sorted(beside)}")
|
| 686 |
check(not LABEL.search("".join(p.read_text(errors="ignore")
|
| 687 |
for p in (HERE / "template").rglob("*") if p.is_file())),
|
|
@@ -690,7 +690,7 @@ def check_files() -> None:
|
|
| 690 |
|
| 691 |
# ------------------------------------------------------------------ metrics
|
| 692 |
|
| 693 |
-
# The example spec's lines that metrics.py reads (
|
| 694 |
RUN_SPEC = """name: ${RUN_NAME:-s3-maze}
|
| 695 |
naming: consecutive-id
|
| 696 |
task:
|
|
@@ -704,7 +704,7 @@ agents:
|
|
| 704 |
|
| 705 |
def run_dir(root: Path, work: Path, tree: str, walks: dict[str, bool],
|
| 706 |
env_files: dict[str, str]) -> Path:
|
| 707 |
-
"""A Slurm run's directory, as `
|
| 708 |
files and, per agent in `walks`, one Trial of `tree` (the exit reached or not) graded by the
|
| 709 |
task's own grader on the maze service's own export."""
|
| 710 |
task = HERE / "tasks" / tree
|
|
@@ -738,7 +738,7 @@ def check_metrics(work: Path) -> int:
|
|
| 738 |
{"cluster.env": "N=3\nTREE=maze-t05\n",
|
| 739 |
"run.env": "#TREE=maze-t01\nTREE=maze-t02\nN=2\nRUN_NAME=s3-maze-b\n"},
|
| 740 |
"maze-t02", 2, []),
|
| 741 |
-
# comments after values, read as
|
| 742 |
# its quote, an unquoted one at ` #`
|
| 743 |
"comments in env files": ("maze-t02", {"agent-001": True, "agent-002": False},
|
| 744 |
{"cluster.env": "export N=3 # three\nTREE=maze-t05 # five\n",
|
|
|
|
| 2 |
# requires-python = ">=3.12"
|
| 3 |
# dependencies = ["harbor==0.25.0", "pyyaml"]
|
| 4 |
# ///
|
| 5 |
+
"""s3-maze's checks that need no model (huggingface/legion#115, section 5):
|
| 6 |
|
| 7 |
uv run check.py --env podman # all of them; the Trials in rootless podman (README: "Checks")
|
| 8 |
uv run check.py --env docker # the Trials in local docker
|
|
|
|
| 27 |
no answer names a room other than the current one and its doors (or what the agent asked
|
| 28 |
for); the exit is named only once the agent stands in it. The move log has one record per
|
| 29 |
move request, refused ones included, each with agent, from, to and time, and its accepted
|
| 30 |
+
moves are the walk. success.py (legion's success_check) says false until the exit is reached
|
| 31 |
and true after, and false for a missing or linked state file; export.py writes the service's
|
| 32 |
record for the grader; a restarted service resumes the walk. The `maze` command prints the
|
| 33 |
service's JSON and exits 0, 1 for a refused move, 2 for a usage error.
|
|
|
|
| 51 |
5. Metrics (eval/metrics.py) on Slurm run directories made of real exports and grades, with
|
| 52 |
the example spec's `${TREE:-maze-t01}` and `${N:-4}`: with no env files the row's task is
|
| 53 |
maze-t01 and its team four agents; `run.env` (over `cluster.env`) sets another tree and team
|
| 54 |
+
size, also with comments after quoted and unquoted values (read as legion reads them); a team
|
| 55 |
with one agent's results gone keeps that agent and flags its reward and move
|
| 56 |
log as missing; and the row flags Trials of another task than the spec selects (a `run.env`
|
| 57 |
gone) and of an agent the spec didn't plan, and a winning move log whose last line was cut
|
| 58 |
off.
|
| 59 |
6. Trials (`--env`), on maze-t01, with agents that need no model:
|
| 60 |
+
- a walker checks legion's success_check in the maze service (false), walks the shortest path
|
| 61 |
with `maze move`, checks it again (true), and scores 1; the verifier's folder then holds
|
| 62 |
the move log and the export;
|
| 63 |
- Harbor's oracle agent (solution/solve.sh) scores 1;
|
|
|
|
| 681 |
check(holders == {"environment/maze/tree.json", "tests/expected.json",
|
| 682 |
"solution/solve.sh"}, f"{task.name}: the exit is named in {holders}")
|
| 683 |
beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {
|
| 684 |
+
"tasks", "template", "legion", "eval", ".cache", "__pycache__", ".git"}
|
| 685 |
check(not beside, f"folders beside tasks/: {sorted(beside)}")
|
| 686 |
check(not LABEL.search("".join(p.read_text(errors="ignore")
|
| 687 |
for p in (HERE / "template").rglob("*") if p.is_file())),
|
|
|
|
| 690 |
|
| 691 |
# ------------------------------------------------------------------ metrics
|
| 692 |
|
| 693 |
+
# The example spec's lines that metrics.py reads (Legion's experiments/s3-maze/spec.yaml)
|
| 694 |
RUN_SPEC = """name: ${RUN_NAME:-s3-maze}
|
| 695 |
naming: consecutive-id
|
| 696 |
task:
|
|
|
|
| 704 |
|
| 705 |
def run_dir(root: Path, work: Path, tree: str, walks: dict[str, bool],
|
| 706 |
env_files: dict[str, str]) -> Path:
|
| 707 |
+
"""A Slurm run's directory, as `legion init` and the workers leave it: the spec, the env
|
| 708 |
files and, per agent in `walks`, one Trial of `tree` (the exit reached or not) graded by the
|
| 709 |
task's own grader on the maze service's own export."""
|
| 710 |
task = HERE / "tasks" / tree
|
|
|
|
| 738 |
{"cluster.env": "N=3\nTREE=maze-t05\n",
|
| 739 |
"run.env": "#TREE=maze-t01\nTREE=maze-t02\nN=2\nRUN_NAME=s3-maze-b\n"},
|
| 740 |
"maze-t02", 2, []),
|
| 741 |
+
# comments after values, read as legion's read_env_file does: a quoted value ends at
|
| 742 |
# its quote, an unquoted one at ` #`
|
| 743 |
"comments in env files": ("maze-t02", {"agent-001": True, "agent-002": False},
|
| 744 |
{"cluster.env": "export N=3 # three\nTREE=maze-t05 # five\n",
|
eval/metrics.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
-
"""One row per team from s³ runs (huggingface/
|
| 2 |
RUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.
|
| 3 |
|
| 4 |
s3-aggregation's eval/metrics.py, with s3-maze's move-log metrics added (`maze_moves` in
|
| 5 |
-
EXTRAS). A run directory is one team: a local run's bundle (`.
|
| 6 |
-
docs/local.md), or a Slurm run's directory (`
|
| 7 |
workers copy what a run is graded on into `results/`. Under either, each agent's Trials
|
| 8 |
(`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the board
|
| 9 |
export (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (one
|
|
@@ -267,7 +267,7 @@ PLACEHOLDER = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)(?::-([^}]*))?\}")
|
|
| 267 |
|
| 268 |
|
| 269 |
def env_value(raw: str) -> str:
|
| 270 |
-
"""A `NAME=value` line's value as
|
| 271 |
ends at its closing quote (what follows is a comment), an unquoted one at ` #`."""
|
| 272 |
value = raw.strip()
|
| 273 |
if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0:
|
|
@@ -277,7 +277,7 @@ def env_value(raw: str) -> str:
|
|
| 277 |
|
| 278 |
def run_values(run_dir: Path) -> dict[str, str]:
|
| 279 |
"""The run's `cluster.env` then `run.env` (later wins), as the jobs read them: what fills
|
| 280 |
-
the spec's `${VAR}`s. Lines
|
| 281 |
values = {}
|
| 282 |
for name in ("cluster.env", "run.env"):
|
| 283 |
path = run_dir / name
|
|
@@ -292,13 +292,13 @@ def run_values(run_dir: Path) -> dict[str, str]:
|
|
| 292 |
|
| 293 |
|
| 294 |
def expand(text: str, values: dict[str, str]) -> str:
|
| 295 |
-
"""`${VAR}` and `${VAR:-default}` in the spec's text, as
|
| 296 |
return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]),
|
| 297 |
text)
|
| 298 |
|
| 299 |
|
| 300 |
def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict:
|
| 301 |
-
"""What a Slurm run's directory says: its spec as the run resolved it (`
|
| 302 |
of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their
|
| 303 |
defaults) and the Trials the workers kept. The spec gives the task and the roster: every
|
| 304 |
agent it planned is in the row, so one whose results are missing is flagged, not dropped.
|
|
|
|
| 1 |
+
"""One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.py
|
| 2 |
RUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.
|
| 3 |
|
| 4 |
s3-aggregation's eval/metrics.py, with s3-maze's move-log metrics added (`maze_moves` in
|
| 5 |
+
EXTRAS). A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`,
|
| 6 |
+
docs/local.md), or a Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where the
|
| 7 |
workers copy what a run is graded on into `results/`. Under either, each agent's Trials
|
| 8 |
(`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the board
|
| 9 |
export (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (one
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def env_value(raw: str) -> str:
|
| 270 |
+
"""A `NAME=value` line's value as Legion reads it (specrender.read_env_file): a quoted value
|
| 271 |
ends at its closing quote (what follows is a comment), an unquoted one at ` #`."""
|
| 272 |
value = raw.strip()
|
| 273 |
if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0:
|
|
|
|
| 277 |
|
| 278 |
def run_values(run_dir: Path) -> dict[str, str]:
|
| 279 |
"""The run's `cluster.env` then `run.env` (later wins), as the jobs read them: what fills
|
| 280 |
+
the spec's `${VAR}`s. Lines Legion would refuse (no `=`, a bad name) are skipped."""
|
| 281 |
values = {}
|
| 282 |
for name in ("cluster.env", "run.env"):
|
| 283 |
path = run_dir / name
|
|
|
|
| 292 |
|
| 293 |
|
| 294 |
def expand(text: str, values: dict[str, str]) -> str:
|
| 295 |
+
"""`${VAR}` and `${VAR:-default}` in the spec's text, as Legion fills them (empty = unset)."""
|
| 296 |
return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]),
|
| 297 |
text)
|
| 298 |
|
| 299 |
|
| 300 |
def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict:
|
| 301 |
+
"""What a Slurm run's directory says: its spec as the run resolved it (`legion init`'s copy
|
| 302 |
of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their
|
| 303 |
defaults) and the Trials the workers kept. The spec gives the task and the roster: every
|
| 304 |
agent it planned is in the row, so one whose results are missing is flagged, not dropped.
|
generate.py
CHANGED
|
@@ -21,7 +21,7 @@ import random
|
|
| 21 |
import shutil
|
| 22 |
from pathlib import Path
|
| 23 |
|
| 24 |
-
SEED = 115 # huggingface/
|
| 25 |
TREES = 32 # the paper's held-out set size
|
| 26 |
BRANCHING, CORRIDOR, DEPTH = 3, 10, 3
|
| 27 |
DIGITS = 4 # room labels R1000 .. R9999
|
|
|
|
| 21 |
import shutil
|
| 22 |
from pathlib import Path
|
| 23 |
|
| 24 |
+
SEED = 115 # huggingface/legion#115
|
| 25 |
TREES = 32 # the paper's held-out set size
|
| 26 |
BRANCHING, CORRIDOR, DEPTH = 3, 10, 3
|
| 27 |
DIGITS = 4 # room labels R1000 .. R9999
|
{flock → legion}/registries.conf
RENAMED
|
File without changes
|
{flock → legion}/spec.template.yaml
RENAMED
|
@@ -59,7 +59,7 @@ where:
|
|
| 59 |
backend: docker
|
| 60 |
# The HF cluster: a Slurm worker on hopper-cpu running the team in rootless podman (podman
|
| 61 |
# 4.9), with a local board on that worker (a new one each run). Results reach
|
| 62 |
-
# <run dir>/results/ (
|
| 63 |
cluster:
|
| 64 |
namespace: ${NAMESPACE}
|
| 65 |
bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name>
|
|
|
|
| 59 |
backend: docker
|
| 60 |
# The HF cluster: a Slurm worker on hopper-cpu running the team in rootless podman (podman
|
| 61 |
# 4.9), with a local board on that worker (a new one each run). Results reach
|
| 62 |
+
# <run dir>/results/ (Legion's docs/slurm.md "Results").
|
| 63 |
cluster:
|
| 64 |
namespace: ${NAMESPACE}
|
| 65 |
bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name>
|
{flock → legion}/sweep/README.md
RENAMED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
# s3-maze scaling sweep
|
| 2 |
|
| 3 |
-
The s³ paper's maze results (Figure 4 bottom: success against swarm size) with
|
| 4 |
-
of this dataset at N = 1, 2, 4, 8 and 16 agents, one team each, every team its own
|
| 5 |
the HF cluster, for one model per grid. The results for `Qwen/Qwen3.5-27B` and
|
| 6 |
-
`Qwen/Qwen3.5-2B` are on
|
| 7 |
-
huggingface/
|
| 8 |
`HuggingFaceSwarms/s3-maze-results`.
|
| 9 |
|
| 10 |
| File | |
|
|
@@ -17,23 +17,23 @@ huggingface/flock#123's description; the raw runs are in the private
|
|
| 17 |
|
| 18 |
## Run it
|
| 19 |
|
| 20 |
-
From
|
| 21 |
-
`
|
| 22 |
|
| 23 |
```sh
|
| 24 |
sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 \
|
| 25 |
-
-o vllm-%j.log $DS/
|
| 26 |
-
uv run python $DS/
|
| 27 |
--urls http://<node>:8011/v1,http://<node>:8012/v1,... --per-server 12 --parallel 50 \
|
| 28 |
--root runs/q27 --health servers.jsonl --dataset HuggingFaceSwarms/s3-maze-results
|
| 29 |
-
uv run $DS/
|
| 30 |
```
|
| 31 |
|
| 32 |
Each team is team.py's cluster spec with the model on the servers (`urls`): `compute: slurm`, one
|
| 33 |
worker on hopper-cpu running the team's compose Trials in rootless podman with a local board,
|
| 34 |
and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per maze service and two
|
| 35 |
more (at least 4), at 1900 MB per CPU. The driver inits and launches a team, waits for the first
|
| 36 |
-
exit (and the grading) or the end of the loop, releases it (`
|
| 37 |
ends its controller), and appends metrics.py's row with the team's exit branch and wall time.
|
| 38 |
`--hint` gives every team the protocol hint (`team.py --hint`); the board allows `#general`
|
| 39 |
only (`max_channels: 1`).
|
|
@@ -46,7 +46,7 @@ reward and move log and the board export, and no agent's model server thrashing
|
|
| 46 |
more during it (below). Anything else is the infrastructure's: the team runs again as
|
| 47 |
`<task>-rK`, and `setaside.py` says why. A worker still not started 3 minutes after its launch
|
| 48 |
is released at once, so its team reruns without waiting out its time cap. A rerun's server
|
| 49 |
-
capacity is reserved under the `-rK` name it runs as, since
|
| 50 |
What the model does (no move, no post, no exit) is a result. A restarted driver adopts the teams
|
| 51 |
in flight and keeps each team's own start time.
|
| 52 |
|
|
@@ -67,7 +67,7 @@ run. So:
|
|
| 67 |
- **at most `--per-server` agents per server** (9 to 19 for the 27B model, read again from
|
| 68 |
`<root>/per_server` before each launch, so it can change while the grid runs; the 2B model's
|
| 69 |
smaller cache entries, ~13M tokens per B200, fit a whole grid on one GPU);
|
| 70 |
-
- **every team gets the whole shared list.**
|
| 71 |
sends each agent to a server by hashing its run and its name over the URLs, so teams with
|
| 72 |
`naming: consecutive-id` spread over the servers instead of every team's `agent-001` calling
|
| 73 |
the same one. The driver hashes a new team's agents the same way and starts it once the
|
|
@@ -81,7 +81,7 @@ run. So:
|
|
| 81 |
|
| 82 |
Rootless podman on hopper-cpu can't hold a container to a memory limit, so a runaway process in
|
| 83 |
one agent's container (the 2B model's agents sometimes start one) grows the whole worker until
|
| 84 |
-
|
| 85 |
For the 2B grid, `--cpus-per-agent 2` doubles each agent's share of the worker (and its memory,
|
| 86 |
at 1900 MB per CPU) and `--memory-ladder 0.97,0.98,0.99` lets the worker go closer to its limit
|
| 87 |
before the guard acts.
|
|
|
|
| 1 |
# s3-maze scaling sweep
|
| 2 |
|
| 3 |
+
The s³ paper's maze results (Figure 4 bottom: success against swarm size) with Legion: every tree
|
| 4 |
+
of this dataset at N = 1, 2, 4, 8 and 16 agents, one team each, every team its own Legion run on
|
| 5 |
the HF cluster, for one model per grid. The results for `Qwen/Qwen3.5-27B` and
|
| 6 |
+
`Qwen/Qwen3.5-2B` are on Legion's `s3-maze-results` branch (`experiments/s3-maze/results/`) and in
|
| 7 |
+
huggingface/legion#123's description; the raw runs are in the private
|
| 8 |
`HuggingFaceSwarms/s3-maze-results`.
|
| 9 |
|
| 10 |
| File | |
|
|
|
|
| 17 |
|
| 18 |
## Run it
|
| 19 |
|
| 20 |
+
From Legion's checkout (at or after `0401df9`, legion#129), with this dataset on the shared disk (`DS`; the workers read
|
| 21 |
+
`legion/registries.conf`) and the private-repo credential helper exported (Legion's docs/slurm.md):
|
| 22 |
|
| 23 |
```sh
|
| 24 |
sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 \
|
| 25 |
+
-o vllm-%j.log $DS/legion/sweep/serve-vllm.sbatch # one per GPU; the log ends with its URL
|
| 26 |
+
uv run python $DS/legion/sweep/sweep.py --model Qwen/Qwen3.5-27B --tag q27- --revision <sha> \
|
| 27 |
--urls http://<node>:8011/v1,http://<node>:8012/v1,... --per-server 12 --parallel 50 \
|
| 28 |
--root runs/q27 --health servers.jsonl --dataset HuggingFaceSwarms/s3-maze-results
|
| 29 |
+
uv run $DS/legion/sweep/plot.py --series Qwen3.5-27B=runs/q27 --series Qwen3.5-2B=runs/q2 --out results
|
| 30 |
```
|
| 31 |
|
| 32 |
Each team is team.py's cluster spec with the model on the servers (`urls`): `compute: slurm`, one
|
| 33 |
worker on hopper-cpu running the team's compose Trials in rootless podman with a local board,
|
| 34 |
and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per maze service and two
|
| 35 |
more (at least 4), at 1900 MB per CPU. The driver inits and launches a team, waits for the first
|
| 36 |
+
exit (and the grading) or the end of the loop, releases it (`legion stop --release`, which also
|
| 37 |
ends its controller), and appends metrics.py's row with the team's exit branch and wall time.
|
| 38 |
`--hint` gives every team the protocol hint (`team.py --hint`); the board allows `#general`
|
| 39 |
only (`max_channels: 1`).
|
|
|
|
| 46 |
more during it (below). Anything else is the infrastructure's: the team runs again as
|
| 47 |
`<task>-rK`, and `setaside.py` says why. A worker still not started 3 minutes after its launch
|
| 48 |
is released at once, so its team reruns without waiting out its time cap. A rerun's server
|
| 49 |
+
capacity is reserved under the `-rK` name it runs as, since legion hashes agents by run and name.
|
| 50 |
What the model does (no move, no post, no exit) is a result. A restarted driver adopts the teams
|
| 51 |
in flight and keeps each team's own start time.
|
| 52 |
|
|
|
|
| 67 |
- **at most `--per-server` agents per server** (9 to 19 for the 27B model, read again from
|
| 68 |
`<root>/per_server` before each launch, so it can change while the grid runs; the 2B model's
|
| 69 |
smaller cache entries, ~13M tokens per B200, fit a whole grid on one GPU);
|
| 70 |
+
- **every team gets the whole shared list.** Legion (from huggingface/legion#129, `0401df9`)
|
| 71 |
sends each agent to a server by hashing its run and its name over the URLs, so teams with
|
| 72 |
`naming: consecutive-id` spread over the servers instead of every team's `agent-001` calling
|
| 73 |
the same one. The driver hashes a new team's agents the same way and starts it once the
|
|
|
|
| 81 |
|
| 82 |
Rootless podman on hopper-cpu can't hold a container to a memory limit, so a runaway process in
|
| 83 |
one agent's container (the 2B model's agents sometimes start one) grows the whole worker until
|
| 84 |
+
Legion's memory guard drains or preempts it, and the team runs again on a second incarnation.
|
| 85 |
For the 2B grid, `--cpus-per-agent 2` doubles each agent's share of the worker (and its memory,
|
| 86 |
at 1900 MB per CPU) and `--memory-ladder 0.97,0.98,0.99` lets the worker go closer to its limit
|
| 87 |
before the guard acts.
|
{flock → legion}/sweep/health-log.sh
RENAMED
|
File without changes
|
{flock → legion}/sweep/plot.py
RENAMED
|
@@ -4,7 +4,7 @@
|
|
| 4 |
# ///
|
| 5 |
"""The s3-maze sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`):
|
| 6 |
|
| 7 |
-
uv run
|
| 8 |
|
| 9 |
- `scaling.png`, eight panels, one series per model, after the s³ paper's maze results
|
| 10 |
(Figure 4, bottom: success against swarm size; Figure 5c: success by the branch that holds
|
|
@@ -267,7 +267,7 @@ def main(argv=None) -> int:
|
|
| 267 |
parser.add_argument("--series", action="append", required=True,
|
| 268 |
help="NAME=ROOT, repeatable; NAME=ROOT@light draws it lighter, in the "
|
| 269 |
"colour of the series before it, without its best-of-N line")
|
| 270 |
-
parser.add_argument("--title", default="s3-maze with
|
| 271 |
"size")
|
| 272 |
parser.add_argument("--out", type=Path, required=True)
|
| 273 |
args = parser.parse_args(argv)
|
|
|
|
| 4 |
# ///
|
| 5 |
"""The s3-maze sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`):
|
| 6 |
|
| 7 |
+
uv run legion/sweep/plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>
|
| 8 |
|
| 9 |
- `scaling.png`, eight panels, one series per model, after the s³ paper's maze results
|
| 10 |
(Figure 4, bottom: success against swarm size; Figure 5c: success by the branch that holds
|
|
|
|
| 267 |
parser.add_argument("--series", action="append", required=True,
|
| 268 |
help="NAME=ROOT, repeatable; NAME=ROOT@light draws it lighter, in the "
|
| 269 |
"colour of the series before it, without its best-of-N line")
|
| 270 |
+
parser.add_argument("--title", default="s3-maze with legion: success and cost against swarm "
|
| 271 |
"size")
|
| 272 |
parser.add_argument("--out", type=Path, required=True)
|
| 273 |
args = parser.parse_args(argv)
|
{flock → legion}/sweep/serve-vllm.sbatch
RENAMED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
#!/bin/bash
|
| 2 |
# The s3-maze sweep's model server: one vLLM on one GPU, in Pyxis on hopper-b200, as
|
| 3 |
-
# s3-aggregation's
|
| 4 |
# (podman on hopper-cpu) reach it by this node's address.
|
| 5 |
# sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 -o <dir>/vllm-%j.log serve-vllm.sbatch
|
| 6 |
# Its log ends with: serving <model> at http://<node address>:<port>/v1
|
|
|
|
| 1 |
#!/bin/bash
|
| 2 |
# The s3-maze sweep's model server: one vLLM on one GPU, in Pyxis on hopper-b200, as
|
| 3 |
+
# s3-aggregation's legion/sweep/serve-vllm.sbatch (the same image and parsers). The agents
|
| 4 |
# (podman on hopper-cpu) reach it by this node's address.
|
| 5 |
# sbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 -o <dir>/vllm-%j.log serve-vllm.sbatch
|
| 6 |
# Its log ends with: serving <model> at http://<node address>:<port>/v1
|
{flock → legion}/sweep/setaside.py
RENAMED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
-
"""Why each set-aside attempt of a grid didn't count: `python
|
| 2 |
from `<root>/rows-discarded.jsonl` and the attempt's own logs (s3-aggregation's, for the maze).
|
| 3 |
A restarted driver scores an attempt again from what it left, so one attempt can have several
|
| 4 |
entries: its reason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
|
| 5 |
|
| 6 |
- it ran while its model server was overloaded (`--overloaded`), or an agent's server thrashed
|
| 7 |
for 5 minutes or more (`--health`);
|
| 8 |
-
- the worker was relaunched (more than one incarnation:
|
| 9 |
memory or after a node failure;
|
| 10 |
- the launch failed (or was cancelled), so its controller never came up;
|
| 11 |
- the worker never started, or started more than 2 min after the launch (the loop counts from
|
|
@@ -31,7 +31,7 @@ def reason(row: dict, run_dir: Path) -> str:
|
|
| 31 |
logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*")
|
| 32 |
if p.is_file()} if (run_dir / "logs").is_dir() else {}
|
| 33 |
workers = " ".join(v for k, v in logs.items() if "-agent-w" in k)
|
| 34 |
-
controllers = " ".join(v for k, v in logs.items() if k.startswith(("
|
| 35 |
"controller-")))
|
| 36 |
if "overloaded model server" in (row.get("set_aside") or ""):
|
| 37 |
return "ran on an overloaded model server (one 27B GPU, KV-cache thrash)"
|
|
@@ -41,8 +41,8 @@ def reason(row: dict, run_dir: Path) -> str:
|
|
| 41 |
if re.search(r"CANCELED: unresponsive", controllers):
|
| 42 |
return "worker stopped answering (e.g. while grading its Trials) and was relaunched"
|
| 43 |
if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers):
|
| 44 |
-
return "worker relaunched after running out of memory (
|
| 45 |
-
return "worker relaunched after a node failure (
|
| 46 |
if row.get("outcome") == "launch":
|
| 47 |
return "launch failed or was cancelled (the controller ended before it came up)"
|
| 48 |
if row.get("worker_wait_s") is None:
|
|
|
|
| 1 |
+
"""Why each set-aside attempt of a grid didn't count: `python legion/sweep/setaside.py <root>`,
|
| 2 |
from `<root>/rows-discarded.jsonl` and the attempt's own logs (s3-aggregation's, for the maze).
|
| 3 |
A restarted driver scores an attempt again from what it left, so one attempt can have several
|
| 4 |
entries: its reason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
|
| 5 |
|
| 6 |
- it ran while its model server was overloaded (`--overloaded`), or an agent's server thrashed
|
| 7 |
for 5 minutes or more (`--health`);
|
| 8 |
+
- the worker was relaunched (more than one incarnation: legion#121's case), after running out of
|
| 9 |
memory or after a node failure;
|
| 10 |
- the launch failed (or was cancelled), so its controller never came up;
|
| 11 |
- the worker never started, or started more than 2 min after the launch (the loop counts from
|
|
|
|
| 31 |
logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*")
|
| 32 |
if p.is_file()} if (run_dir / "logs").is_dir() else {}
|
| 33 |
workers = " ".join(v for k, v in logs.items() if "-agent-w" in k)
|
| 34 |
+
controllers = " ".join(v for k, v in logs.items() if k.startswith(("legion-ctl-",
|
| 35 |
"controller-")))
|
| 36 |
if "overloaded model server" in (row.get("set_aside") or ""):
|
| 37 |
return "ran on an overloaded model server (one 27B GPU, KV-cache thrash)"
|
|
|
|
| 41 |
if re.search(r"CANCELED: unresponsive", controllers):
|
| 42 |
return "worker stopped answering (e.g. while grading its Trials) and was relaunched"
|
| 43 |
if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers):
|
| 44 |
+
return "worker relaunched after running out of memory (legion#121's case)"
|
| 45 |
+
return "worker relaunched after a node failure (legion#121's case)"
|
| 46 |
if row.get("outcome") == "launch":
|
| 47 |
return "launch failed or was cancelled (the controller ended before it came up)"
|
| 48 |
if row.get("worker_wait_s") is None:
|
{flock → legion}/sweep/sweep.py
RENAMED
|
@@ -1,22 +1,22 @@
|
|
| 1 |
"""The s3-maze scaling sweep on the HF cluster, one command per model for the whole grid, run
|
| 2 |
-
from
|
| 3 |
|
| 4 |
-
uv run python <this dataset>/
|
| 5 |
--model Qwen/Qwen3.5-27B --tag q27- --revision <sha> [--trees 1-32] \\
|
| 6 |
-
[--agents 1,2,4,8,16] [--parallel 20] [--max-agents 64] [--root .
|
| 7 |
|
| 8 |
-
s3-aggregation's
|
| 9 |
(`compute: slurm`, podman agents on hopper-cpu, a local board on its one worker), from team.py's
|
| 10 |
cluster spec with the sweep's model on `urls`: the same board rules, loop, limits and move
|
| 11 |
budget at every N, and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per
|
| 12 |
-
maze service and two more (at least 4), at 1900 MB per CPU. Per team: `
|
| 13 |
-
`
|
| 14 |
-
graded) or the loop is done and the agents are idle; `
|
| 15 |
Trials of a run nobody won, and ends the controller in either case); then eval/metrics.py's row
|
| 16 |
plus the wall time and the tree's exit branch go to `<root>/rows.jsonl`.
|
| 17 |
|
| 18 |
A run counts only when its worker started within WAIT_LIMIT of its launch (the loop's time
|
| 19 |
-
counts from the launch), on one worker incarnation (
|
| 20 |
nothing missing (every agent's reward and move log, the board export). Anything else is the
|
| 21 |
infrastructure's, so the team runs again as `<task>-rK` and the attempt goes to
|
| 22 |
`rows-discarded.jsonl`; what the model does (no move, no post, no exit) is a result. A team with
|
|
@@ -51,11 +51,11 @@ import httpx
|
|
| 51 |
import yaml
|
| 52 |
from huggingface_hub import HfApi, get_token
|
| 53 |
|
| 54 |
-
from
|
| 55 |
|
| 56 |
HERE = Path(__file__).resolve().parent
|
| 57 |
DATASET_DIR = HERE.parents[1]
|
| 58 |
-
REPO = Path.cwd() #
|
| 59 |
SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")
|
| 60 |
lock, init_lock = threading.Lock(), threading.Semaphore(4)
|
| 61 |
LOST, GONE = "controller lost", "no controller left"
|
|
@@ -95,10 +95,10 @@ def numbers(text: str) -> list[int]:
|
|
| 95 |
return out
|
| 96 |
|
| 97 |
|
| 98 |
-
def
|
| 99 |
-
env = {**os.environ, "
|
| 100 |
env.pop("VIRTUAL_ENV", None)
|
| 101 |
-
return subprocess.run([str(Path(sys.executable).with_name("
|
| 102 |
env=env, capture_output=True, text=True, timeout=timeout, check=False)
|
| 103 |
|
| 104 |
|
|
@@ -173,7 +173,7 @@ def job_state(name: str) -> str:
|
|
| 173 |
|
| 174 |
|
| 175 |
def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
|
| 176 |
-
"""Poll `
|
| 177 |
('success'), or the loop is done and every agent is idle ('done'): or why not. A controller
|
| 178 |
that stops answering and isn't running (a spot reclaim requeued it, or it is gone) is LOST."""
|
| 179 |
deadline, unanswered, stopped = time.monotonic() + timeout, 0, None
|
|
@@ -184,10 +184,10 @@ def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
|
|
| 184 |
if (launches and not any((run_dir / "logs").glob("*-agent-w*.out"))
|
| 185 |
and time.time() - min(p.stat().st_mtime for p in launches) > WAIT_LIMIT + 60):
|
| 186 |
return f"worker not started {WAIT_LIMIT + 60} s after its launch"
|
| 187 |
-
status =
|
| 188 |
text = status.stdout
|
| 189 |
unanswered = unanswered + 1 if status.returncode != 0 else 0
|
| 190 |
-
if unanswered >= 3 and job_state(f"
|
| 191 |
return LOST
|
| 192 |
if re.search(r"crashloop|launch_refused", text):
|
| 193 |
return "worker failed: " + " ".join(text.split())[:300]
|
|
@@ -204,13 +204,13 @@ def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
|
|
| 204 |
|
| 205 |
|
| 206 |
def release(run_dir: Path, name: str) -> bool:
|
| 207 |
-
"""`
|
| 208 |
controller; then make sure no job of the run is left."""
|
| 209 |
-
out =
|
| 210 |
# once the worker is gone its results are on the shared disk: a controller still up a
|
| 211 |
# minute later (it sometimes outlives the release) only holds the team's slot, and SIGTERM
|
| 212 |
# makes it push its state and exit
|
| 213 |
-
for job, wait in ((f"{name}-agent-w0000", 900), (f"
|
| 214 |
for _ in range(wait // 10): # a draining worker is still grading its Trials
|
| 215 |
if not job_state(job):
|
| 216 |
break
|
|
@@ -231,7 +231,7 @@ def attempt(args, root: Path, secrets: Path, tree: int, n: int, name: str,
|
|
| 231 |
# a previous driver launched it and stopped before its row: finish it from here (its
|
| 232 |
# time cap counts from its own start, cluster.env's), or, with its controller gone,
|
| 233 |
# score what it left
|
| 234 |
-
alive = bool(job_state(f"
|
| 235 |
say(name, "adopting the run a previous driver launched" + ("" if alive else
|
| 236 |
" (no controller left)"))
|
| 237 |
return finish(args, run_dir, name, tree, n, (run_dir / "cluster.env").stat().st_mtime,
|
|
@@ -246,7 +246,7 @@ def attempt(args, root: Path, secrets: Path, tree: int, n: int, name: str,
|
|
| 246 |
log.parent.mkdir(parents=True, exist_ok=True)
|
| 247 |
for tries in range(6): # its checks probe the model servers, which may be busy
|
| 248 |
with init_lock: # a few at a time: many at once race on the bucket's write check
|
| 249 |
-
init =
|
| 250 |
str(profile(root)), "--secrets", str(secrets))
|
| 251 |
log.write_text(init.stdout + init.stderr)
|
| 252 |
if init.returncode == 0:
|
|
@@ -257,7 +257,7 @@ def attempt(args, root: Path, secrets: Path, tree: int, n: int, name: str,
|
|
| 257 |
say(name, "init failed 6 times:", failed or init.stdout[-300:], "(log:", log, ")")
|
| 258 |
return None
|
| 259 |
say(name, "launching")
|
| 260 |
-
launch =
|
| 261 |
if launch.returncode != 0:
|
| 262 |
say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:])
|
| 263 |
return finish(args, run_dir, name, tree, n, started, "launch")
|
|
@@ -271,7 +271,7 @@ def finish(args, run_dir: Path, name: str, tree: int, n: int, started: float,
|
|
| 271 |
why = why or wait_done(run_dir, name, n, max(0.0, args.team_timeout - (time.time() - started)))
|
| 272 |
if why == LOST: # nothing to release: end its jobs, and the team runs again
|
| 273 |
say(name, "controller lost (spot reclaim?): cancelling its jobs")
|
| 274 |
-
for job in (f"
|
| 275 |
subprocess.run(["scancel", "-n", job], check=False)
|
| 276 |
released = False
|
| 277 |
elif why == GONE: # its rewards and export are on disk, or it doesn't count
|
|
@@ -284,7 +284,7 @@ def finish(args, run_dir: Path, name: str, tree: int, n: int, started: float,
|
|
| 284 |
"model": args.model, "tree": tree, "exit_branch": exit_branch(tree),
|
| 285 |
"wall_s": round(ended - started, 1), "outcome": why, "released": released,
|
| 286 |
# each launch of the worker slot writes one env file: more than one is a relaunch or a
|
| 287 |
-
# preemption, whose results a later incarnation overwrites (
|
| 288 |
"incarnations": len(list((run_dir / "launch").glob("*.env"))),
|
| 289 |
"worker_wait_s": worker_wait(run_dir),
|
| 290 |
"thrashed_min": thrashed_minutes(run_dir, n, started, ended),
|
|
@@ -350,16 +350,16 @@ def run_team(args, root: Path, secrets: Path, tree: int, n: int, urls: list[str]
|
|
| 350 |
slots: "Slots", held: dict) -> dict | None:
|
| 351 |
"""A team, run again (as `<task>-rK`) until its run counts. `held["run"]` is the run name its
|
| 352 |
server capacity is reserved under: each attempt moves the reservation to its own name, since
|
| 353 |
-
|
| 354 |
task = f"{args.tag}maze-t{tree:02d}-n{n:02d}"
|
| 355 |
row = None
|
| 356 |
for reruns in range(args.max_reruns + 1):
|
| 357 |
name = task if reruns == 0 else f"{task}-r{reruns}"
|
| 358 |
if name != held["run"] and (not (root / "runs" / name).exists()
|
| 359 |
-
or job_state(f"
|
| 360 |
slots.give(n, held["run"], urls) # a finished attempt is only scored again: keep
|
| 361 |
held["run"] = name
|
| 362 |
-
slots.take(n, name, urls if job_state(f"
|
| 363 |
row = attempt(args, root, secrets, tree, n, name, urls)
|
| 364 |
if row is None:
|
| 365 |
return None
|
|
@@ -383,8 +383,8 @@ def run_team(args, root: Path, secrets: Path, tree: int, n: int, urls: list[str]
|
|
| 383 |
|
| 384 |
|
| 385 |
def agents_on(urls: list[str], n: int, run: str) -> Counter:
|
| 386 |
-
"""How many of run `run`'s agents (agent-001 .. agent-00N) call each server:
|
| 387 |
-
each agent's run and name over the URLs (Inference.endpoint_for,
|
| 388 |
shared list spread over its servers."""
|
| 389 |
block = Inference(urls=urls)
|
| 390 |
return Counter(block.endpoint_for(run, f"agent-{k:03d}") for k in range(1, n + 1))
|
|
@@ -393,7 +393,7 @@ def agents_on(urls: list[str], n: int, run: str) -> Counter:
|
|
| 393 |
class Slots:
|
| 394 |
"""At most `parallel` teams, `max_agents` agents and `per_server` agents per model server
|
| 395 |
(`<root>/max_agents` and `<root>/per_server` override them while the driver runs) in flight,
|
| 396 |
-
granted in order. Every team gets the whole shared list;
|
| 397 |
it by run and name, and a team waits until the servers its agents land on have room (one
|
| 398 |
server's KV cache holds about a dozen long agent contexts)."""
|
| 399 |
|
|
@@ -436,7 +436,7 @@ def live_run(root: Path, tag: str, tree: int, n: int) -> tuple[str, list[str] |
|
|
| 436 |
"""The run of a team that a stopped driver launched and whose controller is still there,
|
| 437 |
with its URLs (it keeps them); else the team's first run name and None."""
|
| 438 |
for spec in sorted((root / "src").glob(f"{tag}maze-t{tree:02d}-n{n:02d}*/spec.yaml")):
|
| 439 |
-
if job_state(f"
|
| 440 |
return spec.parent.name, yaml.safe_load(spec.read_text())["inference"]["urls"]
|
| 441 |
return f"{tag}maze-t{tree:02d}-n{n:02d}", None
|
| 442 |
|
|
@@ -494,7 +494,7 @@ def main(argv=None) -> int:
|
|
| 494 |
parser.add_argument("--cpus-per-agent", type=int, default=1,
|
| 495 |
help="worker CPUs (and so memory, at 1900 MB each) per agent")
|
| 496 |
parser.add_argument("--memory-ladder", help="ROTATE,DRAIN,PREEMPT: the workers' memory "
|
| 497 |
-
"fractions (default:
|
| 498 |
parser.add_argument("--hint", action="store_true",
|
| 499 |
help="every team gets the protocol hint (team.py --hint)")
|
| 500 |
args = parser.parse_args(argv)
|
|
|
|
| 1 |
"""The s3-maze scaling sweep on the HF cluster, one command per model for the whole grid, run
|
| 2 |
+
from Legion's checkout (its environment, and its `.venv` for the workers):
|
| 3 |
|
| 4 |
+
uv run python <this dataset>/legion/sweep/sweep.py --urls http://<vllm node>:8000/v1 \\
|
| 5 |
--model Qwen/Qwen3.5-27B --tag q27- --revision <sha> [--trees 1-32] \\
|
| 6 |
+
[--agents 1,2,4,8,16] [--parallel 20] [--max-agents 64] [--root .legion/s3-maze-sweep/q27]
|
| 7 |
|
| 8 |
+
s3-aggregation's legion/sweep/sweep.py for the maze. Each (tree, N) team is its own legion run
|
| 9 |
(`compute: slurm`, podman agents on hopper-cpu, a local board on its one worker), from team.py's
|
| 10 |
cluster spec with the sweep's model on `urls`: the same board rules, loop, limits and move
|
| 11 |
budget at every N, and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per
|
| 12 |
+
maze service and two more (at least 4), at 1900 MB per CPU. Per team: `legion init`,
|
| 13 |
+
`legion launch`, then wait until the first agent's exit stops the run (and every Trial is
|
| 14 |
+
graded) or the loop is done and the agents are idle; `legion stop --release` (which grades the
|
| 15 |
Trials of a run nobody won, and ends the controller in either case); then eval/metrics.py's row
|
| 16 |
plus the wall time and the tree's exit branch go to `<root>/rows.jsonl`.
|
| 17 |
|
| 18 |
A run counts only when its worker started within WAIT_LIMIT of its launch (the loop's time
|
| 19 |
+
counts from the launch), on one worker incarnation (legion#121), with its controller kept and
|
| 20 |
nothing missing (every agent's reward and move log, the board export). Anything else is the
|
| 21 |
infrastructure's, so the team runs again as `<task>-rK` and the attempt goes to
|
| 22 |
`rows-discarded.jsonl`; what the model does (no move, no post, no exit) is a result. A team with
|
|
|
|
| 51 |
import yaml
|
| 52 |
from huggingface_hub import HfApi, get_token
|
| 53 |
|
| 54 |
+
from legion.models import Inference
|
| 55 |
|
| 56 |
HERE = Path(__file__).resolve().parent
|
| 57 |
DATASET_DIR = HERE.parents[1]
|
| 58 |
+
REPO = Path.cwd() # Legion's checkout
|
| 59 |
SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")
|
| 60 |
lock, init_lock = threading.Lock(), threading.Semaphore(4)
|
| 61 |
LOST, GONE = "controller lost", "no controller left"
|
|
|
|
| 95 |
return out
|
| 96 |
|
| 97 |
|
| 98 |
+
def legion(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess:
|
| 99 |
+
env = {**os.environ, "LEGION_RUN_DIR": str(run_dir)}
|
| 100 |
env.pop("VIRTUAL_ENV", None)
|
| 101 |
+
return subprocess.run([str(Path(sys.executable).with_name("legion")), *args], cwd=REPO,
|
| 102 |
env=env, capture_output=True, text=True, timeout=timeout, check=False)
|
| 103 |
|
| 104 |
|
|
|
|
| 173 |
|
| 174 |
|
| 175 |
def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str:
|
| 176 |
+
"""Poll `legion status` until the first exit stopped the run and its Trials are graded
|
| 177 |
('success'), or the loop is done and every agent is idle ('done'): or why not. A controller
|
| 178 |
that stops answering and isn't running (a spot reclaim requeued it, or it is gone) is LOST."""
|
| 179 |
deadline, unanswered, stopped = time.monotonic() + timeout, 0, None
|
|
|
|
| 184 |
if (launches and not any((run_dir / "logs").glob("*-agent-w*.out"))
|
| 185 |
and time.time() - min(p.stat().st_mtime for p in launches) > WAIT_LIMIT + 60):
|
| 186 |
return f"worker not started {WAIT_LIMIT + 60} s after its launch"
|
| 187 |
+
status = legion(run_dir, "status", task, timeout=120)
|
| 188 |
text = status.stdout
|
| 189 |
unanswered = unanswered + 1 if status.returncode != 0 else 0
|
| 190 |
+
if unanswered >= 3 and job_state(f"legion-ctl-{task}") != "RUNNING":
|
| 191 |
return LOST
|
| 192 |
if re.search(r"crashloop|launch_refused", text):
|
| 193 |
return "worker failed: " + " ".join(text.split())[:300]
|
|
|
|
| 204 |
|
| 205 |
|
| 206 |
def release(run_dir: Path, name: str) -> bool:
|
| 207 |
+
"""`legion stop --release`: drains (and so grades) a run nobody won and ends its
|
| 208 |
controller; then make sure no job of the run is left."""
|
| 209 |
+
out = legion(run_dir, "stop", name, "--release")
|
| 210 |
# once the worker is gone its results are on the shared disk: a controller still up a
|
| 211 |
# minute later (it sometimes outlives the release) only holds the team's slot, and SIGTERM
|
| 212 |
# makes it push its state and exit
|
| 213 |
+
for job, wait in ((f"{name}-agent-w0000", 900), (f"legion-ctl-{name}", 60)):
|
| 214 |
for _ in range(wait // 10): # a draining worker is still grading its Trials
|
| 215 |
if not job_state(job):
|
| 216 |
break
|
|
|
|
| 231 |
# a previous driver launched it and stopped before its row: finish it from here (its
|
| 232 |
# time cap counts from its own start, cluster.env's), or, with its controller gone,
|
| 233 |
# score what it left
|
| 234 |
+
alive = bool(job_state(f"legion-ctl-{name}"))
|
| 235 |
say(name, "adopting the run a previous driver launched" + ("" if alive else
|
| 236 |
" (no controller left)"))
|
| 237 |
return finish(args, run_dir, name, tree, n, (run_dir / "cluster.env").stat().st_mtime,
|
|
|
|
| 246 |
log.parent.mkdir(parents=True, exist_ok=True)
|
| 247 |
for tries in range(6): # its checks probe the model servers, which may be busy
|
| 248 |
with init_lock: # a few at a time: many at once race on the bucket's write check
|
| 249 |
+
init = legion(run_dir, "init", str(run_dir), "--from", str(src), "--profile",
|
| 250 |
str(profile(root)), "--secrets", str(secrets))
|
| 251 |
log.write_text(init.stdout + init.stderr)
|
| 252 |
if init.returncode == 0:
|
|
|
|
| 257 |
say(name, "init failed 6 times:", failed or init.stdout[-300:], "(log:", log, ")")
|
| 258 |
return None
|
| 259 |
say(name, "launching")
|
| 260 |
+
launch = legion(run_dir, "launch", str(run_dir / "experiment"))
|
| 261 |
if launch.returncode != 0:
|
| 262 |
say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:])
|
| 263 |
return finish(args, run_dir, name, tree, n, started, "launch")
|
|
|
|
| 271 |
why = why or wait_done(run_dir, name, n, max(0.0, args.team_timeout - (time.time() - started)))
|
| 272 |
if why == LOST: # nothing to release: end its jobs, and the team runs again
|
| 273 |
say(name, "controller lost (spot reclaim?): cancelling its jobs")
|
| 274 |
+
for job in (f"legion-ctl-{name}", f"{name}-agent-w0000"):
|
| 275 |
subprocess.run(["scancel", "-n", job], check=False)
|
| 276 |
released = False
|
| 277 |
elif why == GONE: # its rewards and export are on disk, or it doesn't count
|
|
|
|
| 284 |
"model": args.model, "tree": tree, "exit_branch": exit_branch(tree),
|
| 285 |
"wall_s": round(ended - started, 1), "outcome": why, "released": released,
|
| 286 |
# each launch of the worker slot writes one env file: more than one is a relaunch or a
|
| 287 |
+
# preemption, whose results a later incarnation overwrites (legion#121)
|
| 288 |
"incarnations": len(list((run_dir / "launch").glob("*.env"))),
|
| 289 |
"worker_wait_s": worker_wait(run_dir),
|
| 290 |
"thrashed_min": thrashed_minutes(run_dir, n, started, ended),
|
|
|
|
| 350 |
slots: "Slots", held: dict) -> dict | None:
|
| 351 |
"""A team, run again (as `<task>-rK`) until its run counts. `held["run"]` is the run name its
|
| 352 |
server capacity is reserved under: each attempt moves the reservation to its own name, since
|
| 353 |
+
legion hashes agents by run and name (a rerun's agents land on other servers)."""
|
| 354 |
task = f"{args.tag}maze-t{tree:02d}-n{n:02d}"
|
| 355 |
row = None
|
| 356 |
for reruns in range(args.max_reruns + 1):
|
| 357 |
name = task if reruns == 0 else f"{task}-r{reruns}"
|
| 358 |
if name != held["run"] and (not (root / "runs" / name).exists()
|
| 359 |
+
or job_state(f"legion-ctl-{name}")):
|
| 360 |
slots.give(n, held["run"], urls) # a finished attempt is only scored again: keep
|
| 361 |
held["run"] = name
|
| 362 |
+
slots.take(n, name, urls if job_state(f"legion-ctl-{name}") else None)
|
| 363 |
row = attempt(args, root, secrets, tree, n, name, urls)
|
| 364 |
if row is None:
|
| 365 |
return None
|
|
|
|
| 383 |
|
| 384 |
|
| 385 |
def agents_on(urls: list[str], n: int, run: str) -> Counter:
|
| 386 |
+
"""How many of run `run`'s agents (agent-001 .. agent-00N) call each server: legion hashes
|
| 387 |
+
each agent's run and name over the URLs (Inference.endpoint_for, legion#129), so teams on one
|
| 388 |
shared list spread over its servers."""
|
| 389 |
block = Inference(urls=urls)
|
| 390 |
return Counter(block.endpoint_for(run, f"agent-{k:03d}") for k in range(1, n + 1))
|
|
|
|
| 393 |
class Slots:
|
| 394 |
"""At most `parallel` teams, `max_agents` agents and `per_server` agents per model server
|
| 395 |
(`<root>/max_agents` and `<root>/per_server` override them while the driver runs) in flight,
|
| 396 |
+
granted in order. Every team gets the whole shared list; legion (#129) spreads its agents over
|
| 397 |
it by run and name, and a team waits until the servers its agents land on have room (one
|
| 398 |
server's KV cache holds about a dozen long agent contexts)."""
|
| 399 |
|
|
|
|
| 436 |
"""The run of a team that a stopped driver launched and whose controller is still there,
|
| 437 |
with its URLs (it keeps them); else the team's first run name and None."""
|
| 438 |
for spec in sorted((root / "src").glob(f"{tag}maze-t{tree:02d}-n{n:02d}*/spec.yaml")):
|
| 439 |
+
if job_state(f"legion-ctl-{spec.parent.name}"):
|
| 440 |
return spec.parent.name, yaml.safe_load(spec.read_text())["inference"]["urls"]
|
| 441 |
return f"{tag}maze-t{tree:02d}-n{n:02d}", None
|
| 442 |
|
|
|
|
| 494 |
parser.add_argument("--cpus-per-agent", type=int, default=1,
|
| 495 |
help="worker CPUs (and so memory, at 1900 MB each) per agent")
|
| 496 |
parser.add_argument("--memory-ladder", help="ROTATE,DRAIN,PREEMPT: the workers' memory "
|
| 497 |
+
"fractions (default: legion's 0.75,0.85,0.93)")
|
| 498 |
parser.add_argument("--hint", action="store_true",
|
| 499 |
help="every team gets the protocol hint (team.py --hint)")
|
| 500 |
args = parser.parse_args(argv)
|
{flock → legion}/team.md
RENAMED
|
File without changes
|
{flock → legion}/team.py
RENAMED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
-
"""Write the
|
| 2 |
|
| 3 |
-
uv run python <this dataset>/
|
| 4 |
|
| 5 |
writes `out/maze-t07-n04/spec.yaml` next to this script (or `--out DIR`) from
|
| 6 |
spec.template.yaml: the tree `maze-t07` at `--revision` (default: the dataset's head on the
|
|
@@ -20,7 +20,7 @@ from pathlib import Path
|
|
| 20 |
import yaml
|
| 21 |
from huggingface_hub import HfApi
|
| 22 |
|
| 23 |
-
from
|
| 24 |
|
| 25 |
HERE = Path(__file__).resolve().parent
|
| 26 |
DATASET = "HuggingFaceSwarms/s3-maze"
|
|
@@ -74,7 +74,7 @@ def pinned(revision: str | None) -> str:
|
|
| 74 |
|
| 75 |
|
| 76 |
def main(argv=None) -> int:
|
| 77 |
-
parser = argparse.ArgumentParser(description="Write one s3-maze team's
|
| 78 |
parser.add_argument("--tree", type=int, required=True, choices=TREES)
|
| 79 |
parser.add_argument("--agents", type=int, required=True, choices=SIZES)
|
| 80 |
parser.add_argument("--where", choices=("cluster", "docker"), default="cluster")
|
|
@@ -90,7 +90,7 @@ def main(argv=None) -> int:
|
|
| 90 |
if args.hint:
|
| 91 |
shutil.copyfile(HERE / "team.md", out / "team.md")
|
| 92 |
spec["team_file"] = "team.md"
|
| 93 |
-
header = (f"# {team} ({args.where}), written by {DATASET}'s
|
| 94 |
"spec.template.yaml: edit the template, not this file.\n")
|
| 95 |
(out / "spec.yaml").write_text(header + yaml.safe_dump(spec, sort_keys=False, width=100))
|
| 96 |
print(out / "spec.yaml")
|
|
|
|
| 1 |
+
"""Write the Legion spec for one s3-maze team, from Legion's checkout (it needs Legion):
|
| 2 |
|
| 3 |
+
uv run python <this dataset>/legion/team.py --tree 7 --agents 4 [--where cluster|docker]
|
| 4 |
|
| 5 |
writes `out/maze-t07-n04/spec.yaml` next to this script (or `--out DIR`) from
|
| 6 |
spec.template.yaml: the tree `maze-t07` at `--revision` (default: the dataset's head on the
|
|
|
|
| 20 |
import yaml
|
| 21 |
from huggingface_hub import HfApi
|
| 22 |
|
| 23 |
+
from legion.models import load_spec_yaml
|
| 24 |
|
| 25 |
HERE = Path(__file__).resolve().parent
|
| 26 |
DATASET = "HuggingFaceSwarms/s3-maze"
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
def main(argv=None) -> int:
|
| 77 |
+
parser = argparse.ArgumentParser(description="Write one s3-maze team's Legion spec.")
|
| 78 |
parser.add_argument("--tree", type=int, required=True, choices=TREES)
|
| 79 |
parser.add_argument("--agents", type=int, required=True, choices=SIZES)
|
| 80 |
parser.add_argument("--where", choices=("cluster", "docker"), default="cluster")
|
|
|
|
| 90 |
if args.hint:
|
| 91 |
shutil.copyfile(HERE / "team.md", out / "team.md")
|
| 92 |
spec["team_file"] = "team.md"
|
| 93 |
+
header = (f"# {team} ({args.where}), written by {DATASET}'s legion/team.py from "
|
| 94 |
"spec.template.yaml: edit the template, not this file.\n")
|
| 95 |
(out / "spec.yaml").write_text(header + yaml.safe_dump(spec, sort_keys=False, width=100))
|
| 96 |
print(out / "spec.yaml")
|